summaryrefslogtreecommitdiff
path: root/lib/bidding/vendor/partners-bidding-detail.tsx
blob: f9241f7b5280944d6aaddfc01b6a1967186a72ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
'use client'

import * as React from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Label } from '@/components/ui/label'
import {
  ArrowLeft,
  User,
  Users,
  Send,
  CheckCircle,
  XCircle,
  Save,
  FileText,
  Building2,
  Package
} from 'lucide-react'

import { formatDate } from '@/lib/utils'
import {
  getBiddingDetailsForPartners,
  submitPartnerResponse,
  updatePartnerBiddingParticipation,
  saveBiddingDraft
} from '../detail/service'
import { getPrItemsForBidding, getSavedPrItemQuotations } from '@/lib/bidding/pre-quote/service'
import { PrItemsPricingTable } from './components/pr-items-pricing-table'
import { SimpleFileUpload } from './components/simple-file-upload'
import {
  biddingStatusLabels,
  contractTypeLabels,
  biddingTypeLabels
} from '@/db/schema'
import { useToast } from '@/hooks/use-toast'
import { useTransition } from 'react'
import { useSession } from 'next-auth/react'

interface PartnersBiddingDetailProps {
  biddingId: number
  companyId: number
}

interface BiddingDetail {
  id: number
  biddingNumber: string
  revision: number | null
  projectName: string | null
  itemName: string | null
  title: string
  description: string | null
  content: string | null
  contractType: string
  biddingType: string
  awardCount: string | null
  contractStartDate: Date | null
  contractEndDate: Date | null
  preQuoteDate: Date | null
  biddingRegistrationDate: Date | null
  submissionStartDate: Date | null
  submissionEndDate: Date | null
  evaluationDate: Date | null
  currency: string
  budget: number | null
  targetPrice: number | null
  status: string
  managerName: string | null
  managerEmail: string | null
  managerPhone: string | null
  biddingCompanyId: number
  biddingId: number
  invitationStatus: string
  finalQuoteAmount: number | null
  finalQuoteSubmittedAt: Date | null
  isWinner: boolean
  isAttendingMeeting: boolean | null
  isBiddingParticipated: boolean | null
  additionalProposals: string | null
  responseSubmittedAt: Date | null
}

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 BiddingPrItemQuotation {
  prItemId: number
  bidUnitPrice: number
  bidAmount: number
  proposedDeliveryDate?: string
  technicalSpecification?: string
}

