"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
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 { getColumns } from "./bid-history-table-columns";
import { getBidHistory } from "../service";
import { TooltipProvider } from "@/components/ui/tooltip";

export interface BidHistoryRow {
  id: number;
  biddingId: number;
  biddingNumber: string | null;
  revision: number | null;
  contractType: "unit_price" | "general" | "sale";
  biddingType: "equipment" | "construction" | "service" | "lease" | "steel_stock" | "piping" | "transport" | "waste" | "sale";
  biddingStatus: "bidding_generated" | "request_for_quotation" | "received_quotation" | "set_target_price" | "bidding_opened" | "bidding_closed" | "evaluation_of_bidding" | "bidding_disposal" | "vendor_selected";
  projectCode: string | null;
  projectName: string | null;
  itemName: string | null;
  materialGroup: string | null;
  materialGroupName: string | null;
  biddingTitle: string | null;
  poNumber: string | null;
  contractNumber: string | null;
  biddingRequestDate: Date | null;
  biddingDeadline: Date | null;
  biddingManager: string | null;
  currency: string | null;
  finalBidPrice: string | null;
  expectedAmount: string | null;
  awardRatio: string | null;
  preQuotePrice: string | null;
  createdAt: Date;
  updatedAt: Date;
}

interface BidHistoryTableProps {
  promises: Promise<
    [
      Awaited<ReturnType<typeof getBidHistory>>,
    ]
  >;
  lng: string;
}

export function VendorBidHistoryTable({ promises, lng }: BidHistoryTableProps) {
  const router = useRouter();

  // SSR을 위해 React.use() 사용 - 서버에서 렌더링된 데이터를 클라이언트에서 사용
  const [{ data = [], pageCount = 0 }] = React.use(promises);

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

  const handleViewDetails = React.useCallback((biddingId: number) => {
    router.push(`/${lng}/evcp/bid/${biddingId}/detail`);
  }, [router, lng]);

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

  const filterFields: DataTableFilterField<BidHistoryRow>[] = [
    {
      id: "biddingNumber",
      label: "입찰번호",
      placeholder: "입찰번호로 검색...",
    },
    {
      id: "contractType",
      label: "계약구분",
      options: [
        { label: "단가", value: "unit_price" },
        { label: "일반", value: "general" },
        { label: "매각", value: "sale" }
      ],
    },
    {
      id: "biddingType",
      label: "입찰유형",
      options: [
        { label: "기자재", value: "equipment" },
        { label: "공사", value: "construction" },
        { label: "용역", value: "service" },
        { label: "임차", value: "lease" },
        { label: "형강스톡", value: "steel_stock" },
        { label: "배관", value: "piping" },
        { label: "운송", value: "transport" },
        { label: "폐기물", value: "waste" },
        { label: "매각", value: "sale" }
      ],
    },
    {
      id: "biddingStatus",
      label: "입찰상태",
      options: [
        { label: "입찰생성", value: "bidding_generated" },
        { label: "사전견적요청", value: "request_for_quotation" },
        { label: "사전견적접수", value: "received_quotation" },
        { label: "내정가산정", value: "set_target_price" },
        { label: "입찰공고", value: "bidding_opened" },
        { label: "입찰마감", value: "bidding_closed" },
        { label: "입찰평가중", value: "evaluation_of_bidding" },
        { label: "유찰", value: "bidding_disposal" },
        { label: "업체선정", value: "vendor_selected" }
      ],
    },
    {
      id: "projectName",
      label: "프로젝트명",
      placeholder: "프로젝트명으로 검색...",
    }
  ];

  const advancedFilterFields: DataTableAdvancedFilterField<BidHistoryRow>[] = [
    { id: "biddingNumber", label: "입찰번호", type: "text" },
    { id: "projectCode", label: "프로젝트코드", type: "text" },
    { id: "projectName", label: "프로젝트명", type: "text" },
    {
      id: "contractType",
      label: "계약구분",
      type: "multi-select",
      options: [
        { label: "단가", value: "unit_price" },
        { label: "일반", value: "general" },
        { label: "매각", value: "sale" }
      ],
    },
    {
      id: "biddingType",
      label: "입찰유형",
      type: "multi-select",
      options: [
        { label: "기자재", value: "equipment" },
        { label: "공사", value: "construction" },
        { label: "용역", value: "service" },
        { label: "임차", value: "lease" },
        { label: "형강스톡", value: "steel_stock" },
        { label: "배관", value: "piping" },
        { label: "운송", value: "transport" },
        { label: "폐기물", value: "waste" },
        { label: "매각", value: "sale" }
      ],
    },
    {
      id: "biddingStatus",
      label: "입찰상태",
      type: "multi-select",
      options: [
        { label: "입찰생성", value: "bidding_generated" },
        { label: "사전견적요청", value: "request_for_quotation" },
        { label: "사전견적접수", value: "received_quotation" },
        { label: "내정가산정", value: "set_target_price" },
        { label: "입찰공고", value: "bidding_opened" },
        { label: "입찰마감", value: "bidding_closed" },
        { label: "입찰평가중", value: "evaluation_of_bidding" },
        { label: "유찰", value: "bidding_disposal" },
        { label: "업체선정", value: "vendor_selected" }
      ],
    },
    { id: "biddingManager", label: "입찰담당자", type: "text" },
    { id: "biddingRequestDate", label: "입찰요청일", type: "date" },
    { id: "biddingDeadline", label: "입찰마감일", type: "date" },
    { id: "createdAt", 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, 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>
    </>
  );
}
