"use client";

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

import {
  DataTablePagination,
  useDebouncedValue,
} from "@/app/dashboard/_components/data-table";
import { Input } from "@/components/ui/input";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { SETTINGS_INPUT_CLASS } from "@/components/settings/constants";
import { cn } from "@/lib/utils";

import { createBondMaturityColumns } from "./columns";
import {
  buildBondMaturityHref,
  DEFAULT_PAGE_SIZE,
} from "./constants";
import type { BondMaturityRow } from "./schema";
import { formatPlainAmount } from "@/lib/format/numbers";

type Props = {
  data: BondMaturityRow[];
  filters: {
    id: string;
    name: string;
    isin: string;
  };
  totalCount: number;
  page: number;
  pageSize: number;
  pageCount: number;
};

const filterInputClass = cn(SETTINGS_INPUT_CLASS, "h-8");

export function BondMaturityTable({
  data,
  filters,
  totalCount,
  page,
  pageSize,
  pageCount,
}: Props) {
  const router = useRouter();
  const [idDraft, setIdDraft] = React.useState(filters.id);
  const [nameDraft, setNameDraft] = React.useState(filters.name);
  const [isinDraft, setIsinDraft] = React.useState(filters.isin);
  const debouncedId = useDebouncedValue(idDraft);
  const debouncedName = useDebouncedValue(nameDraft);
  const debouncedIsin = useDebouncedValue(isinDraft);

  const navigate = React.useCallback(
    (
      next: {
        id?: string;
        name?: string;
        isin?: string;
        page?: number;
        pageSize?: number;
      },
      options?: { replace?: boolean },
    ) => {
      const href = buildBondMaturityHref({
        id: next.id ?? filters.id,
        name: next.name ?? filters.name,
        isin: next.isin ?? filters.isin,
        page: next.page ?? page,
        pageSize: next.pageSize ?? pageSize,
      });

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

      router.push(href, { scroll: false });
    },
    [filters.id, filters.isin, filters.name, page, pageSize, router],
  );

  React.useEffect(() => {
    setIdDraft(filters.id);
  }, [filters.id]);

  React.useEffect(() => {
    setNameDraft(filters.name);
  }, [filters.name]);

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

  React.useEffect(() => {
    const normalized = debouncedId.trim();
    if (normalized === filters.id) return;
    navigate({ id: normalized, page: 1 }, { replace: true });
  }, [debouncedId, filters.id, navigate]);

  React.useEffect(() => {
    const normalized = debouncedName.trim();
    if (normalized === filters.name) return;
    navigate({ name: normalized, page: 1 }, { replace: true });
  }, [debouncedName, filters.name, navigate]);

  React.useEffect(() => {
    const normalized = debouncedIsin.trim();
    if (normalized === filters.isin) return;
    navigate({ isin: normalized, page: 1 }, { replace: true });
  }, [debouncedIsin, filters.isin, navigate]);

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

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

  const table = useReactTable({
    data,
    columns,
    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) => row.id,
  });

  const start = totalCount === 0 ? 0 : (page - 1) * pageSize + 1;
  const end = Math.min(page * pageSize, totalCount);
  const headers = table.getHeaderGroups()[0]?.headers ?? [];

  return (
    <div className="space-y-4">
      <p className="text-sm text-muted-foreground">
        Displaying {start}–{end} of {formatPlainAmount(totalCount)} results.
      </p>
      <div className="overflow-x-auto rounded-lg border bg-card">
        <Table>
          <TableHeader>
            <TableRow className="bg-muted/40 hover:bg-muted/40">
              {headers.map((h) => (
                <TableHead key={h.id} className="h-10 px-3 whitespace-nowrap">
                  {flexRender(h.column.columnDef.header, h.getContext())}
                </TableHead>
              ))}
            </TableRow>
            <TableRow className="bg-muted/20 hover:bg-muted/20">
              {headers.map((h) => {
                const colId = h.column.id;
                if (colId === "id") {
                  return (
                    <TableHead key={h.id} className="px-3 py-2">
                      <Input
                        className={filterInputClass}
                        placeholder="Filter"
                        value={idDraft}
                        onChange={(e) => setIdDraft(e.target.value)}
                      />
                    </TableHead>
                  );
                }
                if (colId === "name") {
                  return (
                    <TableHead key={h.id} className="px-3 py-2">
                      <Input
                        className={filterInputClass}
                        placeholder="Filter"
                        value={nameDraft}
                        onChange={(e) => setNameDraft(e.target.value)}
                      />
                    </TableHead>
                  );
                }
                if (colId === "isin") {
                  return (
                    <TableHead key={h.id} className="px-3 py-2">
                      <Input
                        className={filterInputClass}
                        placeholder="Filter"
                        value={isinDraft}
                        onChange={(e) => setIsinDraft(e.target.value)}
                      />
                    </TableHead>
                  );
                }
                return <TableHead key={h.id} className="px-3 py-2" />;
              })}
            </TableRow>
          </TableHeader>
          <TableBody>
            {table.getRowModel().rows.length ? (
              table.getRowModel().rows.map((row) => (
                <TableRow key={row.id}>
                  {row.getVisibleCells().map((cell) => (
                    <TableCell key={cell.id} className="px-3 py-2.5">
                      {flexRender(cell.column.columnDef.cell, cell.getContext())}
                    </TableCell>
                  ))}
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell
                  colSpan={columns.length}
                  className="h-24 text-center text-muted-foreground"
                >
                  No results found.
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>
      <DataTablePagination
        table={table}
        totalRows={totalCount}
        itemNoun="record"
        idPrefix="bond-maturity"
        pageSizes={[10, 20, DEFAULT_PAGE_SIZE, 100]}
      />
    </div>
  );
}
