"use client";

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

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useToast } from "@/hooks/use-toast";
import { AddPossibleItemDialog } from "./add-possible-item-dialog";
import { DeletePossibleItemsDialog } from "./delete-possible-items-dialog";
// Excel 함수들을 동적 import로만 사용하기 위해 타입만 import
type TechVendorPossibleItemsData = {
  id: number;
  vendorId: number;
  vendorCode: string | null;
  vendorName: string;
  techVendorType: string;
  itemCode: string;
  itemList: string | null;
  workType: string | null;
  shipTypes: string | null;
  subItemList: string | null;
  createdAt: Date;
  updatedAt: Date;
};

interface PossibleItemsTableToolbarActionsProps {
  table: Table<TechVendorPossibleItemsData>;
}

export function PossibleItemsTableToolbarActions({
  table,
}: PossibleItemsTableToolbarActionsProps) {
  const { toast } = useToast();
  
  const selectedRows = table.getFilteredSelectedRowModel().rows;
  const hasSelection = selectedRows.length > 0;
  const selectedItems = selectedRows.map(row => row.original);

  const handleSuccess = () => {
    table.toggleAllRowsSelected(false);
    // 페이지 새로고침이나 데이터 다시 로드 필요
    window.location.reload();
  };

  const handleExport = async () => {
    try {
      const { exportTechVendorPossibleItemsToExcel } = await import("./excel-export");
      const result = await exportTechVendorPossibleItemsToExcel(table.getFilteredRowModel().rows.map(row => row.original));
      
      if (result.success) {
        toast({
          title: "성공",
          description: "Excel 파일이 다운로드되었습니다.",
        });
      } else {
        toast({
          title: "오류",
          description: result.error || "내보내기 중 오류가 발생했습니다.",
          variant: "destructive",
        });
      }
    } catch (error) {
      console.error("Export error:", error);
      toast({
        title: "오류",
        description: "내보내기 중 오류가 발생했습니다.",
        variant: "destructive",
      });
    }
  };

  const handleImport = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    try {
      const { importTechVendorPossibleItemsFromExcel } = await import("./excel-import");
      const result = await importTechVendorPossibleItemsFromExcel(file);
      
      if (result.success) {
        toast({
          title: "성공",
          description: `${result.successCount}개의 아이템이 가져와졌습니다.`,
        });
        // 페이지 새로고침이나 데이터 다시 로드 필요
        window.location.reload();
      } else {
        toast({
          title: "가져오기 완료",
          description: `${result.successCount}개 성공, ${result.failedRows.length}개 실패`,
          variant: result.successCount > 0 ? "default" : "destructive",
        });
      }
    } catch (error) {
      console.error("Import error:", error);
      toast({
        title: "오류",
        description: "가져오기 중 오류가 발생했습니다.",
        variant: "destructive",
      });
    }

    // Reset input
    event.target.value = "";
  };

  const handleDownloadTemplate = async () => {
    try {
      const { exportTechVendorPossibleItemsTemplate } = await import("./excel-template");
      const result = await exportTechVendorPossibleItemsTemplate();
      if (result.success) {
        toast({
          title: "성공",
          description: "템플릿 파일이 다운로드되었습니다.",
        });
      } else {
        toast({
          title: "오류",
          description: result.error || "템플릿 다운로드 중 오류가 발생했습니다.",
          variant: "destructive",
        });
      }
    } catch (error) {
      console.error("Template download error:", error);
      toast({
        title: "오류",
        description: "템플릿 다운로드 중 오류가 발생했습니다.",
        variant: "destructive",
      });
    }
  };

  return (
    <div className="flex items-center gap-2">
            {hasSelection && (
        <DeletePossibleItemsDialog 
          selectedItems={selectedItems}
          onSuccess={handleSuccess}
        />
      )}
      <AddPossibleItemDialog onSuccess={handleSuccess}>
        <Button size="sm">
          <Plus className="mr-2 h-4 w-4" />
          추가
        </Button>
      </AddPossibleItemDialog>

      <Button 
        variant="outline" 
        size="sm" 
        onClick={() => document.getElementById("import-file")?.click()}
      >
        <Upload className="mr-2 h-4 w-4" />
        Import
      </Button>
      
      <Button variant="outline" size="sm" onClick={handleExport}>
        <Download className="mr-2 h-4 w-4" />
        Export
      </Button>
      
      <Input
        id="import-file"
        type="file"
        accept=".xlsx,.xls"
        onChange={handleImport}
        className="hidden"
      />
      
      
      <Button variant="outline" size="sm" onClick={handleDownloadTemplate}>
        <FileSpreadsheet className="mr-2 h-4 w-4" />
        Download Template
      </Button>
    </div>
  );
} 