"use client"

import * as React from "react"
import {
  Send, CheckCircle, FileText, Truck, Calculator, Package
} 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 { Badge } from "@/components/ui/badge"
import { Separator } from "@/components/ui/separator"
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip"
import { BiddingListItem } from "@/db/schema"
import { transmitToContract, transmitToPO, getWinnerDetails } from "@/lib/bidding/actions"

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

interface WinnerDetail {
  id: number
  companyId: number
  vendorName: string | null
  vendorCode: string | null
  awardRatio: number
  totalFinalAmount: number
  items: Array<{
    prItemId: number
    proposedDeliveryDate: string | null
    bidUnitPrice: string | null
    bidAmount: string | null
    currency: string | null
    itemNumber: string | null
    itemInfo: string | null
    materialDescription: string | null
    quantity: string | null
    quantityUnit: string | null
    finalQuantity: number
    finalWeight: number
    finalAmount: number
    awardRatio: number
  }>
}

export function TransmissionDialog({ open, onOpenChange, bidding, userId }: TransmissionDialogProps) {
  const [isLoading, setIsLoading] = React.useState(false)
  const [winnerDetails, setWinnerDetails] = React.useState<WinnerDetail[]>([])
  const [isLoadingDetails, setIsLoadingDetails] = React.useState(false)

  // 낙찰 업체 상세 정보 로드
  const loadWinnerDetails = React.useCallback(async () => {
    if (!bidding) return

    try {
      setIsLoadingDetails(true)
      const result = await getWinnerDetails(bidding.id)
      if (result.success) {
        setWinnerDetails(result.data || [])
      } else {
        toast.error(result.error || '낙찰 업체 정보를 불러오는데 실패했습니다.')
      }
    } catch (error) {
      console.error('Failed to load winner details:', error)
      toast.error('낙찰 업체 정보를 불러오는데 실패했습니다.')
    } finally {
      setIsLoadingDetails(false)
    }
  }, [bidding])

  React.useEffect(() => {
    if (open && bidding) {
      loadWinnerDetails()
    }
  }, [open, bidding, loadWinnerDetails])

  if (!bidding) return null

  const handleToContract = async () => {
    try {
      setIsLoading(true)
      console.log('bidding.id', bidding.id)
      console.log('userId', userId)
      await transmitToContract(bidding.id, userId)
      toast.success('계약서 생성이 완료되었습니다.')
      onOpenChange(false)
    } catch (error) {
      toast.error(`계약서 생성에 실패했습니다: ${error}`)
    } finally {
      setIsLoading(false)
    }
  }

  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 flex items-center gap-2">
                <CheckCircle className="w-4 h-4 text-green-600" />
                선정된 업체 ({winnerDetails.length}개)
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {isLoadingDetails ? (
                <div className="text-center py-4">
                  <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary mx-auto"></div>
                  <p className="text-sm text-muted-foreground mt-2">업체 정보를 불러오는 중...</p>
                </div>
              ) : winnerDetails.length === 0 ? (
                <p className="text-sm text-muted-foreground">선정된 업체가 없습니다.</p>
              ) : (
                winnerDetails.map((winner) => (
                  <div key={winner.id} className="border rounded-lg p-4 space-y-3">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <Package className="w-4 h-4 text-primary" />
                        <span className="font-medium">{winner.vendorName || `업체 ${winner.companyId}`}</span>
                        <Badge variant="outline">{winner.vendorCode}</Badge>
                      </div>
                      <div className="text-right">
                        <div className="text-sm font-medium">
                          발주비율: {winner.awardRatio.toFixed(1)}%
                        </div>
                        <div className="text-sm text-muted-foreground">
                          최종 견적가: {winner.totalFinalAmount.toLocaleString()} {winner.items[0]?.currency || 'KRW'}
                        </div>
                      </div>
                    </div>

                    <Separator />

                    <div className="space-y-2">
                      <div className="text-sm font-medium flex items-center gap-2">
                        <Calculator className="w-4 h-4" />
                        품목별 상세 ({winner.items.length}개 품목)
                      </div>

                      <div className="space-y-2 max-h-40 overflow-y-auto">
                        {winner.items.map((item, itemIndex) => (
                          <div key={itemIndex} className="bg-muted/50 rounded p-2 text-xs">
                            <div className="grid grid-cols-2 gap-2">
                              <div>
                                <span className="font-medium">품목:</span> {item.itemInfo || item.itemNumber}
                              </div>
                              <div>
                                <span className="font-medium">규격:</span> {item.materialDescription}
                              </div>
                              <div>
                                <span className="font-medium">원래 수량:</span> {Number(item.quantity).toLocaleString()} {item.quantityUnit}
                              </div>
                              <div>
                                <span className="font-medium">발주 수량:</span> {item.finalQuantity.toLocaleString()} {item.quantityUnit}
                              </div>
                              <div>
                                <span className="font-medium">단가:</span> {Number(item.bidUnitPrice).toLocaleString()} {item.currency}
                              </div>
                              <div>
                                <span className="font-medium">최종 금액:</span> {item.finalAmount.toLocaleString()} {item.currency}
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>
                ))
              )}
            </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>
          {bidding.ANFNR ? (
            <Button
              onClick={handleToPO}
              disabled={isLoading}
              className="gap-2"
            >
              <Truck className="w-4 h-4" />
              TO PO
            </Button>
          ) : (
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <div>
                    <Button
                      disabled
                      className="gap-2 opacity-50"
                    >
                      <Truck className="w-4 h-4" />
                      TO PO
                    </Button>
                  </div>
                </TooltipTrigger>
                <TooltipContent>
                  <p>해당 입찰은 SAP TO PO가 불가능합니다.</p>
                </TooltipContent>
              </Tooltip>
            </TooltipProvider>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
