"use client";

import * as React from "react";
import { type Table } from "@tanstack/react-table";
import { Download, RefreshCw, Plus } from "lucide-react";

import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { RfqsLastView } from "@/db/schema";
import { CreateGeneralRfqDialog } from "./create-general-rfq-dialog";

interface RfqTableToolbarActionsProps {
  table: Table<RfqsLastView>;
  onRefresh?: () => void;
  rfqCategory?: "general" | "itb" | "rfq";
}

export function RfqTableToolbarActions({
  table,
  onRefresh,
  rfqCategory = "itb",
}: RfqTableToolbarActionsProps) {
  const [isExporting, setIsExporting] = React.useState(false);

  const handleExportCSV = React.useCallback(async () => {
    setIsExporting(true);
    try {
      const data = table.getFilteredRowModel().rows.map((row) => {
        const original = row.original;
        return {
          "RFQ 코드": original.rfqCode || "",
          "상태": original.status || "",
          "프로젝트 코드": original.projectCode || "",
          "프로젝트명": original.projectName || "",
          "자재코드": original.itemCode || "",
          "자재명": original.itemName || "",
          "패키지 번호": original.packageNo || "",
          "패키지명": original.packageName || "",
          "구매담당자": original.picUserName || original.picName || "",
          "엔지니어링 담당": original.engPicName || "",
          "발송일": original.rfqSendDate ? new Date(original.rfqSendDate).toLocaleDateString("ko-KR") : "",
          "마감일": original.dueDate ? new Date(original.dueDate).toLocaleDateString("ko-KR") : "",
          "업체수": original.vendorCount || 0,
          "Short List": original.shortListedVendorCount || 0,
          "견적접수": original.quotationReceivedCount || 0,
          "PR Items": original.prItemsCount || 0,
          "주요 Items": original.majorItemsCount || 0,
          "시리즈": original.series || "",
          "견적 유형": original.rfqType || "",
          "견적 제목": original.rfqTitle || "",
          "프로젝트 회사": original.projectCompany || "",
          "프로젝트 사이트": original.projectSite || "",
          "SM 코드": original.smCode || "",
          "PR 번호": original.prNumber || "",
          "PR 발행일": original.prIssueDate ? new Date(original.prIssueDate).toLocaleDateString("ko-KR") : "",
          "생성자": original.createdByUserName || "",
          "생성일": original.createdAt ? new Date(original.createdAt).toLocaleDateString("ko-KR") : "",
          "수정자": original.updatedByUserName || "",
          "수정일": original.updatedAt ? new Date(original.updatedAt).toLocaleDateString("ko-KR") : "",
        };
      });

      const fileName = `RFQ_목록_${new Date().toISOString().split("T")[0]}.csv`;
      exportTableToCSV({ data, filename: fileName });
    } catch (error) {
      console.error("Export failed:", error);
    } finally {
      setIsExporting(false);
    }
  }, [table]);

  const handleExportSelected = React.useCallback(async () => {
    setIsExporting(true);
    try {
      const selectedRows = table.getFilteredSelectedRowModel().rows;
      if (selectedRows.length === 0) {
        alert("선택된 항목이 없습니다.");
        return;
      }

      const data = selectedRows.map((row) => {
        const original = row.original;
        return {
          "RFQ 코드": original.rfqCode || "",
          "상태": original.status || "",
          "프로젝트 코드": original.projectCode || "",
          "프로젝트명": original.projectName || "",
          "자재코드": original.itemCode || "",
          "자재명": original.itemName || "",
          "패키지 번호": original.packageNo || "",
          "패키지명": original.packageName || "",
          "구매담당자": original.picUserName || original.picName || "",
          "엔지니어링 담당": original.engPicName || "",
          "발송일": original.rfqSendDate ? new Date(original.rfqSendDate).toLocaleDateString("ko-KR") : "",
          "마감일": original.dueDate ? new Date(original.dueDate).toLocaleDateString("ko-KR") : "",
          "업체수": original.vendorCount || 0,
          "Short List": original.shortListedVendorCount || 0,
          "견적접수": original.quotationReceivedCount || 0,
        };
      });

      const fileName = `RFQ_선택항목_${new Date().toISOString().split("T")[0]}.csv`;
      exportTableToCSV({ data, filename: fileName });
    } catch (error) {
      console.error("Export failed:", error);
    } finally {
      setIsExporting(false);
    }
  }, [table]);

  return (
    <div className="flex items-center gap-2">
      {onRefresh && (
        <Button
          variant="outline"
          size="sm"
          onClick={onRefresh}
          className="h-8 px-2 lg:px-3"
        >
          <RefreshCw className="mr-2 h-4 w-4" />
          새로고침
        </Button>
      )}

      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button
            variant="outline"
            size="sm"
            className="h-8 px-2 lg:px-3"
            disabled={isExporting}
          >
            <Download className="mr-2 h-4 w-4" />
            {isExporting ? "내보내는 중..." : "내보내기"}
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end">
          <DropdownMenuItem onClick={handleExportCSV}>
            전체 데이터 내보내기
          </DropdownMenuItem>
          <DropdownMenuItem 
            onClick={handleExportSelected}
            disabled={table.getFilteredSelectedRowModel().rows.length === 0}
          >
            선택한 항목 내보내기 ({table.getFilteredSelectedRowModel().rows.length}개)
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>

      {/* rfqCategory가 'general'일 때만 일반견적 생성 다이얼로그 표시 */}
      {rfqCategory === "general" && (
        <CreateGeneralRfqDialog onSuccess={onRefresh} />
      ) }
    </div>
  );
}