"use client"

import * as React from "react"
import { type Table } from "@tanstack/react-table"
import {
  Send, Download, FileSpreadsheet
} from "lucide-react"
import { toast } from "sonner"
import { useSession } from "next-auth/react"
import { exportTableToExcel } from "@/lib/export"
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"

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 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
  console.log(canTransmit, 'canTransmit')
  console.log(selectedBiddings, 'selectedBiddings')

  return (
    <>
      <div className="flex items-center gap-2">
        {/* 신규입찰 생성 버튼 */}
        <BiddingCreateDialog form={form} onSuccess={() => {
          // 성공 시 테이블 새로고침 등 추가 작업
          // window.location.reload()
        }} />

        {/* 전송하기 (업체선정 완료된 입찰만) */}
        <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>
      </div>

      {/* 전송 다이얼로그 */}
      <TransmissionDialog
        open={isTransmissionDialogOpen}
        onOpenChange={setIsTransmissionDialogOpen}
        bidding={selectedBiddings[0]}
        userId={userId}
      />
    </>
  )
}