// lib/vendor-responses/table/vendor-responses-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 { useRouter } from "next/navigation"
import { getColumns } from "./vendor-responses-table-columns"
import { VendorRfqResponseSummary } from "../validations"

interface VendorResponsesTableProps {
  promises: Promise<[{ data: VendorRfqResponseSummary[], pageCount: number, totalCount: number }]>;
}

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

  console.log(data, "vendor responses data")
  
  // 선택된 행 액션 상태
  
  // 테이블 컬럼 정의
  const columns = React.useMemo(() => getColumns({
    router,
  }), [router]);
  
  // 상태별 응답 수 계산 (전체 상태 기준)
  const statusCounts = React.useMemo(() => {
    return {
      NOT_RESPONDED: data.filter(r => r.overallStatus === "NOT_RESPONDED").length,
      RESPONDED: data.filter(r => r.overallStatus === "RESPONDED").length,
      REVISION_REQUESTED: data.filter(r => r.overallStatus === "REVISION_REQUESTED").length,
      WAIVED: data.filter(r => r.overallStatus === "WAIVED").length,
    };
  }, [data]);

  
  // 필터 필드
  const filterFields: DataTableFilterField<VendorRfqResponseSummary>[] = [
    {
      id: "overallStatus",
      label: "전체 상태",
      options: [
        { label: "미응답", value: "NOT_RESPONDED", count: statusCounts.NOT_RESPONDED },
        { label: "응답완료", value: "RESPONDED", count: statusCounts.RESPONDED },
        { label: "수정요청", value: "REVISION_REQUESTED", count: statusCounts.REVISION_REQUESTED },
        { label: "포기", value: "WAIVED", count: statusCounts.WAIVED },
      ]
    },

    {
      id: "rfqCode",
      label: "RFQ 번호",
      placeholder: "RFQ 번호 검색...",
    }
  ];
  
  // 고급 필터 필드
  const advancedFilterFields: DataTableAdvancedFilterField<VendorRfqResponseSummary>[] = [
    {
      id: "rfqCode",
      label: "RFQ 번호",
      type: "text",
    },
    {
      id: "overallStatus",
      label: "전체 상태",
      type: "multi-select",
      options: [
        { label: "미응답", value: "NOT_RESPONDED" },
        { label: "응답완료", value: "RESPONDED" },
        { label: "수정요청", value: "REVISION_REQUESTED" },
        { label: "포기", value: "WAIVED" },
      ],
    },
    {
      id: "rfqType",
      label: "RFQ 타입",
      type: "multi-select",
      options: [
        { label: "초기 RFQ", value: "INITIAL" },
        { label: "최종 RFQ", value: "FINAL" },
      ],
    },
    {
      id: "responseRate",
      label: "응답률",
      type: "number",
    },
    {
      id: "completionRate",
      label: "완료율",
      type: "number",
    },
    {
      id: "requestedAt",
      label: "요청일",
      type: "date",
    },
    {
      id: "lastRespondedAt",
      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="flex items-center justify-between py-4">
        <div className="flex items-center space-x-2">
          <span className="text-sm text-muted-foreground">
            총 {totalCount}개의 응답 요청
          </span>
        </div>
      </div>
      
      <div className="overflow-x-auto">
        <DataTable
          table={table}
          className="min-w-full"
        >
          <DataTableAdvancedToolbar
            table={table}
            filterFields={advancedFilterFields}
            shallow={false}
          >
            {/* 추가적인 액션 버튼들을 여기에 추가할 수 있습니다 */}
          </DataTableAdvancedToolbar>
        </DataTable>
      </div>
    </div>
  );
}