export function PartnersBiddingDetail({ biddingId, companyId }: PartnersBiddingDetailProps) {
  const router = useRouter()
  const { toast } = useToast()
  const session = useSession()
  const [isPending, startTransition] = useTransition()
  const [biddingDetail, setBiddingDetail] = React.useState<BiddingDetail | null>(null)
  const [isLoading, setIsLoading] = React.useState(true)
  const [isUpdatingParticipation, setIsUpdatingParticipation] = React.useState(false)
  const [isSavingDraft, setIsSavingDraft] = React.useState(false)
  const [isSubmitting, setIsSubmitting] = React.useState(false)
  
  // 품목별 견적 관련 상태
  const [prItems, setPrItems] = React.useState<PrItem[]>([])
  const [prItemQuotations, setPrItemQuotations] = React.useState<BiddingPrItemQuotation[]>([])
  const [totalQuotationAmount, setTotalQuotationAmount] = React.useState(0)

  // 응찰 폼 상태
  const [responseData, setResponseData] = React.useState({
    finalQuoteAmount: '',
    proposedContractDeliveryDate: '',
    additionalProposals: '',
  })
  const userId = session.data?.user?.id || ''


  // 데이터 로드
  React.useEffect(() => {
    const loadData = async () => {
      try {
        setIsLoading(true)
        const [result, prItemsResult] = await Promise.all([
          getBiddingDetailsForPartners(biddingId, companyId),
          getPrItemsForBidding(biddingId)
        ])
        
        if (result) {
          setBiddingDetail(result)

          // 기존 응답 데이터로 폼 초기화
          setResponseData({
            finalQuoteAmount: result.finalQuoteAmount?.toString() || '',
            proposedContractDeliveryDate: result.proposedContractDeliveryDate || '',
            additionalProposals: result.additionalProposals || '',
          })
        }

        // PR 아이템 설정
        setPrItems(prItemsResult)

        // 사전견적 데이터를 본입찰용으로 로드 (응찰 확정 시 또는 사전견적이 있는 경우)
        if (result?.biddingCompanyId) {
          try {
            // 사전견적 데이터를 가져와서 본입찰용으로 변환
            const preQuoteData = await getSavedPrItemQuotations(result.biddingCompanyId)
            
            // 사전견적 데이터를 본입찰 포맷으로 변환
            const convertedQuotations = preQuoteData.map(item => ({
              prItemId: item.prItemId,
              bidUnitPrice: item.bidUnitPrice,
              bidAmount: item.bidAmount,
              proposedDeliveryDate: item.proposedDeliveryDate || undefined,
              technicalSpecification: item.technicalSpecification || undefined
            }))
            
            setPrItemQuotations(convertedQuotations)
            
            // 총 금액 계산
            const total = convertedQuotations.reduce((sum, q) => sum + q.bidAmount, 0)
            setTotalQuotationAmount(total)
            
            // 응찰 확정 시에만 사전견적 금액을 finalQuoteAmount로 설정
            if (totalQuotationAmount > 0 && result.isBiddingParticipated === true) {
              setResponseData(prev => ({
                ...prev,
                finalQuoteAmount: totalQuotationAmount.toString()
              }))
            }
          } catch (error) {
            console.error('Failed to load pre-quote data:', error)
          }
        }
      } catch (error) {
        console.error('Failed to load bidding detail:', error)
        toast({
          title: '오류',
          description: '입찰 정보를 불러오는데 실패했습니다.',
          variant: 'destructive',
        })
      } finally {
        setIsLoading(false)
      }
    }

    loadData()
  }, [biddingId, companyId, toast])

  // 입찰 참여여부 결정 핸들러
  const handleParticipationDecision = async (participated: boolean) => {
    if (!biddingDetail) return

    setIsUpdatingParticipation(true)
    try {
      const result = await updatePartnerBiddingParticipation(
        biddingDetail.biddingCompanyId,
        participated,
        userId
      )

      if (result.success) {
        toast({
          title: participated ? '참여 확정' : '미참여 확정',
          description: participated 
            ? '입찰에 참여하셨습니다. 이제 견적을 작성할 수 있습니다.' 
            : '입찰 참여를 거절하셨습니다.',
        })

        // 데이터 새로고침
        const updatedDetail = await getBiddingDetailsForPartners(biddingId, companyId)
        if (updatedDetail) {
          setBiddingDetail(updatedDetail)
          
          // 참여 확정 시 사전견적 데이터가 있다면 로드
          if (participated && updatedDetail.biddingCompanyId) {
            try {
              const preQuoteData = await getSavedPrItemQuotations(updatedDetail.biddingCompanyId)
              const convertedQuotations = preQuoteData.map(item => ({
                prItemId: item.prItemId,
                bidUnitPrice: item.bidUnitPrice,
                bidAmount: item.bidAmount,
                proposedDeliveryDate: item.proposedDeliveryDate || undefined,
                technicalSpecification: item.technicalSpecification || undefined
              }))
              
              setPrItemQuotations(convertedQuotations)
              const total = convertedQuotations.reduce((sum, q) => sum + q.bidAmount, 0)
              setTotalQuotationAmount(total)
              
              if (total > 0) {
                setResponseData(prev => ({
                  ...prev,
                  finalQuoteAmount: total.toString()
                }))
              }
            } catch (error) {
              console.error('Failed to load pre-quote data after participation:', error)
            }
          }
        }
      } else {
        toast({
          title: '오류',
          description: result.error,
          variant: 'destructive',
        })
      }
    } catch (error) {
      console.error('Failed to update participation:', error)
      toast({
        title: '오류',
        description: '참여여부 업데이트에 실패했습니다.',
        variant: 'destructive',
      })
    } finally {
      setIsUpdatingParticipation(false)
    }
  }

  // 품목별 견적 변경 핸들러
  const handleQuotationsChange = (quotations: BiddingPrItemQuotation[]) => {
    console.log('견적 변경:', quotations)
    setPrItemQuotations(quotations)
  }

  // 총 금액 변경 핸들러
  const handleTotalAmountChange = (total: number) => {
    setTotalQuotationAmount(total)
    // 자동으로 총 견적 금액도 업데이트
    setResponseData(prev => ({
      ...prev,
      finalQuoteAmount: total.toString()
    }))
  }

  // 임시 저장 핸들러
  const handleSaveDraft = async () => {
    if (!biddingDetail || !userId) return
    
    // 입찰 마감 상태 체크
    const biddingStatus = biddingDetail.status
    const isClosed = biddingStatus === 'bidding_closed' || biddingStatus === 'vendor_selected' || biddingStatus === 'bidding_disposal'

    if (isClosed) {
      toast({
        title: "접근 제한",
        description: "입찰이 마감되어 더 이상 입찰에 참여할 수 없습니다.",
        variant: "destructive",
      })
      return
    }
    
    if (prItemQuotations.length === 0) {
      toast({
        title: '저장할 데이터 없음',
        description: '저장할 품목별 견적이 없습니다.',
        variant: 'destructive',
      })
      return
    }

    setIsSavingDraft(true)
    try {
      const quotationsForSave = prItemQuotations.map(q => ({
        prItemId: q.prItemId,
        bidUnitPrice: q.bidUnitPrice,
        bidAmount: q.bidAmount,
        proposedDeliveryDate: q.proposedDeliveryDate,
        technicalSpecification: q.technicalSpecification
      }))
      
      console.log('임시저장 - prItemQuotations:', prItemQuotations)
      console.log('임시저장 - quotationsForSave:', quotationsForSave)
      
      const result = await saveBiddingDraft(
        biddingDetail.biddingCompanyId,
        quotationsForSave,
        userId
      )

      if (result.success) {
        toast({
          title: '임시 저장 완료',
          description: '품목별 견적이 임시 저장되었습니다.',
        })
      } else {
        toast({
          title: '임시 저장 실패',
          description: result.error,
          variant: 'destructive',
        })
      }
    } catch (error) {
      console.error('Failed to save draft:', error)
      toast({
        title: '오류',
        description: '임시 저장에 실패했습니다.',
        variant: 'destructive',
      })
    } finally {
      setIsSavingDraft(false)
    }
  }

  const handleSubmitResponse = () => {
    if (!biddingDetail) return
    // 입찰 마감 상태 체크
    const biddingStatus = biddingDetail.status
    const isClosed = biddingStatus === 'bidding_closed' || biddingStatus === 'vendor_selected' || biddingStatus === 'bidding_disposal'

    if (isClosed) {
      toast({
        title: "접근 제한",
        description: "입찰이 마감되어 더 이상 입찰에 참여할 수 없습니다.",
        variant: "destructive",
      })
      return
    }

    // 필수값 검증
    if (!responseData.finalQuoteAmount.trim()) {
      toast({
        title: '유효성 오류',
        description: '견적 금액을 입력해주세요.',
        variant: 'destructive',
      })
      return
    }

    // 품목별 견적이 있는지 확인
    if (prItems.length > 0 && prItemQuotations.length === 0) {
      toast({
        title: '유효성 오류',
        description: '품목별 견적을 작성해주세요.',
        variant: 'destructive',
      })
      return
    }

    setIsSubmitting(true)
    startTransition(async () => {
      try {
        // 1. 입찰 참여 상태를 응찰로 변경
        const participationResult = await updatePartnerBiddingParticipation(
          biddingDetail.biddingCompanyId,
          true, // 응찰
          userId
        )

        if (!participationResult.success) {
          throw new Error(participationResult.error)
        }

        // 2. 최종 견적 응답 제출 (PR 아이템별 견적 포함)
        const result = await submitPartnerResponse(
          biddingDetail.biddingCompanyId,
          {
            finalQuoteAmount: parseFloat(responseData.finalQuoteAmount),
            proposedContractDeliveryDate: responseData.proposedContractDeliveryDate,
            additionalProposals: responseData.additionalProposals,
            prItemQuotations: prItemQuotations.length > 0 ? prItemQuotations.map(q => ({
              prItemId: q.prItemId,
              bidUnitPrice: q.bidUnitPrice,
              bidAmount: q.bidAmount,
              proposedDeliveryDate: q.proposedDeliveryDate,
              technicalSpecification: q.technicalSpecification
            })) : undefined,
          },
          userId
        )

        if (result.success) {
          toast({
            title: '응찰 완료',
            description: '견적이 성공적으로 제출되었습니다.',
          })

          // 데이터 새로고침
          const updatedDetail = await getBiddingDetailsForPartners(biddingId, companyId)
          if (updatedDetail) {
            setBiddingDetail(updatedDetail)
          }
        } else {
          throw new Error(result.error)
        }
      } catch (error) {
        console.error('Failed to submit response:', error)
        toast({
          title: '오류',
          description: error instanceof Error ? error.message : '응찰 제출에 실패했습니다.',
          variant: 'destructive',
        })
      } finally {
        setIsSubmitting(false)
      }
    })
  }

  if (isLoading) {
    return (
      <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>
    )
  }

  if (!biddingDetail) {
    return (
      <div className="text-center py-12">
        <p className="text-muted-foreground">입찰 정보를 찾을 수 없습니다.</p>
        <Button onClick={() => router.back()} className="mt-4">
          <ArrowLeft className="w-4 h-4 mr-2" />
          돌아가기
        </Button>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 헤더 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button variant="outline" onClick={() => router.back()}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            목록으로
          </Button>
          <div>
            <h1 className="text-2xl font-semibold">{biddingDetail.title}</h1>
            <div className="flex items-center gap-2 mt-1">
              <Badge variant="outline" className="font-mono text-xs">
                {biddingDetail.biddingNumber}
              </Badge>
              <Badge variant="outline" className="font-mono">
                Rev. {biddingDetail.revision ?? 0}
              </Badge>
              <Badge variant={
                biddingDetail.status === 'bidding_disposal' ? 'destructive' :
                biddingDetail.status === 'vendor_selected' ? 'default' :
                'secondary'
              }>
                {biddingStatusLabels[biddingDetail.status]}
              </Badge>
            </div>
          </div>
        </div>

        {/* 입찰 참여여부 상태 표시 */}
        <div className="flex items-center gap-2">
          <Badge variant={
            biddingDetail.isBiddingParticipated === null ? 'outline' :
            biddingDetail.isBiddingParticipated === true ? 'default' : 'destructive'
          }>
            {biddingDetail.isBiddingParticipated === null ? '참여 결정 대기' :
             biddingDetail.isBiddingParticipated === true ? '응찰' : '미응찰'}
          </Badge>
        </div>

      </div>

      {/* 입찰 공고 섹션 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <FileText className="w-5 h-5" />
            입찰 공고
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label className="text-sm font-medium text-muted-foreground">프로젝트</Label>
              <div className="flex items-center gap-2 mt-1">
                <Building2 className="w-4 h-4" />
                <span>{biddingDetail.projectName || '미설정'}</span>
              </div>
            </div>
            <div>
              <Label className="text-sm font-medium text-muted-foreground">품목</Label>
              <div className="flex items-center gap-2 mt-1">
                <Package className="w-4 h-4" />
                <span>{biddingDetail.itemName || '미설정'}</span>
              </div>
            </div>
            <div>
              <Label className="text-sm font-medium text-muted-foreground">계약구분</Label>
              <div className="mt-1">{contractTypeLabels[biddingDetail.contractType]}</div>
            </div>
            <div>
              <Label className="text-sm font-medium text-muted-foreground">입찰유형</Label>
              <div className="mt-1">{biddingTypeLabels[biddingDetail.biddingType]}</div>
            </div>
            <div>
              <Label className="text-sm font-medium text-muted-foreground">낙찰수</Label>
              <div className="mt-1">{biddingDetail.awardCount === 'single' ? '단수' : biddingDetail.awardCount === 'multiple' ? '복수' : '미설정'}</div>
            </div>
            <div>
              <Label className="text-sm font-medium text-muted-foreground">입찰 담당자</Label>
              <div className="flex items-center gap-2 mt-1">
                <User className="w-4 h-4" />
                <span>{biddingDetail.managerName || '미설정'}</span>
              </div>
            </div>
          </div>

          {/* {biddingDetail.budget && (
            <div>
              <Label className="text-sm font-medium text-muted-foreground">예산</Label>
              <div className="flex items-center gap-2 mt-1">
                <DollarSign className="w-4 h-4" />
                <span className="font-semibold">{formatCurrency(biddingDetail.budget)}</span>
              </div>
            </div>
          )} */}

          {/* 일정 정보 */}
          <div className="pt-4 border-t">
            <Label className="text-sm font-medium text-muted-foreground mb-2 block">일정 정보</Label>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-2 text-sm">
              {biddingDetail.submissionStartDate && biddingDetail.submissionEndDate && (
                <div>
                  <span className="font-medium">제출기간:</span> {formatDate(biddingDetail.submissionStartDate, 'KR')} ~ {formatDate(biddingDetail.submissionEndDate, 'KR')}
                </div>
              )}
              {biddingDetail.evaluationDate && (
                <div>
                  <span className="font-medium">평가일:</span> {formatDate(biddingDetail.evaluationDate, 'KR')}
                </div>
              )}
            </div>
          </div>
        </CardContent>
      </Card>


      {/* 참여 상태에 따른 섹션 표시 */}
      {biddingDetail.isBiddingParticipated === false ? (
        /* 미응찰 상태 표시 */
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <XCircle className="w-5 h-5 text-destructive" />
              입찰 참여 거절
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-center py-8">
              <XCircle className="w-16 h-16 text-destructive mx-auto mb-4" />
              <h3 className="text-lg font-semibold text-destructive mb-2">입찰에 참여하지 않기로 결정했습니다</h3>
              <p className="text-muted-foreground">
                해당 입찰에 대한 견적 제출 및 관련 기능은 이용할 수 없습니다.
              </p>
            </div>
          </CardContent>
        </Card>
      ) : biddingDetail.isBiddingParticipated === null ? (
        /* 참여 의사 확인 섹션 */
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Users className="w-5 h-5" />
              입찰 참여 의사 확인
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-center py-8">
              <div className="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center mx-auto mb-4">
                <Users className="w-8 h-8 text-primary" />
              </div>
              <h3 className="text-lg font-semibold mb-2">이 입찰에 참여하시겠습니까?</h3>
              <p className="text-muted-foreground mb-6">
                참여를 선택하시면 견적 작성 및 제출이 가능합니다.
              </p>
              <div className="flex justify-center gap-4">
                <Button 
                  onClick={() => handleParticipationDecision(true)}
                  disabled={isUpdatingParticipation}
                  className="min-w-[120px]"
                >
                  <CheckCircle className="w-4 h-4 mr-2" />
                  참여하기
                </Button>
                <Button 
                  onClick={() => handleParticipationDecision(false)}
                  disabled={isUpdatingParticipation}
                  variant="destructive"
                  className="min-w-[120px]"
                >
                  <XCircle className="w-4 h-4 mr-2" />
                  미참여
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      ) : biddingDetail.isBiddingParticipated === true ? (
        /* 응찰 폼 섹션 */
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Send className="w-5 h-5" />
              응찰하기
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
              {/* 품목별 상세 견적 테이블 */}
              {prItems.length > 0 ? (
                <PrItemsPricingTable
                  prItems={prItems}
                  initialQuotations={prItemQuotations}
                  currency={biddingDetail?.currency || 'KRW'}
                  onQuotationsChange={handleQuotationsChange}
                  onTotalAmountChange={handleTotalAmountChange}
                  readOnly={false}
                />
              ) : (
                <div className="border rounded-lg p-4 bg-muted/20">
                  <p className="text-sm text-muted-foreground text-center py-4">
                    등록된 품목이 없습니다.
                  </p>
            </div>
              )}

          {/* 견적 첨부파일 섹션 */}
          {biddingDetail && userId && (
            <SimpleFileUpload
              biddingId={biddingId}
              companyId={companyId}
              userId={userId}
              readOnly={false}
            />
          )}
          {/* 응찰 제출 버튼 - 참여 확정 상태일 때만 표시 */}
          <div className="flex justify-end pt-4 gap-2">
            <Button
              variant="outline"
              onClick={handleSaveDraft}
              disabled={isSavingDraft || isSubmitting}
              className="min-w-[100px]"
            >
              <Save className="w-4 h-4 mr-2" />
              {isSavingDraft ? '저장 중...' : '임시 저장'}
            </Button>
            <Button
              onClick={handleSubmitResponse}
              disabled={isSubmitting || isSavingDraft || !!biddingDetail.responseSubmittedAt}
              className="min-w-[100px]"
            >
              <Send className="w-4 h-4 mr-2" />
              {isSubmitting ? '제출 중...' : biddingDetail.responseSubmittedAt ? '응찰 완료' : '응찰 제출'}
            </Button>
          </div>
        </CardContent>
      </Card>
      ) : null}
    </div>
  )
}