"use client"

import * as React from "react"
import { type Table } from "@tanstack/react-table"
import {
  Send, Download, FileSpreadsheet, Trash
} from "lucide-react"
import { toast } from "sonner"
import { useSession } from "next-auth/react"
import { exportBiddingsToExcel } from "./export-biddings-to-excel"
import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { BiddingListItem } from "@/db/schema"
import { TransmissionDialog } from "./biddings-transmission-dialog"
import { BiddingCreateDialog } from "@/components/bidding/create/bidding-create-dialog"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { createBiddingSchema } from "@/lib/bidding/validation"
import { deleteBidding } from "@/lib/bidding/delete-action"
import { BiddingDeleteDialog } from "./biddings-delete-dialog"

interface BiddingsTableToolbarActionsProps {
  table: Table<BiddingListItem>
}

export function BiddingsTableToolbarActions({ table }: BiddingsTableToolbarActionsProps) {
  const { data: session } = useSession()
  const [isExporting, setIsExporting] = React.useState(false)
  const [isTransmissionDialogOpen, setIsTransmissionDialogOpen] = React.useState(false)
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = React.useState(false)
  
  const userId = session?.user?.id ? Number(session.user.id) : 1

  // 입찰 생성 폼
  const form = useForm({
    resolver: zodResolver(createBiddingSchema),
    defaultValues: {
      revision: 0,
      title: '',
      description: '',
      content: '',
      noticeType: 'standard' as const,
      contractType: 'general' as const,
      biddingType: 'equipment' as const,
      awardCount: 'single' as const,
      currency: 'KRW',
      status: 'bidding_generated' as const,
      bidPicName: '',
      bidPicCode: '',
      supplyPicName: '',
      supplyPicCode: '',
      requesterName: '',
      attachments: [],
      vendorAttachments: [],
      hasSpecificationMeeting: false,
      hasPrDocument: false,
      isPublic: false,
      isUrgent: false,
      purchasingOrganization: '',
      biddingConditions: {
        paymentTerms: '',
        taxConditions: 'V1',
        incoterms: 'DAP',
        incotermsOption: '',
        contractDeliveryDate: '',
        shippingPort: '',
        destinationPort: '',
        isPriceAdjustmentApplicable: false,
        sparePartOptions: '',
      },
    },
  })

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

  // 업체선정이 완료된 입찰만 전송 가능
  const canTransmit = true
  
  // 삭제 가능 여부: 선택된 항목이 정확히 1개이고, '입찰생성' 상태여야 함
  const canDelete = React.useMemo(() => {
    return selectedBiddings.length === 1 && selectedBiddings[0].status === 'bidding_generated'
  }, [selectedBiddings])

  // Excel 내보내기 핸들러
  const handleExport = React.useCallback(async () => {
    try {
      setIsExporting(true)
      await exportBiddingsToExcel(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">
        {/* 신규입찰 생성 버튼 */}
        <BiddingCreateDialog form={form} onSuccess={() => {
          // 성공 시 테이블 새로고침 등 추가 작업
          // window.location.reload()
        }} />
        {/* 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="default"
          size="sm"
          onClick={() => setIsTransmissionDialogOpen(true)}
          disabled={!canTransmit}
          className="gap-2"
        >
          <Send className="size-4" aria-hidden="true" />
          <span className="hidden sm:inline">전송하기</span>
        </Button>
        {/* 삭제 버튼 */}
        <Button
          variant="destructive"
          size="sm"
          onClick={() => setIsDeleteDialogOpen(true)}
          disabled={!canDelete}
          className="gap-2"
        >
          <Trash className="size-4" aria-hidden="true" />
          <span className="hidden sm:inline">삭제</span>
        </Button>
      </div>

      {/* 전송 다이얼로그 */}
      <TransmissionDialog
        open={isTransmissionDialogOpen}
        onOpenChange={setIsTransmissionDialogOpen}
        bidding={selectedBiddings[0]}
        userId={userId}
      />
      
      {/* 삭제 다이얼로그 */}
      <BiddingDeleteDialog
        open={isDeleteDialogOpen}
        onOpenChange={setIsDeleteDialogOpen}
        bidding={selectedBiddings[0]}
        onSuccess={() => table.resetRowSelection()}
      />
    </>
  )
}