"use client";

import * as React from "react";

import {
  getCoreRowModel,
  getPaginationRowModel,
  useReactTable,
  type PaginationState,
  type RowSelectionState,
} from "@tanstack/react-table";
import { useRouter } from "next/navigation";
import { toast } from "sonner";

import { DataTablePagination, DataTableShell } from "@/app/dashboard/_components/data-table";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { isApiSuccess } from "@/lib/api-messages";
import { requestDashboardApi } from "@/lib/dashboard-api-client";
import { toastApiError } from "@/lib/toast-api-error";

import { createOptionsInvalidIsinColumns } from "./columns";
import type { OptionsInvalidIsinRow } from "./schema";

const BULK_HREF = "/dashboard/master-table/options-invalid-isin/override/bulk";
const ISO_ISIN_PATTERN = /^[A-Z]{2}[A-Z0-9]{9}[0-9]$/;

type Props = {
  data: OptionsInvalidIsinRow[];
};

export function OptionsInvalidIsinTable({ data }: Props) {
  const router = useRouter();
  const [pagination, setPagination] = React.useState<PaginationState>({
    pageIndex: 0,
    pageSize: 50,
  });
  const [rowSelection, setRowSelection] = React.useState<RowSelectionState>({});
  const [bulkIsin, setBulkIsin] = React.useState("");
  const [bulkBusy, setBulkBusy] = React.useState(false);
  const [confirmOpen, setConfirmOpen] = React.useState(false);

  const pageOffset = pagination.pageIndex * pagination.pageSize;

  const columns = React.useMemo(
    () => createOptionsInvalidIsinColumns(pageOffset),
    [pageOffset],
  );

  const table = useReactTable({
    data,
    columns,
    state: { pagination, rowSelection },
    onPaginationChange: setPagination,
    onRowSelectionChange: setRowSelection,
    enableRowSelection: true,
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getRowId: (row) => row.id,
  });

  const selectedRows = table.getSelectedRowModel().rows.map((row) => row.original);
  const selectedCount = selectedRows.length;
  const distinctUnderlyings = React.useMemo(() => {
    const names = new Set(
      selectedRows
        .map((row) => row.underlyingName.trim())
        .filter((name) => name !== ""),
    );
    return names.size;
  }, [selectedRows]);

  function requestBulkOverride() {
    if (selectedCount === 0 || bulkBusy) return;

    const realUnderlyingIsin = bulkIsin.trim().toUpperCase();
    if (!ISO_ISIN_PATTERN.test(realUnderlyingIsin)) {
      toast.error("Enter a valid 12-character ISO ISIN.");
      return;
    }
    if (selectedCount > 50) {
      toast.error("Maximum 50 options per bulk override.");
      return;
    }

    setConfirmOpen(true);
  }

  async function applyBulkOverride() {
    if (selectedCount === 0 || bulkBusy) return;

    const realUnderlyingIsin = bulkIsin.trim().toUpperCase();
    if (!ISO_ISIN_PATTERN.test(realUnderlyingIsin)) {
      toast.error("Enter a valid 12-character ISO ISIN.");
      return;
    }

    setConfirmOpen(false);
    setBulkBusy(true);
    try {
      const data = await requestDashboardApi<{
        status?: string;
        message?: string;
        data?: { updated?: number; failed?: number };
      }>({
        url: BULK_HREF,
        method: "POST",
        body: {
          realUnderlyingIsin,
          items: selectedRows.map((row) => ({
            stockId: row.stockId > 0 ? row.stockId : undefined,
            oldUnderlier: row.underlier,
            oldParentIsin: row.parentIsin,
            fType: row.fType || undefined,
            mDate: row.mDate || undefined,
            tOo: row.tOo || undefined,
            tOt: row.tOt || undefined,
            price: row.price || undefined,
          })),
        },
        fallbackError: "Could not bulk override option ISINs.",
        validate: (payload) => isApiSuccess(payload),
      });

      toast.success(
        data.message ||
          `Overrode ${data.data?.updated ?? selectedCount} option underlier(s).`,
      );
      setRowSelection({});
      setBulkIsin("");
      router.refresh();
    } catch (error) {
      toastApiError(error, "Could not bulk override option ISINs.");
    } finally {
      setBulkBusy(false);
    }
  }

  const realUnderlyingIsin = bulkIsin.trim().toUpperCase();

  return (
    <div className="space-y-4">
      <div className="flex flex-col gap-3 rounded-lg border bg-muted/20 px-4 py-3 sm:flex-row sm:flex-wrap sm:items-center">
        <p className="text-muted-foreground text-sm whitespace-nowrap">
          {selectedCount > 0 ? `${selectedCount} selected` : "Select rows"}
        </p>
        <Input
          className="h-9 max-w-xs font-mono uppercase"
          placeholder="Real underlying ISIN"
          value={bulkIsin}
          disabled={bulkBusy || selectedCount === 0}
          onChange={(event) => setBulkIsin(event.target.value)}
          autoComplete="off"
        />
        <Button
          type="button"
          size="sm"
          disabled={bulkBusy || selectedCount === 0 || bulkIsin.trim() === ""}
          onClick={requestBulkOverride}
        >
          {bulkBusy ? "Updating…" : "Override selected"}
        </Button>
        <Button
          type="button"
          variant="ghost"
          size="sm"
          disabled={bulkBusy || selectedCount === 0}
          onClick={() => setRowSelection({})}
        >
          Clear
        </Button>
        {selectedCount > 0 && distinctUnderlyings > 1 ? (
          <p className="text-amber-700 text-xs dark:text-amber-400">
            Selection spans {distinctUnderlyings} underlyings — same ISIN applies to all.
          </p>
        ) : null}
      </div>

      <DataTableShell
        table={table}
        columnCount={columns.length}
        emptyMessage="No records found."
        renderFilterCell={() => null}
      />

      <DataTablePagination
        table={table}
        totalRows={data.length}
        itemNoun="option"
        idPrefix="options-invalid-isin"
      />

      <AlertDialog open={confirmOpen} onOpenChange={setConfirmOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              Override {selectedCount} option{selectedCount === 1 ? "" : "s"}?
            </AlertDialogTitle>
            <AlertDialogDescription>
              Map selected underlier(s) to{" "}
              <span className="font-mono font-medium text-foreground">
                {realUnderlyingIsin || "—"}
              </span>
              . This regenerates parent_isin and rewrites temp, transactions, and market
              rows, and saves an Underlying Alias for the next XML import.
              {distinctUnderlyings > 1
                ? ` Selection spans ${distinctUnderlyings} underlyings — the same ISIN applies to all.`
                : ""}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={bulkBusy}>Cancel</AlertDialogCancel>
            <AlertDialogAction
              disabled={bulkBusy}
              onClick={(event) => {
                event.preventDefault();
                void applyBulkOverride();
              }}
            >
              {bulkBusy ? "Updating…" : "Override"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
