"use client"

import * as React from "react"
import { type Table } from "@tanstack/react-table"
import { Download, FileDown, Upload } from "lucide-react"
import { toast } from "sonner"

import { exportTableToExcel } from "@/lib/export"
import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"

import { DeletePqsDialog } from "./delete-pqs-dialog"
import { AddPqDialog } from "./add-pq-dialog"
import { PqCriterias } from "@/db/schema/pq"
import { ImportPqButton } from "./import-pq-button"
import { exportPqTemplate } from "./pq-excel-template"

interface PqTableToolbarActionsProps {
  table: Table<PqCriterias>
  currentProjectId?: number
}

export function PqTableToolbarActions({ 
  table, 
  currentProjectId
}: PqTableToolbarActionsProps) {
  const [refreshKey, setRefreshKey] = React.useState(0)
  const isProjectSpecific = !!currentProjectId
  
  // Import 성공 후 테이블 갱신
  const handleImportSuccess = () => {
    setRefreshKey(prev => prev + 1)
  }
  
  return (
    <div className="flex items-center gap-2">
      {table.getFilteredSelectedRowModel().rows.length > 0 ? (
        <DeletePqsDialog
          pqs={table
            .getFilteredSelectedRowModel()
            .rows.map((row) => row.original)}
          onSuccess={() => table.toggleAllRowsSelected(false)}
        />
      ) : null}
      
      <AddPqDialog currentProjectId={currentProjectId} />
      
      {/* Import 버튼 */}
      <ImportPqButton 
        projectId={currentProjectId} 
        onSuccess={handleImportSuccess} 
      />
      
      {/* Export 드롭다운 메뉴 */}
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button variant="outline" size="sm" className="gap-2">
            <Download className="size-4" aria-hidden="true" />
            <span className="hidden sm:inline">Export</span>
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end">
          <DropdownMenuItem
            onClick={() =>
              exportTableToExcel(table, {
                filename: isProjectSpecific ? `project-${currentProjectId}-pq-criteria` : "general-pq-criteria",
                excludeColumns: ["select", "actions"],
              })
            }
          >
            <FileDown className="mr-2 h-4 w-4" />
            <span>현재 데이터 내보내기</span>
          </DropdownMenuItem>
          <DropdownMenuItem onClick={() => exportPqTemplate(isProjectSpecific)}>
            <FileDown className="mr-2 h-4 w-4" />
            <span>{isProjectSpecific ? '프로젝트용' : '일반'} 템플릿 다운로드</span>
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  )
}