"use client"

import * as React from "react"
import { type Table } from "@tanstack/react-table"
import { 
  Plus, Send, Gavel, Download, FileSpreadsheet,
  Eye, Clock, CheckCircle 
} from "lucide-react"
import { toast } from "sonner"
import { useRouter } from "next/navigation"
import { exportTableToExcel } from "@/lib/export"
import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { BiddingListItem } from "@/db/schema"
import { CreateBiddingDialog } from "./create-bidding-dialog"

interface BiddingsTableToolbarActionsProps {
  table: Table<BiddingListItem>
  paymentTermsOptions: Array<{code: string, description: string}>
  incotermsOptions: Array<{code: string, description: string}>
}

export function BiddingsTableToolbarActions({ table, paymentTermsOptions, incotermsOptions }: BiddingsTableToolbarActionsProps) {
  const router = useRouter()
  const [isExporting, setIsExporting] = React.useState(false)

  // 선택된 입찰들
  const selectedBiddings = React.useMemo(() => {
    return table
      .getFilteredSelectedRowModel()
      .rows
      .map(row => row.original)
  }, [table.getFilteredSelectedRowModel().rows])

  const handleExport = async () => {
    try {
      setIsExporting(true)
      await exportTableToExcel(table, {
        filename: "biddings",
        excludeColumns: ["select", "actions"],
      })
      toast.success("입찰 목록이 성공적으로 내보내졌습니다.")
    } catch (error) {
      toast.error("내보내기 중 오류가 발생했습니다.")
    } finally {
      setIsExporting(false)
    }
  }

  return (
    <div className="flex items-center gap-2">
      {/* 신규 생성 */}
    <CreateBiddingDialog
      paymentTermsOptions={paymentTermsOptions}
      incotermsOptions={incotermsOptions}
    />

      {/* 개찰 (입찰 오픈) */}
      {/* {openEligibleBiddings.length > 0 && (
        <Button 
          variant="outline" 
          size="sm"
          onClick={handleBiddingOpen}
        >
          <Gavel className="mr-2 h-4 w-4" />
          개찰 ({openEligibleBiddings.length})
        </Button>
      )} */}

      {/* Export */}
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button
            variant="outline"
            size="sm"
            className="gap-2"
            disabled={isExporting}
          >
            <Download className="size-4" aria-hidden="true" />
            <span className="hidden sm:inline">
              {isExporting ? "내보내는 중..." : "Export"}
            </span>
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end">
          <DropdownMenuItem onClick={handleExport} disabled={isExporting}>
            <FileSpreadsheet className="mr-2 size-4" />
            <span>입찰 목록 내보내기</span>
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  )
}