"use client"

import * as React from "react"
import type {
  DataTableAdvancedFilterField,
  DataTableFilterField,
  DataTableRowAction,
} from "@/types/table"

import { toSentenceCase } from "@/lib/utils"
import { useDataTable } from "@/hooks/use-data-table"
import { DataTable } from "@/components/data-table/data-table"
import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"
import { getColumns } from "./rfq-history-table-columns"
import { getRfqHistory } from "../service"
import { RfqHistoryTableToolbarActions } from "./rfq-history-table-toolbar-actions"
import { RfqItemsTableDialog } from "./rfq-items-table-dialog"
import { getRFQStatusIcon } from "@/lib/tasks/utils"
import { TooltipProvider } from "@/components/ui/tooltip"

export interface RfqHistoryRow {
  id: number;
  rfqCode: string | null;
  projectCode: string | null;
  projectName: string | null;
  description: string | null;
  dueDate: Date;
  status: "DRAFT" | "PUBLISHED" | "EVALUATION" | "AWARDED";
  vendorStatus: string;
  totalAmount: number | null;
  currency: string | null;
  leadTime: string | null;
  itemCount: number;
  tbeResult: string | null;
  cbeResult: string | null;
  createdAt: Date;
  items: {
    rfqId: number;
    id: number;
    itemCode: string;
    description: string | null;
    quantity: number | null;
    uom: string | null;
  }[];
}

interface RfqHistoryTableProps {
  promises: Promise<
    [
      Awaited<ReturnType<typeof getRfqHistory>>,
    ]
  >
}

export function VendorRfqHistoryTable({ promises }: RfqHistoryTableProps) {
  const [{ data, pageCount }] = React.use(promises)

  const [rowAction, setRowAction] = React.useState<DataTableRowAction<RfqHistoryRow> | null>(null)

  const [itemsModalOpen, setItemsModalOpen] = React.useState(false);
  const [selectedRfq, setSelectedRfq] = React.useState<RfqHistoryRow | null>(null);

  const openItemsModal = React.useCallback((rfqId: number) => {
    const rfq = data.find(r => r.id === rfqId);
    if (rfq) {
      setSelectedRfq(rfq);
      setItemsModalOpen(true);
    }
  }, [data]);

  const columns = React.useMemo(() => getColumns({
    setRowAction,
    openItemsModal,
  }), [setRowAction, openItemsModal]);

  const filterFields: DataTableFilterField<RfqHistoryRow>[] = [
    {
      id: "rfqCode",
      label: "RFQ Code",
      placeholder: "Filter RFQ Code...",
    },
    {
      id: "status",
      label: "Status",
      options: ["DRAFT", "PUBLISHED", "EVALUATION", "AWARDED"].map((status) => ({
        label: toSentenceCase(status),
        value: status,
        icon: getRFQStatusIcon(status),
      })),
    },
    {
      id: "vendorStatus",
      label: "Vendor Status",
      placeholder: "Filter Vendor Status...",
    }
  ]

  const advancedFilterFields: DataTableAdvancedFilterField<RfqHistoryRow>[] = [
    { id: "rfqCode", label: "RFQ Code", type: "text" },
    { id: "projectCode", label: "Project Code", type: "text" },
    { id: "projectName", label: "Project Name", type: "text" },
    { 
      id: "status", 
      label: "RFQ Status", 
      type: "multi-select",
      options: ["DRAFT", "PUBLISHED", "EVALUATION", "AWARDED"].map((status) => ({
        label: toSentenceCase(status),
        value: status,
        icon: getRFQStatusIcon(status),
      })),
    },
    { id: "vendorStatus", label: "Vendor Status", type: "text" },
    { id: "dueDate", label: "Due Date", type: "date" },
    { id: "createdAt", label: "Created At", type: "date" },
  ]

  const { table } = useDataTable({
    data,
    columns,
    pageCount,
    filterFields,
    enablePinning: true,
    enableAdvancedFilter: true,
    initialState: {
      sorting: [{ id: "createdAt", desc: true }],
      columnPinning: { right: ["actions"] },
    },
    getRowId: (originalRow) => String(originalRow.id),
    shallow: true,
    clearOnDefault: true,
  })

  return (
    <>
      <TooltipProvider>
        <DataTable
          table={table}
        >
          <DataTableAdvancedToolbar
            table={table}
            filterFields={advancedFilterFields}
            shallow={false}
          >
            <RfqHistoryTableToolbarActions table={table} />
          </DataTableAdvancedToolbar>
        </DataTable>

        <RfqItemsTableDialog
          open={itemsModalOpen}
          onOpenChange={setItemsModalOpen}
          items={selectedRfq?.items ?? []}
        />
      </TooltipProvider>
    </>
  )
}