// vendor-quotations-table-last.tsx
"use client"

import * as React from "react"
import { 
  type DataTableAdvancedFilterField, 
  type DataTableFilterField, 
  type 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 { useRouter } from "next/navigation"
import { getColumns } from "./vendor-quotations-table-columns"
import { RfqAttachmentsDialog } from "./rfq-attachments-dialog";
import { RfqItemsDialog } from "../shared/rfq-items-dialog";
import { VendorQuotationView } from "@/db/schema"

interface VendorQuotationsTableLastProps {
  promises: Promise<[{ data: VendorQuotationView[], pageCount: number }]>
}

export function VendorQuotationsTableLast({ promises }: VendorQuotationsTableLastProps) {
  const [{ data, pageCount }] = React.use(promises)
  const router = useRouter()

  console.log(data,"VendorQuotationsTableLast")
  
  const [rowAction, setRowAction] = React.useState<DataTableRowAction<VendorQuotationView> | null>(null)
  
  // 테이블 컬럼
  const columns = React.useMemo(() => getColumns({
    setRowAction,
    router,
  }), [setRowAction, router])
  
  // 응답 상태별 카운트
  const statusCounts = React.useMemo(() => {
    return {
      notResponded: data.filter(q => q.displayStatus === "미응답").length,
      declined: data.filter(q => q.displayStatus === "불참").length,
      drafting: data.filter(q => q.displayStatus === "작성중").length,
      submitted: data.filter(q => q.displayStatus === "제출완료").length,
      revisionRequested: data.filter(q => q.displayStatus === "수정요청").length,
      confirmed: data.filter(q => q.displayStatus === "최종확정").length,
      cancelled: data.filter(q => q.displayStatus === "취소").length,
    }
  }, [data])
  
  // 필터 필드
  const filterFields: DataTableFilterField<VendorQuotationView>[] = [
    {
      id: "displayStatus",
      label: "상태",
      options: [
        { label: "미응답", value: "미응답", count: statusCounts.notResponded },
        { label: "불참", value: "불참", count: statusCounts.declined },
        { label: "작성중", value: "작성중", count: statusCounts.drafting },
        { label: "제출완료", value: "제출완료", count: statusCounts.submitted },
        { label: "수정요청", value: "수정요청", count: statusCounts.revisionRequested },
        { label: "최종확정", value: "최종확정", count: statusCounts.confirmed },
        { label: "취소", value: "취소", count: statusCounts.cancelled },
      ]
    },
    {
      id: "rfqCode",
      label: "RFQ 번호",
      placeholder: "RFQ 번호 검색...",
    },
  ]
  
  // 고급 필터 필드
  const advancedFilterFields: DataTableAdvancedFilterField<VendorQuotationView>[] = [
    {
      id: "rfqCode",
      label: "RFQ 번호",
      type: "text",
    },
    {
      id: "rfqTitle",
      label: "RFQ 제목",
      type: "text",
    },
    {
      id: "projectName",
      label: "프로젝트명",
      type: "text",
    },
    {
      id: "displayStatus",
      label: "상태",
      options: [
        { label: "미응답", value: "미응답", count: statusCounts.notResponded },
        { label: "불참", value: "불참", count: statusCounts.declined },
        { label: "작성중", value: "작성중", count: statusCounts.drafting },
        { label: "제출완료", value: "제출완료", count: statusCounts.submitted },
        { label: "수정요청", value: "수정요청", count: statusCounts.revisionRequested },
        { label: "최종확정", value: "최종확정", count: statusCounts.confirmed },
        { label: "취소", value: "취소", count: statusCounts.cancelled },
      ]
    },
    {
      id: "dueDate",
      label: "마감일",
      type: "date",
    },
    {
      id: "submittedAt",
      label: "제출일",
      type: "date",
    },
  ]
  
  // useDataTable 훅 사용
  const { table } = useDataTable({
    data,
    columns,
    pageCount,
    filterFields,
    enablePinning: true,
    enableAdvancedFilter: true,
    enableColumnResizing: true,
    columnResizeMode: 'onChange',
    initialState: {
      sorting: [{ id: "updatedAt", desc: true }],
      columnPinning: { right: ["actions"] },
    },
    getRowId: (originalRow) => String(originalRow.id),
    shallow: false,
    clearOnDefault: true,
    defaultColumn: {
      minSize: 50,
      maxSize: 500,
    },
  })
  
  return (
    // <div className="w-full">
    <>
      <div className="overflow-x-auto">
        <DataTable
          table={table}
          className="min-w-full"
        >
          <DataTableAdvancedToolbar
            table={table}
            filterFields={advancedFilterFields}
            shallow={false}
          />
        </DataTable>
      </div>
      {/* 다이얼로그들 */}
      {rowAction?.type === "attachment" && (
        <RfqAttachmentsDialog
          isOpen={true}
          onClose={() => setRowAction(null)}
          rfqData={rowAction.row.original}
        />
      )}

      {rowAction?.type === "items" && (
        <RfqItemsDialog
          isOpen={true}
          onClose={() => setRowAction(null)}
          rfqData={rowAction.row.original}
          viewerType="partners"
        />
      )}
    </>
    // </div>
  )
}