"use client"

import * as React from "react"
import type {
  DataTableAdvancedFilterField,
  DataTableFilterField,
} from "@/types/table"

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 "./vendor-regular-registrations-table-columns"
import { VendorRegularRegistrationsTableToolbarActions } from "./vendor-regular-registrations-table-toolbar-actions"
import { fetchVendorRegularRegistrations } from "../service"
import type { VendorRegularRegistration } from "@/config/vendorRegularRegistrationsColumnsConfig"

interface VendorRegularRegistrationsTableProps {
  promises: Promise<
    [
      Awaited<ReturnType<typeof fetchVendorRegularRegistrations>>,
    ]
  >
}

export function VendorRegularRegistrationsTable({ promises }: VendorRegularRegistrationsTableProps) {
  // Suspense로 받아온 데이터
  const [result] = React.use(promises)
  
  if (!result.success || !result.data) {
    throw new Error(result.error || "데이터를 불러오는데 실패했습니다.")
  }

  const data = result.data
  const pageCount = Math.ceil(data.length / 10) // 임시로 10개씩 페이징



  const columns = React.useMemo(
    () => getColumns(),
    []
  )

  const filterFields: DataTableFilterField<VendorRegularRegistration>[] = [
    { id: "companyName", label: "업체명" },
    { id: "businessNumber", label: "사업자번호" },
    { id: "status", label: "상태" },
  ]

  const advancedFilterFields: DataTableAdvancedFilterField<VendorRegularRegistration>[] = [
    { id: "companyName", label: "업체명", type: "text" },
    { id: "businessNumber", label: "사업자번호", type: "text" },
    { id: "potentialCode", label: "잠재코드", type: "text" },
    { id: "representative", label: "대표자명", type: "text" },
    { 
      id: "status", 
      label: "상태", 
      type: "select",
      options: [
        { label: "실사통과", value: "audit_pass" },
        { label: "CP등록", value: "cp_submitted" },
        { label: "CP검토", value: "cp_review" },
        { label: "CP완료", value: "cp_finished" },
        { label: "조건충족", value: "approval_ready" },
        { label: "장기미등록", value: "pending_approval" },
      ]
    },
    { id: "assignedDepartment", label: "담당부서", type: "text" },
    { id: "assignedUser", label: "담당자", type: "text" },
    { id: "registrationRequestDate", label: "등록요청일", type: "date" },
  ]

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

  return (
    <>
      <DataTable
        table={table}
      >
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
        >
          <VendorRegularRegistrationsTableToolbarActions table={table} />
        </DataTableAdvancedToolbar>
      </DataTable>
    </>
  )
}
