"use client";

import * as React from "react";
import type { ColumnDef } from "@tanstack/react-table";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { toast } from "sonner";

import { DashboardMasterRowActions } from "@/app/dashboard/_components/dashboard-master-row-actions";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { dashboardCsrfHeader } from "@/lib/csrf.client";

import { ActiveReviewBadge } from "@/components/shared/status-pill";
import type { SecurityTickerRow, SecurityTickerStatus } from "./schema";

const CHANGE_STATUS_HREF = "/dashboard/master/security-ticker/change-status";
const DELETE_HREF = "/dashboard/master/security-ticker/delete";

type PriorityHandlers = {
  priorities: Record<number, number>;
  onPriorityChange: (id: number, priority: number) => void;
};

function SecurityTickerActions({ row }: { row: SecurityTickerRow }) {
  const base = `/dashboard/master/security-ticker/${row.id}`;

  return (
    <DashboardMasterRowActions
      editHref={base}
      editAriaLabel="Update security ticker"
      deleteUrl={DELETE_HREF}
      entityId={row.id}
      entityName={row.masterName}
      entityLabel="security ticker"
      fallbackError="Security ticker could not be deleted."
      defaultSuccessMessage="Security ticker deleted."
    />
  );
}

function TickerNameCell({ row }: { row: SecurityTickerRow }) {
  const router = useRouter();
  const [pendingStatus, setPendingStatus] = React.useState<SecurityTickerStatus | null>(null);
  const base = `/dashboard/master/security-ticker/${row.id}`;

  const changeStatus = async (status: SecurityTickerStatus) => {
    setPendingStatus(status);

    try {
      const response = await fetch(CHANGE_STATUS_HREF, {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
          ...dashboardCsrfHeader(),
        },
        body: JSON.stringify({ id: row.id, status }),
      });
      const data = (await response.json().catch(() => null)) as {
        status?: string;
        message?: string;
      } | null;

      if (!response.ok || data?.status !== "success") {
        throw new Error(data?.message ?? "Security ticker status could not be changed.");
      }

      toast.success(data.message ?? "Security ticker status changed");
      router.refresh();
    } catch (error) {
      toast.error(
        error instanceof Error ? error.message : "Security ticker status could not be changed.",
      );
    } finally {
      setPendingStatus(null);
    }
  };

  if (row.status !== "R") {
    return (
      <Link
        href={base}
        className="inline-flex rounded-md border bg-muted/50 px-2 py-0.5 font-mono font-bold text-sm uppercase tracking-wide text-primary hover:underline"
      >
        {row.masterName}
      </Link>
    );
  }

  return (
    <div className="space-y-2 min-w-[140px]">
      <Link
        href={base}
        className="inline-flex rounded-md border bg-muted/50 px-2 py-0.5 font-mono font-bold text-sm uppercase tracking-wide text-primary hover:underline"
      >
        {row.masterName}
      </Link>
      <p className="text-amber-800 text-xs font-medium">Under review</p>
      <div className="flex flex-wrap gap-1">
        <Button
          type="button"
          size="sm"
          variant="secondary"
          className="h-7 text-xs"
          disabled={pendingStatus !== null}
          onClick={() => changeStatus("A")}
        >
          {pendingStatus === "A" ? "Approving..." : "Approve"}
        </Button>
        <Button
          type="button"
          size="sm"
          variant="outline"
          className="h-7 text-xs"
          disabled={pendingStatus !== null}
          onClick={() => changeStatus("I")}
        >
          {pendingStatus === "I" ? "Saving..." : "Inactive"}
        </Button>
      </div>
    </div>
  );
}

function ParentNameCell({ row }: { row: SecurityTickerRow }) {
  if (row.parentMasterId == null) {
    return <span className="text-sm text-muted-foreground">-</span>;
  }

  const parentHref = `/dashboard/master/security-name/${row.parentMasterId}`;

  if (row.parentStatus !== "R") {
    return (
      <Link href={parentHref} className="text-sm text-primary hover:underline">
        {row.parentName}
      </Link>
    );
  }

  return (
    <div className="space-y-2 min-w-[180px]">
      <Link href={parentHref} className="text-sm text-primary hover:underline">
        {row.parentName}
      </Link>
      <p className="text-amber-800 text-xs font-medium">Parent under review</p>
      <div className="flex flex-wrap gap-1">
        <Button
          type="button"
          size="sm"
          variant="secondary"
          className="h-7 text-xs"
          onClick={() => toast.success(`"${row.parentName}" approved (mock)`)}
        >
          Approve
        </Button>
        <Button
          type="button"
          size="sm"
          variant="outline"
          className="h-7 text-xs"
          onClick={() => toast.info(`"${row.parentName}" marked inactive (mock)`)}
        >
          Inactive
        </Button>
      </div>
    </div>
  );
}

export function createSecurityTickerColumns({
  priorities,
  onPriorityChange,
}: PriorityHandlers): ColumnDef<SecurityTickerRow>[] {
  return [
    {
      accessorKey: "masterName",
      header: "Security ticker",
      cell: ({ row }) => <TickerNameCell row={row.original} />,
    },
    {
      accessorKey: "parentName",
      header: "Security name",
      cell: ({ row }) => <ParentNameCell row={row.original} />,
    },
    {
      accessorKey: "status",
      header: "Status",
      cell: ({ row }) => (
        <ActiveReviewBadge
          status={row.original.status}
          label={row.original.statusLabel}
        />
      ),
    },
    {
      id: "priority",
      header: "Priority",
      enableColumnFilter: false,
      cell: ({ row }) => {
        const id = row.original.id;
        const value = priorities[id] ?? row.original.priority;

        return (
          <Input
            type="number"
            min={0}
            className="h-8 w-14 bg-background text-center text-xs tabular-nums"
            value={value}
            onChange={(event) => {
              const parsed = Number(event.target.value);
              onPriorityChange(id, Number.isFinite(parsed) ? parsed : 0);
            }}
          />
        );
      },
    },
    {
      id: "options",
      header: () => <span className="block w-full text-right">Options</span>,
      cell: ({ row }) => <SecurityTickerActions row={row.original} />,
      enableSorting: false,
    },
  ];
}
