"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 type {
  DataTableAdvancedFilterField,
  DataTableRowAction,
} from "@/types/table"
import { getPaymentTerms } from "../service";
import { getColumns } from "./payment-terms-table-columns";
import { DeletePaymentTermsDialog } from "./delete-payment-terms-dialog";
import { PaymentTermsEditSheet } from "./payment-terms-edit-sheet";
import { PaymentTermsTableToolbarActions } from "./payment-terms-table-toolbar";
import { paymentTerms } from "@/db/schema/procurementRFQ";
import { GetPaymentTermsSchema } from "../validations";

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

export function PaymentTermsTable({ promises }: PaymentTermsTableProps) {
  const [rawData, setRawData] = React.useState<{ data: typeof paymentTerms.$inferSelect[]; pageCount: number }>({ data: [], pageCount: 0 });
  const [rowAction, setRowAction] = React.useState<DataTableRowAction<typeof paymentTerms.$inferSelect> | null>(null);

  React.useEffect(() => {
    if (promises) {
      promises.then(([result]) => {
        setRawData(result);
      });
    } else {
      // fallback: 클라이언트에서 직접 fetch (CSR)
      (async () => {
        try {
          const result = await getPaymentTerms({
            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);
        }
      })();
    }
  }, [promises]);

  const fetchPaymentTerms = React.useCallback(async (params: Record<string, unknown>) => {
    try {
      const result = await getPaymentTerms(params as GetPaymentTermsSchema);
      return result;
    } catch (error) {
      console.error("Error fetching payment terms:", error);
      throw error;
    }
  }, []);

  const refreshData = React.useCallback(async () => {
    try {
      const result = await fetchPaymentTerms({
        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);
    }
  }, [fetchPaymentTerms]);

  // 컬럼 설정 - 외부 파일에서 가져옴
  const columns = React.useMemo(
    () => getColumns({ setRowAction }),
    [setRowAction]
  )

  // 고급 필터 필드 설정
  const advancedFilterFields: DataTableAdvancedFilterField<typeof paymentTerms.$inferSelect>[] = [
    { id: "code", label: "코드", type: "text" },
    {
      id: "isActive", label: "상태", type: "select", options: [
        { label: "활성", value: "true" },
        { label: "비활성", value: "false" },
      ]
    },
    { id: "description", label: "설명", type: "text" },
    { id: "createdAt", label: "생성일", type: "date" },
  ];

  const { table } = useDataTable({
      data: rawData.data,
      columns,
      pageCount: rawData.pageCount,
      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={advancedFilterFields}
        >
          <PaymentTermsTableToolbarActions table={table} onSuccess={refreshData} />
        </DataTableAdvancedToolbar>
      </DataTable>

      <DeletePaymentTermsDialog
        open={rowAction?.type === "delete"}
        onOpenChange={() => setRowAction(null)}
        paymentTerms={rowAction?.row.original ? [rowAction?.row.original] : []}
        showTrigger={false}
        onSuccess={() => {
          rowAction?.row.toggleSelected(false)
          refreshData()
        }}
      />

      <PaymentTermsEditSheet
        open={rowAction?.type === "update"}
        onOpenChange={() => setRowAction(null)}
        data={rowAction?.row.original ?? null}
        onSuccess={refreshData}
      />
    </>
  );
} 