"use client";

import * as React from "react";

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

import {
  DataTablePagination,
  DataTableShell,
  downloadCsv,
  useDebouncedValue,
} from "@/app/dashboard/_components/data-table";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { TableCell } from "@/components/ui/table";

import { uniqueIsinColumns } from "./columns";
import {
  buildUniqueIsinHref,
  DEFAULT_PAGE_SIZE,
  type UniqueIsinRouteState,
} from "./constants";
import type { UniqueIsinFilters, UniqueIsinRow } from "./schema";
import { formatPlainAmount } from "@/lib/format/numbers";

type Props = {
  data: UniqueIsinRow[];
  filters: UniqueIsinFilters;
  totalCount: number;
  page: number;
  pageSize: number;
  pageCount: number;
};

export function UniqueIsinTable({
  data,
  filters,
  totalCount,
  page,
  pageSize,
  pageCount,
}: Props) {
  const router = useRouter();
  const [isinDraft, setIsinDraft] = React.useState(filters.isin);
  const debouncedIsin = useDebouncedValue(isinDraft);

  const navigate = React.useCallback(
    (
      next: Partial<UniqueIsinRouteState>,
      options?: { replace?: boolean },
    ) => {
      const href = buildUniqueIsinHref({
        isin: next.isin ?? filters.isin,
        isParentIsin: next.isParentIsin ?? filters.isParentIsin,
        isIsin: next.isIsin ?? filters.isIsin,
        emptyPrice: next.emptyPrice ?? filters.emptyPrice,
        page: next.page ?? page,
        pageSize: next.pageSize ?? pageSize,
      });

      if (options?.replace) {
        router.replace(href, { scroll: false });
        return;
      }

      router.push(href, { scroll: false });
    },
    [
      filters.emptyPrice,
      filters.isIsin,
      filters.isParentIsin,
      filters.isin,
      page,
      pageSize,
      router,
    ],
  );

  React.useEffect(() => {
    setIsinDraft(filters.isin);
  }, [filters.isin]);

  React.useEffect(() => {
    const normalizedIsin = debouncedIsin.trim();
    if (normalizedIsin === filters.isin) {
      return;
    }

    navigate(
      {
        isin: normalizedIsin,
        page: 1,
      },
      { replace: true },
    );
  }, [debouncedIsin, filters.isin, navigate]);

  const pagination = React.useMemo<PaginationState>(
    () => ({
      pageIndex: Math.max(page - 1, 0),
      pageSize,
    }),
    [page, pageSize],
  );

  const table = useReactTable({
    data,
    columns: uniqueIsinColumns,
    state: { pagination },
    pageCount,
    manualPagination: true,
    onPaginationChange: (updater) => {
      const next = typeof updater === "function" ? updater(pagination) : updater;
      const nextPageSize = next.pageSize > 0 ? next.pageSize : pageSize;
      const nextPage = nextPageSize !== pageSize ? 1 : Math.max(next.pageIndex + 1, 1);

      navigate({
        page: nextPage,
        pageSize: nextPageSize,
      });
    },
    getCoreRowModel: getCoreRowModel(),
    getRowId: (row) => String(row.id),
  });

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center gap-4 rounded-lg border bg-muted/20 px-4 py-3">
        <div className="flex items-center gap-2">
          <Checkbox
            id="filter_is_parent"
            checked={filters.isParentIsin}
            onCheckedChange={(checked) =>
              navigate({
                isParentIsin: checked === true,
                // Parent + non-parent filters are mutually exclusive.
                isIsin: checked === true ? false : filters.isIsin,
                page: 1,
              })
            }
          />
          <Label htmlFor="filter_is_parent" className="font-normal text-sm">
            Parent ISIN
          </Label>
        </div>
        <div className="flex items-center gap-2">
          <Checkbox
            id="filter_is_isin"
            checked={filters.isIsin}
            onCheckedChange={(checked) =>
              navigate({
                isIsin: checked === true,
                isParentIsin: checked === true ? false : filters.isParentIsin,
                page: 1,
              })
            }
          />
          <Label htmlFor="filter_is_isin" className="font-normal text-sm">
            ISIN
          </Label>
        </div>
        <div className="flex items-center gap-2">
          <Checkbox
            id="filter_empty_price"
            checked={filters.emptyPrice}
            onCheckedChange={(checked) =>
              navigate({
                emptyPrice: checked === true,
                page: 1,
              })
            }
          />
          <Label htmlFor="filter_empty_price" className="font-normal text-sm">
            Empty market price
          </Label>
        </div>
      </div>

      <div className="flex items-center justify-between gap-3">
        <p className="text-muted-foreground text-sm">
          {formatPlainAmount(totalCount)} ISIN{totalCount === 1 ? "" : "s"}
        </p>
        <Button
          type="button"
          variant="secondary"
          size="sm"
          onClick={() =>
            downloadCsv({
              filename: "unique-isin",
              headers: ["ISIN"],
              rows: data,
              toRow: (row) => [row.isin],
            })
          }
        >
          Export page
        </Button>
      </div>

      <DataTableShell
        table={table}
        columnCount={uniqueIsinColumns.length}
        emptyMessage="No unique ISIN records match your filters."
        renderFilterCell={(header) =>
          renderFilterCell(header, isinDraft, setIsinDraft)
        }
      />

      <DataTablePagination
        table={table}
        totalRows={totalCount}
        itemNoun="ISIN"
        idPrefix="unique-isin"
        pageSizes={[25, DEFAULT_PAGE_SIZE, 100]}
      />
    </div>
  );
}

function renderFilterCell(
  header: Header<UniqueIsinRow, unknown>,
  isinDraft: string,
  setIsinDraft: React.Dispatch<React.SetStateAction<string>>,
) {
  if (header.column.id !== "isin") {
    return null;
  }

  return (
    <TableCell key={header.id} className="p-2">
      <Input
        value={isinDraft}
        onChange={(event) => setIsinDraft(event.target.value)}
        placeholder="Search ISIN"
        className="h-8 bg-background font-mono text-xs"
      />
    </TableCell>
  );
}
