"use client"

import * as React from "react"
import type {
  DataTableAdvancedFilterField,
  DataTableFilterField,
  DataTableRowAction,
} 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 { getChangeOrders } from "../service"
import { POADetail } from "@/db/schema/contract"
import { getColumns } from "./poa-table-columns"
import { PoaTableToolbarActions } from "./poa-table-toolbar-actions"

interface ItemsTableProps {
  promises: Promise<
    [
      Awaited<ReturnType<typeof getChangeOrders>>,
    ]
  >
}

export function ChangeOrderListsTable({ promises }: ItemsTableProps) {
  const [result] = React.use(promises)
  const { data, pageCount } = result
    
  const [rowAction, setRowAction] = 
    React.useState<DataTableRowAction<POADetail> | null>(null)
    
  // Handle row actions
  React.useEffect(() => {
    if (!rowAction) return
    
    if (rowAction.type === "items") {
      // Handle items view action
      setRowAction(null)
    }
  }, [rowAction])
  
  const columns = React.useMemo(
    () => getColumns({ setRowAction }),
    [setRowAction]
  )

  const filterFields: DataTableFilterField<POADetail>[] = [
    {
      id: "contractNo",
      label: "계약번호",
    },
    {
      id: "originalContractName",
      label: "계약명",
    },
    {
      id: "approvalStatus",
      label: "승인 상태",
    },
  ]

  const advancedFilterFields: DataTableAdvancedFilterField<POADetail>[] = [
    {
      id: "contractNo",
      label: "계약번호",
      type: "text",
    },
    {
      id: "originalContractName",
      label: "계약명",
      type: "text",
    },
    {
      id: "projectId",
      label: "프로젝트 ID",
      type: "number",
    },
    {
      id: "vendorId",
      label: "벤더 ID",
      type: "number",
    },
    {
      id: "originalStatus",
      label: "상태",
      type: "text",
    },
    {
      id: "deliveryTerms",
      label: "납품조건",
      type: "text",
    },
    {
      id: "deliveryDate",
      label: "납품기한",
      type: "date",
    },
    {
      id: "deliveryLocation",
      label: "납품장소",
      type: "text",
    },
    {
      id: "currency",
      label: "통화",
      type: "text",
    },
    {
      id: "totalAmount",
      label: "총 금액",
      type: "number",
    },
    {
      id: "discount",
      label: "할인",
      type: "number",
    },
    {
      id: "tax",
      label: "세금",
      type: "number",
    },
    {
      id: "shippingFee",
      label: "배송비",
      type: "number",
    },
    {
      id: "netTotal",
      label: "최종 금액",
      type: "number",
    },
    {
      id: "changeReason",
      label: "변경 사유",
      type: "text",
    },
    {
      id: "approvalStatus",
      label: "승인 상태",
      type: "text",
    },
    {
      id: "createdAt",
      label: "생성일",
      type: "date",
    },
    {
      id: "updatedAt",
      label: "수정일",
      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.id),
    shallow: false,
    clearOnDefault: true,
  })

  return (
    <>
      <DataTable
        table={table}
        className="h-[calc(100vh-12rem)]"
      >
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
        >
          <PoaTableToolbarActions table={table} />
        </DataTableAdvancedToolbar>
      </DataTable>
    </>
  )
} 