"use client"

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

import { Button } from "@/components/ui/button"
import { PartnersBiddingListItem } from '../detail/service'
import { exportPartnersBiddingsToExcel } from './export-partners-biddings-to-excel'

interface PartnersBiddingToolbarActionsProps {
  table: Table<PartnersBiddingListItem>
  setRowAction?: (action: { type: string; row: { original: PartnersBiddingListItem } }) => void
}

export function PartnersBiddingToolbarActions({ 
  table,
  setRowAction 
}: PartnersBiddingToolbarActionsProps) {
  // 선택된 행 가져오기 (단일 선택)
  const selectedRows = table.getFilteredSelectedRowModel().rows
  const selectedBidding = selectedRows.length === 1 ? selectedRows[0].original : null

  const [isExporting, setIsExporting] = React.useState(false)

  const handleSpecificationMeetingClick = () => {
    if (selectedBidding && setRowAction) {
      setRowAction({ 
        type: 'specification_meeting', 
        row: { original: selectedBidding } 
      })
    }
  }

  // Excel 내보내기 핸들러
  const handleExport = React.useCallback(async () => {
    try {
      setIsExporting(true)
      await exportPartnersBiddingsToExcel(table, {
        filename: "협력업체입찰목록",
        onlySelected: false,
      })
      toast.success("Excel 파일이 다운로드되었습니다.")
    } catch (error) {
      console.error("Excel export error:", error)
      toast.error("Excel 내보내기 중 오류가 발생했습니다.")
    } finally {
      setIsExporting(false)
    }
  }, [table])

  return (
    <div className="flex items-center gap-2">
      {/* Excel 내보내기 버튼 */}
      <Button
        variant="outline"
        size="sm"
        onClick={handleExport}
        disabled={isExporting}
        className="gap-2"
      >
        <FileSpreadsheet className="size-4" aria-hidden="true" />
        <span className="hidden sm:inline">{isExporting ? "내보내는 중..." : "Excel 내보내기"}</span>
      </Button>
      <Button
        variant="outline"
        size="sm"
        onClick={handleSpecificationMeetingClick}
        className="flex items-center gap-2"
      >
        <Users className="w-4 h-4" />
        사양설명회 참석여부
      </Button>
    </div>
  )
}