'use client'

import * as React from 'react'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { PrItemsPricingTable } from '../../vendor/components/pr-items-pricing-table'
import { getSavedPrItemQuotations } from '../service'

interface PrItem {
  id: number
  itemNumber: string | null
  prNumber: string | null
  itemInfo: string | null
  materialDescription: string | null
  quantity: string | null
  quantityUnit: string | null
  totalWeight: string | null
  weightUnit: string | null
  currency: string | null
  requestedDeliveryDate: string | null
  hasSpecDocument: boolean | null
}

interface PrItemQuotation {
  prItemId: number
  bidUnitPrice: number
  bidAmount: number
  proposedDeliveryDate?: string
  technicalSpecification?: string
}

interface BiddingPreQuoteItemDetailsDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  biddingId: number
  biddingCompanyId: number
  companyName: string
  prItems: PrItem[]
  currency?: string
}

export function BiddingPreQuoteItemDetailsDialog({
  open,
  onOpenChange,
  biddingId,
  biddingCompanyId,
  companyName,
  prItems,
  currency = 'KRW'
}: BiddingPreQuoteItemDetailsDialogProps) {
  const [prItemQuotations, setPrItemQuotations] = React.useState<PrItemQuotation[]>([])
  const [isLoading, setIsLoading] = React.useState(false)

  // 다이얼로그가 열릴 때 저장된 품목별 견적 데이터 로드
  React.useEffect(() => {
    if (open && biddingCompanyId) {
      loadSavedQuotations()
    }
  }, [open, biddingCompanyId])

  const loadSavedQuotations = async () => {
    setIsLoading(true)
    try {
      console.log('Loading saved quotations for biddingCompanyId:', biddingCompanyId)
      const savedQuotations = await getSavedPrItemQuotations(biddingCompanyId)
      console.log('Loaded saved quotations:', savedQuotations)
      setPrItemQuotations(savedQuotations)
    } catch (error) {
      console.error('Failed to load saved quotations:', error)
    } finally {
      setIsLoading(false)
    }
  }

  const handleQuotationsChange = (quotations: PrItemQuotation[]) => {
    // ReadOnly 모드이므로 변경사항을 저장하지 않음
    console.log('Quotations changed (readonly):', quotations)
  }

  const handleTotalAmountChange = (total: number) => {
    // ReadOnly 모드이므로 총 금액 변경을 처리하지 않음
    console.log('Total amount changed (readonly):', total)
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-7xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <span>품목별 견적 상세</span>
            <span className="text-sm font-normal text-muted-foreground">
              - {companyName}
            </span>
          </DialogTitle>
          <DialogDescription>
            협력업체가 제출한 품목별 견적 상세 정보입니다.
          </DialogDescription>
        </DialogHeader>

        {isLoading ? (
          <div className="flex items-center justify-center py-12">
            <div className="text-center">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
              <p className="text-muted-foreground">견적 정보를 불러오는 중...</p>
            </div>
          </div>
        ) : (
          <PrItemsPricingTable
            prItems={prItems}
            initialQuotations={prItemQuotations}
            currency={currency}
            onQuotationsChange={handleQuotationsChange}
            onTotalAmountChange={handleTotalAmountChange}
            readOnly={true}
          />
        )}
      </DialogContent>
    </Dialog>
  )
}
