"use client";

import * as React from "react";

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

import {
  DataTablePagination,
  DataTableShell,
  useServerPagination,
  type ServerPaginationMeta,
} from "@/app/dashboard/_components/data-table";
import { useMasterListFilters } from "@/hooks/use-master-list-filters";
import { useDebouncedValue } from "@/hooks/use-debounced-value";
import { requestDashboardApi } from "@/lib/dashboard-api-client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { TableCell } from "@/components/ui/table";

import { createCommodityNameColumns } from "./columns";
import {
  COMMODITY_NAME_STATUS_OPTIONS,
  type CommodityNameFilters,
  type CommodityNameRow,
} from "./schema";
import { exportCommodityNameCsv } from "./export-csv";

const PRIORITY_SAVE_HREF = "/dashboard/master/commodity-name/priority";

type Props = {
  data: CommodityNameRow[];
  initialFilters: CommodityNameFilters;
  pagination: ServerPaginationMeta;
};

type TextDrafts = Pick<CommodityNameFilters, "masterName">;

function buildPriorityMap(rows: CommodityNameRow[]) {
  return Object.fromEntries(rows.map((row) => [row.id, String(row.priority)]));
}

export function CommodityNamesTable({
  data,
  initialFilters,
  pagination: serverPagination,
}: Props) {
  const router = useRouter();
  const { filters, setFilter } = useMasterListFilters(initialFilters, [
    "masterName",
    "status",
  ] as const);
  const [drafts, setDrafts] = React.useState<TextDrafts>({ masterName: filters.masterName });
  const committedTextRef = React.useRef<TextDrafts>({ masterName: filters.masterName });
  const prioritiesRef = React.useRef<Record<number, string>>(buildPriorityMap(data));
  const { pagination, onPaginationChange, totalCount } = useServerPagination(serverPagination);
  const debouncedMasterName = useDebouncedValue(drafts.masterName, 300);

  React.useEffect(() => {
    setDrafts((draft) => ({
      masterName:
        draft.masterName === committedTextRef.current.masterName ||
        draft.masterName === filters.masterName
          ? filters.masterName
          : draft.masterName,
    }));
    committedTextRef.current = {
      masterName: filters.masterName,
    };
  }, [filters.masterName]);

  React.useEffect(() => {
    prioritiesRef.current = buildPriorityMap(data);
  }, [data]);

  React.useEffect(() => {
    if (debouncedMasterName !== filters.masterName) {
      setFilter("masterName", debouncedMasterName);
    }
  }, [debouncedMasterName, filters.masterName, setFilter]);

  const onPriorityChange = React.useCallback((id: number, priority: string) => {
    prioritiesRef.current = { ...prioritiesRef.current, [id]: priority };
  }, []);

  const columns = React.useMemo(
    () => createCommodityNameColumns({ onPriorityChange }),
    [onPriorityChange],
  );

  const table = useReactTable({
    data,
    columns,
    state: { pagination },
    onPaginationChange,
    manualPagination: true,
    pageCount: serverPagination.pageCount,
    rowCount: totalCount,
    getCoreRowModel: getCoreRowModel(),
    getRowId: (row) => String(row.id),
  });

  const updateDraft = <K extends keyof TextDrafts>(key: K, value: TextDrafts[K]) => {
    setDrafts((prev) => ({ ...prev, [key]: value }));
  };

  const updateFilter = <K extends keyof CommodityNameFilters>(
    key: K,
    value: CommodityNameFilters[K],
  ) => {
    setFilter(key, value);
  };

  const handlePrioritySave = async () => {
    try {
      const response = await requestDashboardApi<{ message?: string }>({
        url: PRIORITY_SAVE_HREF,
        method: "POST",
        body: {
          priority: Object.fromEntries(
            Object.entries(prioritiesRef.current).map(([id, value]) => [
              id,
              Number.parseInt(value || "0", 10) || 0,
            ]),
          ),
        },
        fallbackError: "Commodity name priority could not be updated.",
      });
      toast.success(response.message ?? "Priority successfully updated!");
      router.refresh();
    } catch (error) {
      toast.error(
        error instanceof Error ? error.message : "Commodity name priority could not be updated.",
      );
    }
  };

  return (
    <div className="space-y-4">
      <div className="flex justify-end">
        <Button
          type="button"
          variant="secondary"
          size="sm"
          onClick={() => exportCommodityNameCsv(data)}
        >
          Export filtered
        </Button>
      </div>

      <DataTableShell
        table={table}
        columnCount={columns.length}
        emptyMessage="No commodity names match your filters."
        renderFilterCell={(header) =>
          renderFilterCell(header, filters, drafts, updateFilter, updateDraft)
        }
      />

      <DataTablePagination
        table={table}
        totalRows={totalCount}
        itemNoun="commodity name"
        idPrefix="commodity-names"
      />

      <div className="flex justify-end border-t pt-4">
        <Button type="button" onClick={handlePrioritySave}>
          Update priority
        </Button>
      </div>
    </div>
  );
}

function renderFilterCell(
  header: Header<CommodityNameRow, unknown>,
  filters: CommodityNameFilters,
  drafts: TextDrafts,
  updateFilter: <K extends keyof CommodityNameFilters>(
    key: K,
    value: CommodityNameFilters[K],
  ) => void,
  updateDraft: <K extends keyof TextDrafts>(key: K, value: TextDrafts[K]) => void,
) {
  const columnId = header.column.id;

  if (columnId === "masterName") {
    return (
      <TableCell key={header.id} className="p-2">
        <Input
          value={drafts.masterName}
          onChange={(event) => updateDraft("masterName", event.target.value)}
          placeholder="Commodity name"
          className="h-8 bg-background text-xs"
        />
      </TableCell>
    );
  }

  if (columnId === "status") {
    return (
      <TableCell key={header.id} className="p-2">
        <Select value={filters.status} onValueChange={(value) => updateFilter("status", value)}>
          <SelectTrigger className="h-8 bg-background text-xs">
            <SelectValue placeholder="Status" />
          </SelectTrigger>
          <SelectContent>
            {COMMODITY_NAME_STATUS_OPTIONS.map((option) => (
              <SelectItem key={option.value} value={option.value}>
                {option.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </TableCell>
    );
  }

  return null;
}
