"use client"

import * as React from "react"
import type {
  DataTableAdvancedFilterField,
  DataTableFilterField,
  DataTableRowAction,
} from "@/types/table"

import { toSentenceCase } from "@/lib/utils"
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 { getColumns } from "./rfq-history-table-columns"
import { getRfqHistory } from "../service"
import { RfqHistoryTableToolbarActions } from "./rfq-history-table-toolbar-actions"
import { getRFQStatusIcon } from "@/lib/tasks/utils"
import { TooltipProvider } from "@/components/ui/tooltip"
import { useRouter } from "next/navigation"

export interface RfqHistoryRow {
  id: number;
  rfqType: string | null;
  status: string;
  rfqCode: string | null;
  projectInfo: string | null;
  packageInfo: string | null;
  materialInfo: string | null;
  // 견적정보 세부 필드들
  currency: string | null;
  totalAmount: number | null;
  leadTime: string | null;
  paymentTerms: string | null;
  incoterms: string | null;
  shippingLocation: string | null;
  contractInfo: string | null;
  rfqSendDate: Date | null;
  submittedAt: Date | null;
  picName: string | null;
  // 기존 필드들 (호환성을 위해 유지)
  projectCode: string | null;
  projectName: string | null;
  description: string | null;
  dueDate: Date;
  vendorStatus: string;
  itemCount: number;
  tbeResult: string | null;
  cbeResult: string | null;
  items: {
    rfqId: number;
    id: number;
    itemCode: string;
    description: string | null;
    quantity: number | null;
    uom: string | null;
  }[];
  actions?: any; // actions 컬럼용
}

interface RfqHistoryTableProps {
  promises: Promise<
    [
      Awaited<ReturnType<typeof getRfqHistory>>,
    ]
  >
  lng: string
  vendorId: number
}

export function VendorRfqHistoryTable({ promises, lng, vendorId }: RfqHistoryTableProps) {
  const [{ data = [], pageCount = 0 }] = React.use(promises)
  const router = useRouter()

  const [, setRowAction] = React.useState<DataTableRowAction<RfqHistoryRow> | null>(null)

  const onViewDetails = React.useCallback((rfqId: number) => {
    router.push(`/${lng}/evcp/rfq-last/${rfqId}`);
  }, [router, lng]);

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

  const filterFields: DataTableFilterField<RfqHistoryRow>[] = [
    {
      id: "rfqType",
      label: "견적종류",
      options: [
        { label: "ITB", value: "ITB" },
        { label: "RFQ", value: "RFQ" },
        { label: "일반", value: "일반" },
        { label: "정기견적", value: "정기견적" }
      ],
    },
    {
      id: "status",
      label: "견적상태",
      options: [
        { label: "ITB 발송", value: "ITB 발송" },
        { label: "TBE 요청", value: "TBE 요청" },
        { label: "최종업체선정", value: "최종업체선정" },
        { label: "견적접수", value: "견적접수" },
        { label: "견적평가중", value: "견적평가중" },
        { label: "견적완료", value: "견적완료" }
      ],
    },
    { id: "rfqCode", label: "견적번호", placeholder: "견적번호로 검색..." },
    { id: "projectInfo", label: "프로젝트", placeholder: "프로젝트로 검색..." },
    { id: "packageInfo", label: "PKG No.", placeholder: "PKG로 검색..." },
    { id: "materialInfo", label: "자재그룹", placeholder: "자재그룹으로 검색..." },
    {
      id: "currency",
      label: "통화",
      options: [
        { label: "USD", value: "USD" },
        { label: "KRW", value: "KRW" },
        { label: "EUR", value: "EUR" },
        { label: "JPY", value: "JPY" }
      ],
    },
    { id: "paymentTerms", label: "지급조건", placeholder: "지급조건으로 검색..." },
    { id: "incoterms", label: "Incoterms", placeholder: "Incoterms로 검색..." },
    { id: "shippingLocation", label: "선적지", placeholder: "선적지로 검색..." },
    { id: "picName", label: "견적담당자", placeholder: "담당자로 검색..." },
  ]

  const advancedFilterFields: DataTableAdvancedFilterField<RfqHistoryRow>[] = [
    {
      id: "rfqType",
      label: "견적종류",
      type: "multi-select",
      options: [
        { label: "ITB", value: "ITB" },
        { label: "RFQ", value: "RFQ" },
        { label: "일반", value: "일반" },
        { label: "정기견적", value: "정기견적" }
      ],
    },
    {
      id: "status",
      label: "견적상태",
      type: "multi-select",
      options: [
        { label: "ITB 발송", value: "ITB 발송" },
        { label: "TBE 요청", value: "TBE 요청" },
        { label: "최종업체선정", value: "최종업체선정" },
        { label: "견적접수", value: "견적접수" },
        { label: "견적평가중", value: "견적평가중" },
        { label: "견적완료", value: "견적완료" }
      ],
    },
    { id: "rfqCode", label: "견적번호", type: "text" },
    { id: "projectInfo", label: "프로젝트", type: "text" },
    { id: "packageInfo", label: "PKG No.", type: "text" },
    { id: "materialInfo", label: "자재그룹", type: "text" },
    {
      id: "currency",
      label: "통화",
      type: "multi-select",
      options: [
        { label: "USD", value: "USD" },
        { label: "KRW", value: "KRW" },
        { label: "EUR", value: "EUR" },
        { label: "JPY", value: "JPY" }
      ],
    },
    { id: "totalAmount", label: "총 견적금액", type: "number" },
    { id: "leadTime", label: "업체 L/T(W)", type: "text" },
    { id: "paymentTerms", label: "지급조건", type: "text" },
    { id: "incoterms", label: "Incoterms", type: "text" },
    { id: "shippingLocation", label: "선적지", type: "text" },
    { id: "contractInfo", label: "PO/계약정보", type: "text" },
    { id: "rfqSendDate", label: "견적요청일", type: "date" },
    { id: "submittedAt", label: "견적회신일", type: "date" },
    { id: "picName", label: "견적담당자", type: "text" },
  ]

  const { table } = useDataTable({
    data,
    columns,
    pageCount,
    filterFields,
    enablePinning: true,
    enableAdvancedFilter: true,
    initialState: {
      sorting: [{ id: "rfqSendDate", desc: true }],
      columnPinning: { right: ["actions"] },
    },
    getRowId: (originalRow, index) => originalRow?.id ? String(originalRow.id) : String(index),
    shallow: false,
    clearOnDefault: true,
  });

  return (
    <>
      <TooltipProvider>
        <DataTable
          table={table}
        >
          <DataTableAdvancedToolbar
            table={table}
            filterFields={advancedFilterFields}
            shallow={false}
          >
          </DataTableAdvancedToolbar>
        </DataTable>

      </TooltipProvider>
    </>
  )
}