"use client";

import * as React from "react";
import { DataTable } from "@/components/data-table/data-table";
import { Button } from "@/components/ui/button";
import { Plus, Loader2 } from "lucide-react";
import { useDataTable } from "@/hooks/use-data-table";
import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar";
import type {
  DataTableAdvancedFilterField,
  DataTableFilterField,
  DataTableRowAction,
} from "@/types/table"
import { toast } from "sonner";
import { getColumns } from "./basic-contract-columns";
import { getBasicContracts } from "../service";
import { BasicContractTemplateStatsView } from "@/db/schema";
import { BasicContractTableToolbarActions } from "./basicContract-table-toolbar-actions";
import { useRouter } from "next/navigation"

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

export function BasicContractsTable({ promises }: BasicTemplateTableProps) {

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

  const [{ data, pageCount }] =
    React.use(promises)

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

  // config 기반으로 필터 필드 설정
  const advancedFilterFields: DataTableAdvancedFilterField<BasicContractTemplateStatsView>[] = [
    { id: "templateName", label: "템플릿명", type: "text" },
    { id: "revision", label: "리비전", type: "number" },
    { id: "validityPeriod", label: "유효기간(개월)", type: "number" },
    { id: "totalSentCount", label: "발송건수", type: "number" },
    { id: "overdueCount", label: "지연건수", type: "number" },
    { id: "unsignedCount", label: "미서명건수", type: "number" },
    { id: "legalRequestCount", label: "법무요청건수", type: "number" },
    { id: "legalCompletedCount", label: "법무완료건수", type: "number" },
    { id: "contractCompletedCount", label: "계약완료건수", type: "number" },
    { id: "rejectedCount", label: "거절건수", type: "number" },
    { id: "avgProcessingDays", label: "평균처리일", type: "number" },
    { id: "templateCreatedAt", label: "템플릿 생성일", type: "date" },
    { id: "lastActivityDate", label: "최근활동일", type: "date" },
  ];

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

  return (
    <>

      <DataTable table={table}>
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
        >
          <BasicContractTableToolbarActions table={table} />

        </DataTableAdvancedToolbar>
      </DataTable>

    </>

  );
} 