"use client"

import * as React from "react"
import {
  Send, CheckCircle, FileText, Truck
} from "lucide-react"
import { toast } from "sonner"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { BiddingListItem } from "@/db/schema"
import { transmitToContract, transmitToPO } from "@/lib/bidding/actions"

console.log('=== Module loaded ===')
console.log('transmitToContract imported:', typeof transmitToContract)
console.log('transmitToPO imported:', typeof transmitToPO)

interface TransmissionDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  bidding: BiddingListItem | undefined
  userId: number
}

export function TransmissionDialog({ open, onOpenChange, bidding, userId }: TransmissionDialogProps) {
  const [isLoading, setIsLoading] = React.useState(false)

  if (!bidding) return null

  const handleToContract = async () => {
    try {
      setIsLoading(true)
      console.log('=== START handleToContract ===')
      console.log('bidding.id', bidding.id)
      console.log('userId', userId)
      console.log('transmitToContract function:', typeof transmitToContract)

      console.log('About to call transmitToContract...')
      const result = await transmitToContract(bidding.id, userId)
      console.log('transmitToContract result:', result)

      toast.success('계약서 생성이 완료되었습니다.')
      onOpenChange(false)
    } catch (error) {
      console.error('handleToContract error:', error)
      toast.error(`계약서 생성에 실패했습니다: ${error}`)
    } finally {
      setIsLoading(false)
      console.log('=== END handleToContract ===')
    }
  }

  const handleToPO = async () => {
    try {
      setIsLoading(true)
      await transmitToPO(bidding.id)
      toast.success('PO 전송이 완료되었습니다.')
      onOpenChange(false)
    } catch (error) {
      toast.error(`PO 전송에 실패했습니다: ${error}`)
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Send className="w-5 h-5" />
            입찰 전송
          </DialogTitle>
          <DialogDescription>
            선택된 입찰을 계약서 또는 PO로 전송합니다.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6">
          {/* 입찰 정보 */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base">입찰 정보</CardTitle>
            </CardHeader>
            <CardContent className="space-y-2">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="text-sm font-medium">입찰번호</Label>
                  <p className="text-sm text-muted-foreground">{bidding.biddingNumber}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium">입찰명</Label>
                  <p className="text-sm text-muted-foreground">{bidding.title}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium">계약구분</Label>
                  <p className="text-sm text-muted-foreground">{bidding.contractType}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium">예산</Label>
                  <p className="text-sm text-muted-foreground">
                    {bidding.budget ? `${bidding.budget.toLocaleString()} ${bidding.currency}` : '-'}
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* 선정된 업체 정보 (임시로 표시) */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base">선정된 업체</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex items-center gap-2">
                <CheckCircle className="w-4 h-4 text-green-600" />
                <span className="text-sm">업체 선정이 완료되었습니다.</span>
              </div>
              <p className="text-xs text-muted-foreground mt-2">
                자세한 업체 정보는 전송 후 확인할 수 있습니다.
              </p>
            </CardContent>
          </Card>
        </div>

        <DialogFooter className="flex gap-2">
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            취소
          </Button>
          <Button
            variant="outline"
            onClick={handleToContract}
            disabled={isLoading}
            className="gap-2"
          >
            <FileText className="w-4 h-4" />
            TO Contract
          </Button>
          <Button
            onClick={handleToPO}
            disabled={isLoading}
            className="gap-2"
          >
            <Truck className="w-4 h-4" />
            TO PO
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
