// lib/vendor-quotations/vendor-quotations-table.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 { Button } from "@/components/ui/button"
import { ProcurementVendorQuotations } from "@/db/schema"
import { useRouter } from "next/navigation"
import { getColumns } from "./vendor-quotations-table-columns"

interface QuotationWithRfqCode extends ProcurementVendorQuotations {
  rfqCode?: string;
  rfq?: {
    rfqCode?: string;
  } | null;
}

interface VendorQuotationsTableProps {
  promises: Promise<[{ data: ProcurementVendorQuotations[], pageCount: number }]>;
}

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

  console.log(data ,"data")
  
  // 선택된 행 액션 상태
  const [rowAction, setRowAction] = React.useState<DataTableRowAction<QuotationWithRfqCode> | null>(null);
  
  // 테이블 컬럼 정의
  const columns = React.useMemo(() => getColumns({
    setRowAction,
    router,
  }), [setRowAction, router]);
  
  // 상태별 견적서 수 계산
  const statusCounts = React.useMemo(() => {
    return {
      Draft: data.filter(q => q.status === "Draft").length,
      Submitted: data.filter(q => q.status === "Submitted").length,
      Revised: data.filter(q => q.status === "Revised").length,
      Rejected: data.filter(q => q.status === "Rejected").length,
      Accepted: data.filter(q => q.status === "Accepted").length,
    };
  }, [data]);
  
  // 필터 필드
  const filterFields: DataTableFilterField<QuotationWithRfqCode>[] = [
    {
      id: "status",
      label: "상태",
      options: [
        { label: "초안", value: "Draft", count: statusCounts.Draft },
        { label: "제출됨", value: "Submitted", count: statusCounts.Submitted },
        { label: "수정됨", value: "Revised", count: statusCounts.Revised },
        { label: "반려됨", value: "Rejected", count: statusCounts.Rejected },
        { label: "승인됨", value: "Accepted", count: statusCounts.Accepted },
      ]
    },
    {
      id: "quotationCode",
      label: "견적서 번호",
      placeholder: "견적서 번호 검색...",
    },
    {
      id: "rfqCode",
      label: "RFQ 번호",
      placeholder: "RFQ 번호 검색...",
    }
  ];
  
  // 고급 필터 필드
  const advancedFilterFields: DataTableAdvancedFilterField<QuotationWithRfqCode>[] = [
    {
      id: "quotationCode",
      label: "견적서 번호",
      type: "text",
    },
    {
      id: "rfqCode",
      label: "RFQ 번호",
      type: "text",
    },
    {
      id: "status",
      label: "상태",
      type: "multi-select",
      options: [
        { label: "초안", value: "Draft" },
        { label: "제출됨", value: "Submitted" },
        { label: "수정됨", value: "Revised" },
        { label: "반려됨", value: "Rejected" },
        { label: "승인됨", value: "Accepted" },
      ],
    },
    {
      id: "validUntil",
      label: "유효기간",
      type: "date",
    },
    {
      id: "submittedAt",
      label: "제출일",
      type: "date",
    },
  ];
  
  // useDataTable 훅 사용 (RfqsTable 스타일로 개선)
  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}
          >
          </DataTableAdvancedToolbar>
        </DataTable>
      </div>
    </div>
  );
}