"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { DataTable } from "@/components/data-table/data-table";
import { useDataTable } from "@/hooks/use-data-table";
import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar";
import type {
  DataTableAdvancedFilterField,
  DataTableRowAction,
} from "@/types/table"
import { getBasicContractTemplates} from "../service";
import { getColumns } from "./basic-contract-template-columns";
import { DeleteTemplatesDialog } from "./delete-basicContract-dialog";
import { UpdateTemplateSheet } from "./update-basicContract-sheet";
import { CreateRevisionDialog } from "./create-revision-dialog";
import { TemplateTableToolbarActions } from "./basicContract-table-toolbar-actions";
import { BasicContractTemplate } from "@/db/schema";

interface BasicTemplateTableProps {
  promises: Promise<
    [
      Awaited<ReturnType<typeof getBasicContractTemplates>>,
    ]
  >
}

export function BasicContractTemplateTable({ promises }: BasicTemplateTableProps) {
  const router = useRouter();
  const [rowAction, setRowAction] =
    React.useState<DataTableRowAction<BasicContractTemplate> | null>(null)
  const [{ data, pageCount }] =
    React.use(promises)
  
  // 컬럼 설정 - router를 전달
  const columns = React.useMemo(
    () => getColumns({ setRowAction, router }),
    [setRowAction, router]
  )

  // config 기반으로 필터 필드 설정
  const advancedFilterFields: DataTableAdvancedFilterField<BasicContractTemplate>[] = [
    { id: "templateName", label: "템플릿명", type: "text" },
    {
      id: "status", label: "상태", type: "select", options: [
        { label: "활성", value: "ACTIVE" },
        { label: "폐기", value: "DISPOSED" },
      ]
    },
    { id: "fileName", label: "파일명", type: "text" },
    { id: "createdAt", label: "생성일", type: "date" },
    { id: "updatedAt", label: "수정일", type: "date" },
  ];

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

  return (
    <>
       <DataTable table={table}>
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
        >
          <TemplateTableToolbarActions table={table} />
         </DataTableAdvancedToolbar>
      </DataTable>

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

      <UpdateTemplateSheet
        open={rowAction?.type === "update"}
        onOpenChange={() => setRowAction(null)}
        template={rowAction?.row.original ?? null}
      />

      <CreateRevisionDialog
        open={rowAction?.type === "createRevision"}
        onOpenChange={() => setRowAction(null)}
        baseTemplate={rowAction?.row.original ?? null}
        onSuccess={() => {
          setRowAction(null);
          router.refresh();
        }}
      />
     </>
   );
}