"use client";
import * as React from "react";
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 "./incoterms-table-columns";
import { incoterms } from "@/db/schema/procurementRFQ";
import { IncotermsTableToolbar } from "./incoterms-table-toolbar";
import { toast } from "sonner";
import { IncotermsEditSheet } from "./incoterms-edit-sheet";
import { Row } from "@tanstack/react-table";
import { getIncoterms } from "../service";

interface IncotermsTableProps {
  promises?: Promise<[{ data: typeof incoterms.$inferSelect[]; pageCount: number }] >;
}

export function IncotermsTable({ promises }: IncotermsTableProps) {
  const [rawData, setRawData] = React.useState<{ data: typeof incoterms.$inferSelect[]; pageCount: number }>({ data: [], pageCount: 0 });
  const [isEditSheetOpen, setIsEditSheetOpen] = React.useState(false);
  const [selectedRow, setSelectedRow] = React.useState<typeof incoterms.$inferSelect | null>(null);

  React.useEffect(() => {
    if (promises) {
      promises.then(([result]) => {
        setRawData(result);
      });
    } else {
      // fallback: 클라이언트에서 직접 fetch (CSR)
      (async () => {
        try {
          const result = await getIncoterms({
            page: 1,
            perPage: 10,
            search: "",
            sort: [{ id: "createdAt", desc: true }],
            filters: [],
            joinOperator: "and",
            flags: ["advancedTable"],
            code: "",
            description: "",
            isActive: ""
          });
          setRawData(result);
        } catch (error) {
          console.error("Error refreshing data:", error);
          toast.error("데이터를 불러오는 중 오류가 발생했습니다.");
        }
      })();
    }
  }, [promises]);

  const refreshData = React.useCallback(async () => {
    try {
      const result = await getIncoterms({
        page: 1,
        perPage: 10,
        search: "",
        sort: [{ id: "createdAt", desc: true }],
        filters: [],
        joinOperator: "and",
        flags: ["advancedTable"],
        code: "",
        description: "",
        isActive: ""
      });
      setRawData(result);
    } catch (error) {
      console.error("Error refreshing data:", error);
      toast.error("데이터를 불러오는 중 오류가 발생했습니다.");
    }
  }, []);

  const handleRowAction = async (action: { type: string; row: Row<typeof incoterms.$inferSelect> }) => {
    if (action.type === "edit") {
      setSelectedRow(action.row.original);
      setIsEditSheetOpen(true);
    }
  };

  const columns = React.useMemo(() => getColumns({ setRowAction: handleRowAction, onSuccess: refreshData }), [refreshData]);

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

  return (
    <>
      <DataTable table={table}>
        <DataTableAdvancedToolbar table={table} filterFields={[]} shallow={false}>
          <IncotermsTableToolbar onSuccess={refreshData} />
        </DataTableAdvancedToolbar>
      </DataTable>
      {isEditSheetOpen && selectedRow && (
        <IncotermsEditSheet
          open={isEditSheetOpen}
          onOpenChange={setIsEditSheetOpen}
          data={selectedRow}
          onSuccess={refreshData}
        />
      )}
    </>
  );
} 