"use client";
import * as React from "react";
import { useRouter } from "next/navigation";
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,
  DataTableFilterField,
  DataTableRowAction,
} from "@/types/table"
import { getColumns } from "./code-groups-table-columns";
import { DeleteCodeGroupsDialog } from "./delete-code-groups-dialog";
import { CodeGroupsEditSheet } from "./code-groups-edit-sheet";
import { CodeGroupsTableToolbarActions } from "./code-groups-table-toolbar";
import { codeGroups } from "@/db/schema/docu-list-rule";

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

export function CodeGroupsTable({ promises }: CodeGroupsTableProps) {
  const router = useRouter();
  const [rowAction, setRowAction] = React.useState<DataTableRowAction<typeof codeGroups.$inferSelect> | null>(null);

  const [{ data, pageCount }] = promises ? React.use(promises) : [{ data: [], pageCount: 0 }];

  const refreshData = React.useCallback(async () => {
    // 전체 페이지 새로고침 대신 router.refresh() 사용 (성능 개선)
    router.refresh();
  }, [router]);

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

  // 필터 필드 설정
  const filterFields: DataTableFilterField<typeof codeGroups.$inferSelect>[] = [];

  // 고급 필터 필드 설정
  const advancedFilterFields: DataTableAdvancedFilterField<typeof codeGroups.$inferSelect>[] = [
    { id: "groupId", label: "Group ID", type: "text" },
    { id: "description", label: "Description", type: "text" },
    { id: "codeFormat", label: "Code Format", type: "text" },
    {
      id: "controlType", label: "Control Type", type: "select", options: [
        { label: "Textbox", value: "textbox" },
        { label: "Combobox", value: "combobox" },
        { label: "Date", value: "date" },
        { label: "Number", value: "number" },
      ]
    },
    {
      id: "isActive", label: "Status", type: "select", options: [
        { label: "Active", value: "true" },
        { label: "Inactive", value: "false" },
      ]
    },
    { 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.groupId),
      shallow: false,
      clearOnDefault: true,
    })

  return (
    <>
      <DataTable table={table}>
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
        >
          <CodeGroupsTableToolbarActions table={table} onSuccess={refreshData} />
        </DataTableAdvancedToolbar>
      </DataTable>

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

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