'use client'

import * as React from 'react'
import { Bidding } from '@/db/schema'
import { QuotationDetails, QuotationVendor } from '@/lib/bidding/detail/service'

import { BiddingDetailVendorTableContent } from './bidding-detail-vendor-table'
import { BiddingDetailItemsDialog } from './bidding-detail-items-dialog'
import { BiddingDetailTargetPriceDialog } from './bidding-detail-target-price-dialog'
import { BiddingPreQuoteItemDetailsDialog } from '../../../bidding/pre-quote/table/bidding-pre-quote-item-details-dialog'
import { getPrItemsForBidding } from '../../../bidding/pre-quote/service'
import { useToast } from '@/hooks/use-toast'
import { useTransition } from 'react'

interface BiddingDetailContentProps {
  bidding: Bidding
  quotationDetails: QuotationDetails | null
  quotationVendors: QuotationVendor[]
  prItems: any[]
}

export function BiddingDetailContent({
  bidding,
  quotationDetails,
  quotationVendors,
  prItems
}: BiddingDetailContentProps) {
  const { toast } = useToast()
  const [isPending, startTransition] = useTransition()
  
  const [dialogStates, setDialogStates] = React.useState({
    items: false,
    targetPrice: false,
    selectionReason: false,
    award: false
  })

  const [, setRefreshTrigger] = React.useState(0)
  
  // PR 아이템 다이얼로그 관련 state
  const [isItemDetailsDialogOpen, setIsItemDetailsDialogOpen] = React.useState(false)
  const [selectedVendorForDetails, setSelectedVendorForDetails] = React.useState<QuotationVendor | null>(null)
  const [prItemsForDialog, setPrItemsForDialog] = React.useState<any[]>([])

  const handleRefresh = React.useCallback(() => {
    setRefreshTrigger(prev => prev + 1)
  }, [])

  const openDialog = React.useCallback((type: keyof typeof dialogStates) => {
    setDialogStates(prev => ({ ...prev, [type]: true }))
  }, [])

  const closeDialog = React.useCallback((type: keyof typeof dialogStates) => {
    setDialogStates(prev => ({ ...prev, [type]: false }))
  }, [])

  const handleViewItemDetails = React.useCallback((vendor: QuotationVendor) => {
    startTransition(async () => {
      try {
        // PR 아이템 정보 로드
        const prItemsData = await getPrItemsForBidding(bidding.id)
        setPrItemsForDialog(prItemsData)
        setSelectedVendorForDetails(vendor)
        setIsItemDetailsDialogOpen(true)
      } catch (error) {
        console.error('Failed to load PR items:', error)
        toast({
          title: '오류',
          description: '품목 정보를 불러오는데 실패했습니다.',
          variant: 'destructive',
        })
      }
    })
  }, [bidding.id, toast])

  return (
    <div className="space-y-6">
      <BiddingDetailVendorTableContent
        biddingId={bidding.id}
        bidding={bidding}
        vendors={quotationVendors}
        onRefresh={handleRefresh}
        onOpenTargetPriceDialog={() => openDialog('targetPrice')}
        onOpenSelectionReasonDialog={() => openDialog('selectionReason')}
        onViewItemDetails={handleViewItemDetails}
        onEdit={undefined}
      />

      <BiddingDetailItemsDialog
        open={dialogStates.items}
        onOpenChange={(open) => closeDialog('items')}
        prItems={prItems}
        bidding={bidding}
      />

      <BiddingDetailTargetPriceDialog
        open={dialogStates.targetPrice}
        onOpenChange={(open) => closeDialog('targetPrice')}
        quotationDetails={quotationDetails}
        bidding={bidding}
        onSuccess={handleRefresh}
      />

      <BiddingPreQuoteItemDetailsDialog
        open={isItemDetailsDialogOpen}
        onOpenChange={setIsItemDetailsDialogOpen}
        biddingId={bidding.id}
        biddingCompanyId={selectedVendorForDetails?.id || 0}
        companyName={selectedVendorForDetails?.vendorName || ''}
        prItems={prItemsForDialog}
        currency={bidding.currency || 'KRW'}
      />
    </div>
  )
}
