"use client"

import React from "react"
import { DataTable } from "@/components/data-table/data-table"
import { ContactPossibleItemsTableToolbarActions } from "./contact-possible-items-table-toolbar-actions"
import { getColumns } from "./contact-possible-items-table-columns"
import { ContactPossibleItemDetail } from "../service"
import { DeleteContactPossibleItemsDialog } from "./delete-contact-possible-items-dialog"
import { useDataTable } from "@/hooks/use-data-table"
import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"
import { type DataTableAdvancedFilterField } from "@/types/table"

// 필터 필드 정의
const advancedFilterFields: DataTableAdvancedFilterField<ContactPossibleItemDetail>[] = [
  {
    id: "contactName",
    label: "담당자명",
    type: "text",
    placeholder: "담당자명으로 검색...",
  },
  {
    id: "vendorName", 
    label: "벤더명",
    type: "text",
    placeholder: "벤더명으로 검색...",
  },
  {
    id: "vendorCode",
    label: "벤더코드",
    type: "text", 
    placeholder: "벤더코드로 검색...",
  },
  {
    id: "itemCode",
    label: "아이템코드",
    type: "text",
    placeholder: "아이템코드로 검색...",
  },
  {
    id: "workType",
    label: "공종",
    type: "text",
    placeholder: "공종으로 검색...",
  },
]

interface ContactPossibleItemsTableProps {
  contactPossibleItemsPromise: Promise<{
    data: ContactPossibleItemDetail[]
    pageCount: number
    total: number
  }>
}

export function ContactPossibleItemsTable({
  contactPossibleItemsPromise,
}: ContactPossibleItemsTableProps) {
  const { data, pageCount, total } = React.use(contactPossibleItemsPromise)

  const [rowAction, setRowAction] = React.useState<any | null>(null)

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

  const { table } = useDataTable({
    data,
    columns,
    pageCount,
    rowCount: total,
  })

  return (
    <div className="w-full space-y-2.5 overflow-auto">
      {/* 메인 테이블 */}
      <DataTable table={table}>
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
        >
          <ContactPossibleItemsTableToolbarActions 
            table={table} 
          />
        </DataTableAdvancedToolbar>
      </DataTable>

      <DeleteContactPossibleItemsDialog
        open={rowAction?.type === "delete"}
        onOpenChange={() => setRowAction(null)}
        contactPossibleItems={
          rowAction?.type === "delete" && rowAction.row
            ? [rowAction.row.original]
            : []
        }
        showTrigger={false}
        onSuccess={() => setRowAction(null)}
      />
    </div>
  )
} 