'use client'

import React, { useState } from 'react'
import { useSession } from 'next-auth/react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Textarea } from '@/components/ui/textarea'
import { Button } from '@/components/ui/button'
import { Save, LoaderIcon } from 'lucide-react'
import { updateContractBasicInfo, getContractBasicInfo } from '../service'
import { toast } from 'sonner'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { GeneralContract } from '@/db/schema'
import { ContractDocuments } from './general-contract-documents'
import { getPaymentTermsForSelection, getIncotermsForSelection, getPlaceOfShippingForSelection, getPlaceOfDestinationForSelection } from '@/lib/procurement-select/service'
import { TAX_CONDITIONS, getTaxConditionName } from '@/lib/tax-conditions/types'
import { GENERAL_CONTRACT_SCOPES } from '@/lib/general-contracts/types'
import { uploadContractAttachment, getContractAttachments, deleteContractAttachment, getContractAttachmentForDownload } from '../service'
import { downloadFile } from '@/lib/file-download'
import { FileText, Upload, Download, Trash2 } from 'lucide-react'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'

interface ContractBasicInfoProps {
  contractId: number
}

export function ContractBasicInfo({ contractId }: ContractBasicInfoProps) {
  const session = useSession()
  const [isLoading, setIsLoading] = useState(false)
  const [contract, setContract] = useState<GeneralContract | null>(null)
  const userId = session.data?.user?.id ? Number(session.data.user.id) : null
  
  // 독립적인 상태 관리
  const [paymentDeliveryPercent, setPaymentDeliveryPercent] = useState('')

  // Procurement 데이터 상태들
  const [paymentTermsOptions, setPaymentTermsOptions] = useState<Array<{code: string, description: string}>>([])
  const [incotermsOptions, setIncotermsOptions] = useState<Array<{code: string, description: string}>>([])
  const [shippingPlaces, setShippingPlaces] = useState<Array<{code: string, description: string}>>([])
  const [destinationPlaces, setDestinationPlaces] = useState<Array<{code: string, description: string}>>([])
  const [procurementLoading, setProcurementLoading] = useState(false)
  
  const [formData, setFormData] = useState({
    contractScope: '', // 계약확정범위
    specificationType: '',
    specificationManualText: '',
    unitPriceType: '',
    warrantyPeriod: {
      납품후: { enabled: false, period: 0, maxPeriod: 0 },
      인도후: { enabled: false, period: 0, maxPeriod: 0 },
      작업후: { enabled: false, period: 0, maxPeriod: 0 },
      기타: { enabled: false, period: 0, maxPeriod: 0 },
    },
    contractAmount: null,
    currency: 'KRW',
    linkedPoNumber: '',
    linkedBidNumber: '',
    notes: '',
    // 개별 JSON 필드들 (스키마에 맞게)
    paymentBeforeDelivery: {},
    paymentDelivery: '', // varchar 타입
    paymentDeliveryAdditionalText: '',
    paymentAfterDelivery: {},
    paymentTerm: '',
    taxType: '',
    liquidatedDamages: false,
    liquidatedDamagesPercent: '',
    deliveryType: '',
    deliveryTerm: '',
    shippingLocation: '',
    dischargeLocation: '',
    contractDeliveryDate: '',
    contractEstablishmentConditions: {
      regularVendorRegistration: false,
      projectAward: false,
      ownerApproval: false,
      other: false,
    },
    interlockingSystem: '',
    mandatoryDocuments: {
      technicalDataAgreement: false,
      nda: false,
      basicCompliance: false,
      safetyHealthAgreement: false,
    },
    contractTerminationConditions: {
      standardTermination: false,
      projectNotAwarded: false,
      other: false,
    },
    externalYardEntry: 'N', // 사외업체 야드투입 (Y/N)
    contractAmountReason: '', // 합의계약 미확정 사유
  })
  
  const [errors] = useState<Record<string, string>>({})
  const [specificationFiles, setSpecificationFiles] = useState<Array<{ id: number; fileName: string; filePath: string; uploadedAt: Date }>>([])
  const [isLoadingSpecFiles, setIsLoadingSpecFiles] = useState(false)
  const [showSpecFileDialog, setShowSpecFileDialog] = useState(false)
  const [unitPriceTypeOther, setUnitPriceTypeOther] = useState<string>('') // 단가 유형 '기타' 수기입력
  const [showYardEntryConfirmDialog, setShowYardEntryConfirmDialog] = useState(false)

  // 계약 데이터 로드
  React.useEffect(() => {
    const loadContract = async () => {
      try {
        console.log('Loading contract with ID:', contractId)
        const contractData = await getContractBasicInfo(contractId)
        console.log('Contract data received:', contractData)
        setContract(contractData as GeneralContract)
        
        // JSON 필드들 파싱 (null 체크) - 스키마에 맞게 개별 필드로 접근
        const paymentBeforeDelivery = (contractData?.paymentBeforeDelivery && typeof contractData.paymentBeforeDelivery === 'object') ? contractData.paymentBeforeDelivery as any : {}
        const paymentAfterDelivery = (contractData?.paymentAfterDelivery && typeof contractData.paymentAfterDelivery === 'object') ? contractData.paymentAfterDelivery as any : {}
        const warrantyPeriod = (contractData?.warrantyPeriod && typeof contractData.warrantyPeriod === 'object') ? contractData.warrantyPeriod as any : {}
        const contractEstablishmentConditions = (contractData?.contractEstablishmentConditions && typeof contractData.contractEstablishmentConditions === 'object') ? contractData.contractEstablishmentConditions as any : {}
        const mandatoryDocuments = (contractData?.mandatoryDocuments && typeof contractData.mandatoryDocuments === 'object') ? contractData.mandatoryDocuments as any : {}
        const contractTerminationConditions = (contractData?.contractTerminationConditions && typeof contractData.contractTerminationConditions === 'object') ? contractData.contractTerminationConditions as any : {}
        
        // paymentDelivery에서 퍼센트와 타입 분리
        const paymentDeliveryValue = contractData?.paymentDelivery || ''
        let paymentDeliveryType = ''
        let paymentDeliveryPercentValue = ''
        
        if (paymentDeliveryValue.includes('%')) {
          const match = paymentDeliveryValue.match(/(\d+)%\s*(.+)/)
          if (match) {
            paymentDeliveryPercentValue = match[1]
            paymentDeliveryType = match[2]
          }
        } else {
          paymentDeliveryType = paymentDeliveryValue
        }
        
        setPaymentDeliveryPercent(paymentDeliveryPercentValue)
        
        // 합의계약(AD, AW)인 경우 인도조건 기본값 설정
        const defaultDeliveryTerm = (contractData?.type === 'AD' || contractData?.type === 'AW') 
          ? '본 표준하도급 계약에 따름'
          : (contractData?.deliveryTerm || '')
        
        setFormData({
          contractScope: contractData?.contractScope || '',
          specificationType: contractData?.specificationType || '',
          specificationManualText: contractData?.specificationManualText || '',
          unitPriceType: contractData?.unitPriceType || '',
          warrantyPeriod: warrantyPeriod || {
            납품후: { enabled: false, period: 0, maxPeriod: 0 },
            인도후: { enabled: false, period: 0, maxPeriod: 0 },
            작업후: { enabled: false, period: 0, maxPeriod: 0 },
            기타: { enabled: false, period: 0, maxPeriod: 0 },
          },
          contractAmount: contractData?.contractAmount || null,
          currency: contractData?.currency || 'KRW',
          linkedPoNumber: contractData?.linkedPoNumber || '',
          linkedBidNumber: contractData?.linkedBidNumber || '',
          notes: contractData?.notes || '',
          // 개별 JSON 필드들
          paymentBeforeDelivery: paymentBeforeDelivery || {} as any,
          paymentDelivery: paymentDeliveryType, // 분리된 타입만 저장
          paymentAfterDelivery: paymentAfterDelivery || {} as any,
          paymentTerm: contractData?.paymentTerm || '',
          taxType: contractData?.taxType || '',
          liquidatedDamages: Boolean(contractData?.liquidatedDamages),
          liquidatedDamagesPercent: contractData?.liquidatedDamagesPercent || '',
          deliveryType: contractData?.deliveryType || '',
          deliveryTerm: defaultDeliveryTerm,
          shippingLocation: contractData?.shippingLocation || '',
          dischargeLocation: contractData?.dischargeLocation || '',
          contractDeliveryDate: contractData?.contractDeliveryDate || '',
          paymentDeliveryAdditionalText: (contractData as any)?.paymentDeliveryAdditionalText || '',
          contractEstablishmentConditions: contractEstablishmentConditions || {
            regularVendorRegistration: false,
            projectAward: false,
            ownerApproval: false,
            other: false,
          },
          interlockingSystem: contractData?.interlockingSystem || '',
          mandatoryDocuments: mandatoryDocuments || {
            technicalDataAgreement: false,
            nda: false,
            basicCompliance: false,
            safetyHealthAgreement: false,
          },
          contractTerminationConditions: contractTerminationConditions || {
            standardTermination: false,
            projectNotAwarded: false,
            other: false,
          },
          externalYardEntry: (contractData?.externalYardEntry as 'Y' | 'N') || 'N',
          contractAmountReason: (contractData as any)?.contractAmountReason || '',
        })
      } catch (error) {
        console.error('Error loading contract:', error)
        toast.error('계약 정보를 불러오는 중 오류가 발생했습니다.')
      }
    }
    
    if (contractId) {
      loadContract()
    }
  }, [contractId])

  // 사양 파일 목록 로드
  React.useEffect(() => {
    const loadSpecificationFiles = async () => {
      if (!contractId || formData.specificationType !== '첨부서류 참조') return
      
      setIsLoadingSpecFiles(true)
      try {
        const attachments = await getContractAttachments(contractId)
        const specFiles = (attachments as Array<{ id: number; fileName: string; filePath: string; documentName: string; uploadedAt: Date }>)
          .filter(att => att.documentName === '사양 및 공급범위' || att.documentName === 'specification')
          .map(att => ({
            id: att.id,
            fileName: att.fileName,
            filePath: att.filePath,
            uploadedAt: att.uploadedAt
          }))
        setSpecificationFiles(specFiles)
      } catch (error) {
        console.error('Error loading specification files:', error)
      } finally {
        setIsLoadingSpecFiles(false)
      }
    }
    
    loadSpecificationFiles()
  }, [contractId, formData.specificationType])

  // Procurement 데이터 로드 함수들
  const loadPaymentTerms = React.useCallback(async () => {
    setProcurementLoading(true);
    try {
      const data = await getPaymentTermsForSelection();
      setPaymentTermsOptions(data);
    } catch (error) {
      console.error("Failed to load payment terms:", error);
      toast.error("결제조건 목록을 불러오는데 실패했습니다.");
    } finally {
      setProcurementLoading(false);
    }
  }, []);

  const loadIncoterms = React.useCallback(async () => {
    setProcurementLoading(true);
    try {
      const data = await getIncotermsForSelection();
      setIncotermsOptions(data);
    } catch (error) {
      console.error("Failed to load incoterms:", error);
      toast.error("운송조건 목록을 불러오는데 실패했습니다.");
    } finally {
      setProcurementLoading(false);
    }
  }, []);

  const loadShippingPlaces = React.useCallback(async () => {
    setProcurementLoading(true);
    try {
      const data = await getPlaceOfShippingForSelection();
      setShippingPlaces(data);
    } catch (error) {
      console.error("Failed to load shipping places:", error);
      toast.error("선적지 목록을 불러오는데 실패했습니다.");
    } finally {
      setProcurementLoading(false);
    }
  }, []);

  const loadDestinationPlaces = React.useCallback(async () => {
    setProcurementLoading(true);
    try {
      const data = await getPlaceOfDestinationForSelection();
      setDestinationPlaces(data);
    } catch (error) {
      console.error("Failed to load destination places:", error);
      toast.error("하역지 목록을 불러오는데 실패했습니다.");
    } finally {
      setProcurementLoading(false);
    }
  }, []);

  // 컴포넌트 마운트 시 procurement 데이터 로드
  React.useEffect(() => {
    loadPaymentTerms();
    loadIncoterms();
    loadShippingPlaces();
    loadDestinationPlaces();
  }, [loadPaymentTerms, loadIncoterms, loadShippingPlaces, loadDestinationPlaces]);
  const handleSaveContractInfo = async () => {
    if (!userId) {
      toast.error('사용자 정보를 찾을 수 없습니다.')
      return
    }
    try {
      setIsLoading(true)
      
      // 필수값 validation 체크
      const validationErrors: string[] = []
      if (!formData.contractScope) validationErrors.push('계약확정범위')
      if (!formData.specificationType) validationErrors.push('사양')
      // 첨부서류 참조 선택 시 사양 파일 필수 체크
      if (formData.specificationType === '첨부서류 참조' && specificationFiles.length === 0) {
        validationErrors.push('사양 파일')
      }
      // LO 계약인 경우 계약체결유효기간 필수값 체크
      if (contract?.type === 'LO' && !contract?.validityEndDate) {
        validationErrors.push('계약체결유효기간')
      }
      if (!formData.paymentDelivery) validationErrors.push('납품 지급조건')
      // 계약확정범위가 '단가' 또는 '물량(실적)'이 아닌 경우에만 계약통화 필수값 체크
      if (formData.contractScope !== '단가' && formData.contractScope !== '물량(실적)' && !formData.currency) {
        validationErrors.push('계약통화')
      }
      if (!formData.paymentTerm) validationErrors.push('지불조건')
      if (!formData.taxType) validationErrors.push('세금조건')
      
      if (validationErrors.length > 0) {
        toast.error(`다음 필수 항목을 입력해주세요: ${validationErrors.join(', ')}`)
        return
      }
      
      // paymentDelivery와 paymentDeliveryPercent 합쳐서 저장
      const dataToSave = {
        ...formData,
        paymentDelivery: (formData.paymentDelivery === 'L/C' || formData.paymentDelivery === 'T/T') && paymentDeliveryPercent
          ? `${paymentDeliveryPercent}% ${formData.paymentDelivery}`
          : formData.paymentDelivery
      }
      
      await updateContractBasicInfo(contractId, dataToSave, userId as number)
      toast.success('계약 정보가 저장되었습니다.')
    } catch (error) {
      console.error('Error saving contract info:', error)
      toast.error('계약 정보 저장 중 오류가 발생했습니다.')
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <Card className="w-full">
      <CardHeader>
        <CardTitle>계약 기본 정보</CardTitle>
      </CardHeader>
      <CardContent>
        <Tabs defaultValue="basic" className="w-full">
          <TabsList className="grid w-full grid-cols-4 h-auto overflow-x-auto">
            <TabsTrigger value="basic" className="text-xs px-2 py-2 whitespace-nowrap">기본 정보</TabsTrigger>
            <TabsTrigger value="conditions" className="text-xs px-2 py-2 whitespace-nowrap">지급/인도 조건</TabsTrigger>
            <TabsTrigger value="additional" className="text-xs px-2 py-2 whitespace-nowrap">추가 조건</TabsTrigger>
            <TabsTrigger value="documents" className="text-xs px-2 py-2 whitespace-nowrap">계약첨부문서</TabsTrigger>
          </TabsList>

      {/* 기본 정보 탭 */}
      <TabsContent value="basic" className="space-y-6">
        <Card>
      {/* 계약확정범위 및 보증기간/단가유형 */}
        <CardHeader>
          <CardTitle>계약확정범위 및 보증기간/단가유형</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* 계약확정범위 */}
          <div className="flex flex-col gap-2">
            <Label htmlFor="contractScope">계약확정범위 *</Label>
            <Select
              value={formData.contractScope}
              onValueChange={(value) => setFormData(prev => ({ ...prev, contractScope: value }))}
            >
              <SelectTrigger>
                <SelectValue placeholder="계약확정범위 선택" />
              </SelectTrigger>
              <SelectContent>
                {GENERAL_CONTRACT_SCOPES.map((scope) => (
                  <SelectItem key={scope} value={scope}>
                    {scope}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          {/* 3그리드: 보증기간, 사양, 단가 */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {/* 보증기간 */}
            <div className="flex flex-col gap-2">
              <Label htmlFor="warrantyPeriod">품질/하자 보증기간</Label>
              <div className="space-y-3">
                <div className="flex items-center space-x-2">
                  <input
                    type="checkbox"
                    id="warrantyAfterDelivery"
                    checked={formData.warrantyPeriod.납품후?.enabled || false}
                    onChange={(e) => setFormData(prev => ({ 
                      ...prev, 
                      warrantyPeriod: { 
                        ...prev.warrantyPeriod, 
                        납품후: { 
                          ...prev.warrantyPeriod.납품후, 
                          enabled: e.target.checked 
                        } 
                      } 
                    }))}
                    className="rounded"
                  />
                  <Label htmlFor="warrantyAfterDelivery" className="text-sm">납품 후</Label>
                </div>
                {formData.warrantyPeriod.납품후?.enabled && (
                  <div className="ml-6 flex items-center space-x-2">
                    <Input
                      type="number"
                      placeholder="보증기간"
                      value={formData.warrantyPeriod.납품후?.period || ''}
                      onChange={(e) => setFormData(prev => ({ 
                        ...prev, 
                        warrantyPeriod: { 
                          ...prev.warrantyPeriod, 
                          납품후: { 
                            ...prev.warrantyPeriod.납품후, 
                            period: parseInt(e.target.value) || 0 
                          } 
                        } 
                      }))}
                      className="w-20 h-8 text-sm"
                    />
                    <span className="text-xs text-muted-foreground">개월, 최대</span>
                    <Input
                      type="number"
                      placeholder="최대"
                      value={formData.warrantyPeriod.납품후?.maxPeriod || ''}
                      onChange={(e) => setFormData(prev => ({ 
                        ...prev, 
                        warrantyPeriod: { 
                          ...prev.warrantyPeriod, 
                          납품후: { 
                            ...prev.warrantyPeriod.납품후, 
                            maxPeriod: parseInt(e.target.value) || 0 
                          } 
                        } 
                      }))}
                      className="w-20 h-8 text-sm"
                    />
                    <span className="text-xs text-muted-foreground">개월</span>
                  </div>
                )}

                <div className="flex items-center space-x-2">
                  <input
                    type="checkbox"
                    id="warrantyAfterHandover"
                    checked={formData.warrantyPeriod.인도후?.enabled || false}
                    onChange={(e) => setFormData(prev => ({ 
                      ...prev, 
                      warrantyPeriod: { 
                        ...prev.warrantyPeriod, 
                        인도후: { 
                          ...prev.warrantyPeriod.인도후, 
                          enabled: e.target.checked 
                        } 
                      } 
                    }))}
                    className="rounded"
                  />
                  <Label htmlFor="warrantyAfterHandover" className="text-sm">인도 후</Label>
                </div>
                {formData.warrantyPeriod.인도후?.enabled && (
                  <div className="ml-6 flex items-center space-x-2">
                    <Input
                      type="number"
                      placeholder="보증기간"
                      value={formData.warrantyPeriod.인도후?.period || ''}
                      onChange={(e) => setFormData(prev => ({ 
                        ...prev, 
                        warrantyPeriod: { 
                          ...prev.warrantyPeriod, 
                          인도후: { 
                            ...prev.warrantyPeriod.인도후, 
                            period: parseInt(e.target.value) || 0 
                          } 
                        } 
                      }))}
                      className="w-20 h-8 text-sm"
                    />
                    <span className="text-xs text-muted-foreground">개월, 최대</span>
                    <Input
                      type="number"
                      placeholder="최대"
                      value={formData.warrantyPeriod.인도후?.maxPeriod || ''}
                      onChange={(e) => setFormData(prev => ({ 
                        ...prev, 
                        warrantyPeriod: { 
                          ...prev.warrantyPeriod, 
                          인도후: { 
                            ...prev.warrantyPeriod.인도후, 
                            maxPeriod: parseInt(e.target.value) || 0 
                          } 
                        } 
                      }))}
                      className="w-20 h-8 text-sm"
                    />
                    <span className="text-xs text-muted-foreground">개월</span>
                  </div>
                )}

                <div className="flex items-center space-x-2">
                  <input
                    type="checkbox"
                    id="warrantyAfterWork"
                    checked={formData.warrantyPeriod.작업후?.enabled || false}
                    onChange={(e) => setFormData(prev => ({ 
                      ...prev, 
                      warrantyPeriod: { 
                        ...prev.warrantyPeriod, 
                        작업후: { 
                          ...prev.warrantyPeriod.작업후, 
                          enabled: e.target.checked 
                        } 
                      } 
                    }))}
                    className="rounded"
                  />
                  <Label htmlFor="warrantyAfterWork" className="text-sm">작업 후</Label>
                </div>
                {formData.warrantyPeriod.작업후?.enabled && (
                  <div className="ml-6 flex items-center space-x-2">
                    <Input
                      type="number"
                      placeholder="보증기간"
                      value={formData.warrantyPeriod.작업후?.period || ''}
                      onChange={(e) => setFormData(prev => ({ 
                        ...prev, 
                        warrantyPeriod: { 
                          ...prev.warrantyPeriod, 
                          작업후: { 
                            ...prev.warrantyPeriod.작업후, 
                            period: parseInt(e.target.value) || 0 
                          } 
                        } 
                      }))}
                      className="w-20 h-8 text-sm"
                    />
                    <span className="text-xs text-muted-foreground">개월, 최대</span>
                    <Input
                      type="number"
                      placeholder="최대"
                      value={formData.warrantyPeriod.작업후?.maxPeriod || ''}
                      onChange={(e) => setFormData(prev => ({ 
                        ...prev, 
                        warrantyPeriod: { 
                          ...prev.warrantyPeriod, 
                          작업후: { 
                            ...prev.warrantyPeriod.작업후, 
                            maxPeriod: parseInt(e.target.value) || 0 
                          } 
                        } 
                      }))}
                      className="w-20 h-8 text-sm"
                    />
                    <span className="text-xs text-muted-foreground">개월</span>
                  </div>
                )}

                <div className="flex items-center space-x-2">
                  <input
                    type="checkbox"
                    id="warrantyOther"
                    checked={formData.warrantyPeriod.기타?.enabled || false}
                    onChange={(e) => setFormData(prev => ({ 
                      ...prev, 
                      warrantyPeriod: { 
                        ...prev.warrantyPeriod, 
                        기타: { 
                          ...prev.warrantyPeriod.기타, 
                          enabled: e.target.checked 
                        } 
                      } 
                    }))}
                    className="rounded"
                  />
                  <Label htmlFor="warrantyOther" className="text-sm">기타/미적용</Label>
                </div>
              </div>
            </div>
            {/* 사양 */}
            <div className="flex flex-col gap-2">
              <Label htmlFor="specificationType">사양 <span className="text-red-600">*</span></Label>
              <Select value={formData.specificationType} onValueChange={(value) => setFormData(prev => ({ ...prev, specificationType: value }))}>
                <SelectTrigger className={errors.specificationType ? 'border-red-500' : ''}>
                  <SelectValue placeholder="사양을 선택하세요" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="첨부서류 참조">첨부서류 참조</SelectItem>
                  <SelectItem value="표준사양">표준사양</SelectItem>
                  <SelectItem value="수기사양">수기사양</SelectItem>
                </SelectContent>
              </Select>
                {errors.specificationType && (
                  <p className="text-sm text-red-600">사양은 필수값입니다.</p>
                )}
            </div>
            {/* 단가 */}
            <div className="flex flex-col gap-2">
              <Label htmlFor="unitPriceType">
                단가 유형
                {(() => {
                  const contractType = contract?.type as string || ''
                  const contractCategory = contract?.category as string || ''
                  const unitPriceContractTypes = ['UP', 'LE', 'IL', 'AL', 'OS', 'OW']
                  const isUnitPriceRequired = contractCategory === 'unit_price' && unitPriceContractTypes.includes(contractType)
                  return isUnitPriceRequired ? <span className="text-red-600 ml-1">*</span> : null
                })()}
              </Label>
              <Select value={formData.unitPriceType} onValueChange={(value) => setFormData(prev => ({ ...prev, unitPriceType: value }))}>
                <SelectTrigger className={
                  (() => {
                    const contractType = contract?.type as string || ''
                    const contractCategory = contract?.category as string || ''
                    const unitPriceContractTypes = ['UP', 'LE', 'IL', 'AL', 'OS', 'OW']
                    const isUnitPriceRequired = contractCategory === 'unit_price' && unitPriceContractTypes.includes(contractType)
                    return isUnitPriceRequired && !formData.unitPriceType ? 'border-red-500' : ''
                  })()
                }>
                  <SelectValue placeholder="단가 유형을 선택하세요" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="자재개별단가">자재개별단가</SelectItem>
                  <SelectItem value="서비스용역단가">서비스용역단가</SelectItem>
                  <SelectItem value="프로젝트단가">프로젝트단가</SelectItem>
                  <SelectItem value="지역별단가">지역별단가</SelectItem>
                  <SelectItem value="직무직급단가">직무직급단가</SelectItem>
                  <SelectItem value="단계별단가">단계별단가</SelectItem>
                  <SelectItem value="기타">기타</SelectItem>
                </SelectContent>
              </Select>
              {/* 단가 유형 '기타' 선택 시 수기입력 필드 */}
              {formData.unitPriceType === '기타' && (
                <div className="mt-2">
                  <Input
                    value={unitPriceTypeOther}
                    onChange={(e) => setUnitPriceTypeOther(e.target.value)}
                    placeholder="단가 유형을 수기로 입력하세요"
                    className="mt-2"
                    required
                  />
                </div>
              )}
              {(() => {
                const contractType = contract?.type as string || ''
                const contractCategory = contract?.category as string || ''
                const unitPriceContractTypes = ['UP', 'LE', 'IL', 'AL', 'OS', 'OW']
                const isUnitPriceRequired = contractCategory === 'unit_price' && unitPriceContractTypes.includes(contractType)
                return isUnitPriceRequired && !formData.unitPriceType ? (
                  <p className="text-sm text-red-600">단가 유형은 필수값입니다.</p>
                ) : formData.unitPriceType === '기타' && !unitPriceTypeOther.trim() ? (
                  <p className="text-sm text-red-600">단가 유형(기타)을 입력해주세요.</p>
                ) : null
              })()}
            </div>
            {/* 선택에 따른 폼: vertical로 출력 */}
        

          {/* 사양이 수기사양일 때 매뉴얼 텍스트 */}
          {formData.specificationType === '수기사양' && (
            <div className="flex flex-col gap-2">
              <Label htmlFor="specificationManualText">사양 매뉴얼 텍스트</Label>
              <Textarea
                value={formData.specificationManualText}
                onChange={(e) => setFormData(prev => ({ ...prev, specificationManualText: e.target.value }))}
                placeholder="사양 매뉴얼 텍스트를 입력하세요"
                rows={3}
              />
            </div>
          )}

          {/* 사양이 첨부서류 참조일 때 파일 업로드 */}
          {formData.specificationType === '첨부서류 참조' && (
            <div className="flex flex-col gap-2">
              <div className="flex items-center justify-between">
                <Label htmlFor="specificationFile">
                  사양 파일 <span className="text-red-600">*</span>
                </Label>
                <Dialog open={showSpecFileDialog} onOpenChange={setShowSpecFileDialog}>
                  <DialogTrigger asChild>
                    <Button variant="outline" size="sm" type="button">
                      <Upload className="h-4 w-4 mr-2" />
                      파일 업로드
                    </Button>
                  </DialogTrigger>
                  <DialogContent className="max-w-2xl">
                    <DialogHeader>
                      <DialogTitle>사양 파일 업로드</DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4">
                      <div>
                        <Label htmlFor="file-upload">파일 선택</Label>
                        <Input
                          id="file-upload"
                          type="file"
                          onChange={async (e) => {
                            const file = e.target.files?.[0]
                            if (!file || !userId) return
                            
                            try {
                              setIsLoadingSpecFiles(true)
                              const result = await uploadContractAttachment(
                                contractId,
                                file,
                                userId.toString(),
                                '사양 및 공급범위'
                              )
                              
                              if (result.success) {
                                toast.success('사양 파일이 업로드되었습니다.')
                                // 파일 목록 새로고침
                                const attachments = await getContractAttachments(contractId)
                                const specFiles = (attachments as Array<{ id: number; fileName: string; filePath: string; documentName: string; uploadedAt: Date }>)
                                  .filter(att => att.documentName === '사양 및 공급범위' || att.documentName === 'specification')
                                  .map(att => ({
                                    id: att.id,
                                    fileName: att.fileName,
                                    filePath: att.filePath,
                                    uploadedAt: att.uploadedAt
                                  }))
                                setSpecificationFiles(specFiles)
                                setShowSpecFileDialog(false)
                                e.target.value = ''
                              } else {
                                toast.error(result.error || '파일 업로드에 실패했습니다.')
                              }
                            } catch (error) {
                              console.error('Error uploading file:', error)
                              toast.error('파일 업로드 중 오류가 발생했습니다.')
                            } finally {
                              setIsLoadingSpecFiles(false)
                            }
                          }}
                          disabled={isLoadingSpecFiles}
                        />
                      </div>
                      
                      {/* 업로드된 파일 목록 */}
                      {specificationFiles.length > 0 && (
                        <div className="space-y-2">
                          <Label>업로드된 파일</Label>
                          <div className="space-y-2 max-h-60 overflow-y-auto">
                            {specificationFiles.map((file) => (
                              <div key={file.id} className="flex items-center justify-between p-2 border rounded">
                                <div className="flex items-center gap-2">
                                  <FileText className="h-4 w-4 text-muted-foreground" />
                                  <span className="text-sm">{file.fileName}</span>
                                  <span className="text-xs text-muted-foreground">
                                    ({new Date(file.uploadedAt).toLocaleDateString()})
                                  </span>
                                </div>
                                <div className="flex items-center gap-2">
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={async () => {
                                      try {
                                        const fileData = await getContractAttachmentForDownload(file.id, contractId)
                                        downloadFile(fileData.attachment?.filePath || '', fileData.attachment?.fileName || '', {
                                          showToast: true
                                        })
                                      } catch (error) {
                                        console.error('Error downloading file:', error)
                                        toast.error('파일 다운로드 중 오류가 발생했습니다.')
                                      }
                                    }}
                                  >
                                    <Download className="h-4 w-4" />
                                  </Button>
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={async () => {
                                      try {
                                        await deleteContractAttachment(file.id, contractId)
                                        toast.success('파일이 삭제되었습니다.')
                                        setSpecificationFiles(prev => prev.filter(f => f.id !== file.id))
                                      } catch (error) {
                                        console.error('Error deleting file:', error)
                                        toast.error('파일 삭제 중 오류가 발생했습니다.')
                                      }
                                    }}
                                    className="text-red-600 hover:text-red-700"
                                  >
                                    <Trash2 className="h-4 w-4" />
                                  </Button>
                                </div>
                              </div>
                            ))}
                          </div>
                        </div>
                      )}
                    </div>
                  </DialogContent>
                </Dialog>
              </div>
              
              {specificationFiles.length === 0 && (
                <p className="text-sm text-red-600">사양 파일을 업로드해주세요.</p>
              )}
              
              {specificationFiles.length > 0 && (
                <div className="space-y-2">
                  {specificationFiles.map((file) => (
                    <div key={file.id} className="flex items-center justify-between p-2 border rounded text-sm">
                      <div className="flex items-center gap-2">
                        <FileText className="h-4 w-4 text-muted-foreground" />
                        <span>{file.fileName}</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={async () => {
                            try {
                              const fileData = await getContractAttachmentForDownload(file.id, contractId)
                              downloadFile(fileData.attachment?.filePath || '', fileData.attachment?.fileName || '', {
                                showToast: true
                              })
                            } catch (error) {
                              console.error('Error downloading file:', error)
                              toast.error('파일 다운로드 중 오류가 발생했습니다.')
                            }
                          }}
                        >
                          <Download className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={async () => {
                            try {
                              await deleteContractAttachment(file.id, contractId)
                              toast.success('파일이 삭제되었습니다.')
                              setSpecificationFiles(prev => prev.filter(f => f.id !== file.id))
                            } catch (error) {
                              console.error('Error deleting file:', error)
                              toast.error('파일 삭제 중 오류가 발생했습니다.')
                            }
                          }}
                          className="text-red-600 hover:text-red-700"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          </div>

          
        </CardContent>
      </Card>
      </TabsContent>

      {/* 지급/인도 조건 탭 */}
      <TabsContent value="conditions" className="space-y-6">
        <Card>
          <CardHeader>
            <CardTitle>Payment & Delivery Conditions (지급/인도 조건)</CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="grid grid-cols-6 gap-4">
              {/* 납품 전 지급조건 */}
              <div className="space-y-2">
                <Label className="text-sm font-medium">납품 전</Label>
                <div className="space-y-2">
                  <div className="flex items-center space-x-1">
                    <input
                      type="checkbox"
                    id="apBond"
                      checked={formData.paymentBeforeDelivery.apBond || false}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentBeforeDelivery: {
                          ...prev.paymentBeforeDelivery,
                          apBond: e.target.checked
                        }
                      }))}
                      className="rounded w-4 h-4"
                    />
                    <Label htmlFor="apBond" className="text-xs">AP Bond</Label>
                    <Input
                      type="number"
                      min="0"
                      placeholder="%"
                      className="w-16 h-6 text-xs"
                      value={formData.paymentBeforeDelivery.apBondPercent || ''}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentBeforeDelivery: {
                          ...prev.paymentBeforeDelivery,
                          apBondPercent: e.target.value
                        }
                      }))}
                      disabled={!formData.paymentBeforeDelivery.apBond}
                    />
                  </div>
                  <div className="flex items-center space-x-1">
                    <input
                      type="checkbox"
                    id="drawingSubmission"
                      checked={formData.paymentBeforeDelivery.drawingSubmission || false}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentBeforeDelivery: {
                          ...prev.paymentBeforeDelivery,
                          drawingSubmission: e.target.checked
                        }
                      }))}
                      className="rounded w-4 h-4"
                    />
                    <Label htmlFor="drawingSubmission" className="text-xs">도면제출</Label>
                    <Input
                      type="number"
                      min="0"
                      placeholder="%"
                      className="w-16 h-6 text-xs"
                      value={formData.paymentBeforeDelivery.drawingSubmissionPercent || ''}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentBeforeDelivery: {
                          ...prev.paymentBeforeDelivery,
                          drawingSubmissionPercent: e.target.value
                        }
                      }))}
                      disabled={!formData.paymentBeforeDelivery.drawingSubmission}
                    />
                  </div>
                  <div className="flex items-center space-x-1">
                    <input
                      type="checkbox"
                    id="materialPurchase"
                      checked={formData.paymentBeforeDelivery.materialPurchase || false}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentBeforeDelivery: {
                          ...prev.paymentBeforeDelivery,
                          materialPurchase: e.target.checked
                        }
                      }))}
                      className="rounded w-4 h-4"
                    />
                    <Label htmlFor="materialPurchase" className="text-xs">소재구매</Label>
                    <Input
                      type="number"
                      min="0"
                      placeholder="%"
                      className="w-16 h-6 text-xs"
                      value={formData.paymentBeforeDelivery.materialPurchasePercent || ''}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentBeforeDelivery: {
                          ...prev.paymentBeforeDelivery,
                          materialPurchasePercent: e.target.value
                        }
                      }))}
                      disabled={!formData.paymentBeforeDelivery.materialPurchase}
                    />
                  </div>
                  <div className="flex items-center space-x-1">
                    <input
                      type="checkbox"
                      id="additionalConditionBefore"
                      checked={formData.paymentBeforeDelivery.additionalCondition || false}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentBeforeDelivery: {
                          ...prev.paymentBeforeDelivery,
                          additionalCondition: e.target.checked
                        }
                      }))}
                      className="rounded w-4 h-4"
                    />
                    <Label htmlFor="additionalConditionBefore" className="text-xs">추가조건</Label>
                    <Input
                      type="number"
                      min="0"
                      placeholder="%"
                      className="w-16 h-6 text-xs"
                      value={formData.paymentBeforeDelivery.additionalConditionPercent || ''}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentBeforeDelivery: {
                          ...prev.paymentBeforeDelivery,
                          additionalConditionPercent: e.target.value
                        }
                      }))}
                      disabled={!formData.paymentBeforeDelivery.additionalCondition}
                    />
                  </div>
                </div>
              </div>

              {/* 납품 지급조건 */}
              <div className="space-y-2">
                <Label className="text-sm font-medium">납품</Label>
                <div className="space-y-2">
                  <div className="space-y-1">
                    <Label htmlFor="paymentDelivery" className="text-xs">지급조건 *</Label>
                    <Select value={formData.paymentDelivery} onValueChange={(value) => setFormData(prev => ({ ...prev, paymentDelivery: value }))}>
                      <SelectTrigger className={`h-8 text-xs ${errors.paymentDelivery ? 'border-red-500' : ''}`}>
                        <SelectValue placeholder="선택" />
                      </SelectTrigger>
                      <SelectContent>
                        {paymentTermsOptions.map((term) => (
                          <SelectItem key={term.code} value={term.code} className="text-xs">
                            {term.code}
                          </SelectItem>
                        ))}
                        <SelectItem value="납품완료일로부터 60일 이내 지급" className="text-xs">60일 이내</SelectItem>
                        <SelectItem value="추가조건" className="text-xs">추가조건</SelectItem>
                      </SelectContent>
                    </Select>
                    {formData.paymentDelivery === '추가조건' && (
                      <Input
                        type="text"
                        value={formData.paymentDeliveryAdditionalText || ''}
                        onChange={(e) => setFormData(prev => ({ ...prev, paymentDeliveryAdditionalText: e.target.value }))}
                        placeholder="추가조건"
                        className="h-6 text-xs mt-1"
                      />
                    )}
                  </div>
                </div>
              </div>

              {/* 납품 외 지급조건 */}
              <div className="space-y-2">
                <Label className="text-sm font-medium">납품 외</Label>
                <div className="space-y-2">
                  <div className="flex items-center space-x-1">
                    <input
                      type="checkbox"
                    id="commissioning"
                      checked={formData.paymentAfterDelivery.commissioning || false}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentAfterDelivery: {
                          ...prev.paymentAfterDelivery,
                          commissioning: e.target.checked
                        }
                      }))}
                      className="rounded w-4 h-4"
                    />
                    <Label htmlFor="commissioning" className="text-xs">Commissioning</Label>
                    <Input
                      type="number"
                      min="0"
                      placeholder="%"
                      className="w-16 h-6 text-xs"
                      value={formData.paymentAfterDelivery.commissioningPercent || ''}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentAfterDelivery: {
                          ...prev.paymentAfterDelivery,
                          commissioningPercent: e.target.value
                        }
                      }))}
                      disabled={!formData.paymentAfterDelivery.commissioning}
                    />
                  </div>
                  <div className="flex items-center space-x-1">
                    <input
                      type="checkbox"
                    id="finalDocument"
                      checked={formData.paymentAfterDelivery.finalDocument || false}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentAfterDelivery: {
                          ...prev.paymentAfterDelivery,
                          finalDocument: e.target.checked
                        }
                      }))}
                      className="rounded w-4 h-4"
                    />
                    <Label htmlFor="finalDocument" className="text-xs">최종문서</Label>
                    <Input
                      type="number"
                      min="0"
                      placeholder="%"
                      className="w-16 h-6 text-xs"
                      value={formData.paymentAfterDelivery.finalDocumentPercent || ''}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentAfterDelivery: {
                          ...prev.paymentAfterDelivery,
                          finalDocumentPercent: e.target.value
                        }
                      }))}
                      disabled={!formData.paymentAfterDelivery.finalDocument}
                    />
                  </div>
                  <div className="flex items-center space-x-1">
                    <input
                      type="checkbox"
                      id="other"
                      checked={formData.paymentAfterDelivery.other || false}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentAfterDelivery: {
                          ...prev.paymentAfterDelivery,
                          other: e.target.checked
                        }
                      }))}
                      className="rounded w-4 h-4"
                    />
                    <Label htmlFor="other" className="text-xs">기타</Label>
                    <Input
                      type="text"
                      placeholder="기타"
                      className="w-16 h-6 text-xs"
                      value={formData.paymentAfterDelivery.otherText || ''}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        paymentAfterDelivery: {
                          ...prev.paymentAfterDelivery,
                          otherText: e.target.value
                        }
                      }))}
                      disabled={!formData.paymentAfterDelivery.other}
                    />
                  </div>
                </div>
              </div>

              {/* 지불조건 */}
              <div className="space-y-2">
                <Label className="text-sm font-medium">지불조건</Label>
                <div className="space-y-2">
                  <div className="space-y-1">
                    <Label htmlFor="paymentTerm" className="text-xs">지불조건 *</Label>
                    <Select
                      value={formData.paymentTerm}
                      onValueChange={(value) => setFormData(prev => ({ ...prev, paymentTerm: value }))}
                    >
                      <SelectTrigger className={`h-8 text-xs ${errors.paymentTerm ? 'border-red-500' : ''}`}>
                        <SelectValue placeholder="선택" />
                      </SelectTrigger>
                      <SelectContent>
                        {paymentTermsOptions.length > 0 ? (
                          paymentTermsOptions.map((option) => (
                            <SelectItem key={option.code} value={option.code} className="text-xs">
                              {option.code}
                            </SelectItem>
                          ))
                        ) : (
                          <SelectItem value="loading" disabled className="text-xs">
                            로딩중...
                          </SelectItem>
                        )}
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="space-y-1">
                    <Label htmlFor="taxType" className="text-xs">세금조건 *</Label>
                    <Select
                      value={formData.taxType}
                      onValueChange={(value) => setFormData(prev => ({ ...prev, taxType: value }))}
                    >
                      <SelectTrigger className={`h-8 text-xs ${errors.taxType ? 'border-red-500' : ''}`}>
                        <SelectValue placeholder="선택" />
                      </SelectTrigger>
                      <SelectContent>
                        {TAX_CONDITIONS.map((condition) => (
                          <SelectItem key={condition.code} value={condition.code} className="text-xs">
                            {condition.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </div>
              </div>

              {/* 클레임금액 */}
              <div className="space-y-2">
                <Label className="text-sm font-medium">클레임금액</Label>
                <div className="space-y-2">
                  <div className="flex items-center space-x-1">
                    <input
                      type="checkbox"
                    id="liquidatedDamages"
                      checked={formData.liquidatedDamages || false}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        liquidatedDamages: e.target.checked
                      }))}
                      className="rounded w-4 h-4"
                    />
                    <Label htmlFor="liquidatedDamages" className="text-xs">지체상금</Label>
                    <Input
                      type="number"
                      min="0"
                      placeholder="%"
                      className="w-16 h-6 text-xs"
                      value={formData.liquidatedDamagesPercent || ''}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        liquidatedDamagesPercent: e.target.value
                      }))}
                      disabled={!formData.liquidatedDamages}
                    />
                  </div>
                </div>
              </div>
            </div>

            {/* 인도조건 섹션 */}
            <div className="mt-6">
              <h3 className="text-base font-semibold mb-3">인도조건</h3>
              <div className="grid grid-cols-6 gap-4">
                {/* 납기종류 */}
                <div className="space-y-2">
                  <Label htmlFor="deliveryType" className="text-xs">납기종류</Label>
                  <Select value={formData.deliveryType} onValueChange={(value) => setFormData(prev => ({ ...prev, deliveryType: value }))}>
                    <SelectTrigger className="h-8 text-xs">
                      <SelectValue placeholder="선택" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="단일납기" className="text-xs">단일납기</SelectItem>
                      <SelectItem value="분할납기" className="text-xs">분할납기</SelectItem>
                      <SelectItem value="구간납기" className="text-xs">구간납기</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                {/* 인도조건 */}
                <div className="space-y-2">
                  <Label htmlFor="deliveryTerm" className="text-xs">인도조건</Label>
                  <Select
                    value={formData.deliveryTerm}
                    onValueChange={(value) => setFormData(prev => ({ ...prev, deliveryTerm: value }))}
                  >
                    <SelectTrigger className="h-8 text-xs">
                      <SelectValue placeholder="선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {incotermsOptions.length > 0 ? (
                        incotermsOptions.map((option) => (
                          <SelectItem key={option.code} value={option.code} className="text-xs">
                            {option.code}
                          </SelectItem>
                        ))
                      ) : (
                        <SelectItem value="loading" disabled className="text-xs">
                          로딩중...
                        </SelectItem>
                      )}
                    </SelectContent>
                  </Select>
                </div>

                {/* 선적지 */}
                <div className="space-y-2">
                  <Label htmlFor="shippingLocation" className="text-xs">선적지</Label>
                  <Select
                    value={formData.shippingLocation}
                    onValueChange={(value) => setFormData(prev => ({ ...prev, shippingLocation: value }))}
                  >
                    <SelectTrigger className="h-8 text-xs">
                      <SelectValue placeholder="선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {shippingPlaces.length > 0 ? (
                        shippingPlaces.map((place) => (
                          <SelectItem key={place.code} value={place.code} className="text-xs">
                            {place.code}
                          </SelectItem>
                        ))
                      ) : (
                        <SelectItem value="loading" disabled className="text-xs">
                          로딩중...
                        </SelectItem>
                      )}
                    </SelectContent>
                  </Select>
                </div>

                {/* 하역지 */}
                <div className="space-y-2">
                  <Label htmlFor="dischargeLocation" className="text-xs">하역지</Label>
                  <Select
                    value={formData.dischargeLocation}
                    onValueChange={(value) => setFormData(prev => ({ ...prev, dischargeLocation: value }))}
                  >
                    <SelectTrigger className="h-8 text-xs">
                      <SelectValue placeholder="선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {destinationPlaces.length > 0 ? (
                        destinationPlaces.map((place) => (
                          <SelectItem key={place.code} value={place.code} className="text-xs">
                            {place.code}
                          </SelectItem>
                        ))
                      ) : (
                        <SelectItem value="loading" disabled className="text-xs">
                          로딩중...
                        </SelectItem>
                      )}
                    </SelectContent>
                  </Select>
                </div>

                {/* 계약납기일 */}
                <div className="space-y-2">
                  <Label htmlFor="contractDeliveryDate" className="text-xs">계약납기일</Label>
                  <Input
                    type="date"
                    value={formData.contractDeliveryDate}
                    onChange={(e) => setFormData(prev => ({ ...prev, contractDeliveryDate: e.target.value }))}
                    className="h-8 text-xs"
                  />
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      </TabsContent>

      {/* 추가 조건 탭 */}
      <TabsContent value="additional" className="space-y-6">
        <Card>
          <CardHeader>
            <CardTitle>Additional Conditions (추가조건)</CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="contractAmount">계약금액 (자동계산)</Label>
                {(contract?.type === 'AD' || contract?.type === 'AW') || formData.contractScope === '단가' || formData.contractScope === '물량(실적)' ? (
                  <div className="space-y-2">
                    <Input
                      type="text"
                      value="미확정"
                      readOnly
                      className="bg-gray-50"
                    />
                    <div className="flex flex-col gap-2">
                      <Label htmlFor="contractAmountReason">미확정 사유</Label>
                      <Textarea
                        id="contractAmountReason"
                        value={formData.contractAmountReason}
                        onChange={(e) => setFormData(prev => ({ ...prev, contractAmountReason: e.target.value }))}
                        placeholder="계약금액 미확정 사유를 입력하세요"
                        rows={3}
                      />
                    </div>
                  </div>
                ) : (
                  <Input
                    type="text"
                    value={contract?.contractAmount ? new Intl.NumberFormat('ko-KR').format(Number(contract.contractAmount)) : '품목정보 없음'}
                    readOnly
                    className="bg-gray-50"
                    placeholder="품목정보에서 자동 계산됩니다"
                  />
                )}
              </div>
              <div className="space-y-2">
                <Label htmlFor="currency">
                  계약통화
                  {formData.contractScope !== '단가' && formData.contractScope !== '물량(실적)' && <span className="text-red-600">*</span>}
                </Label>
                <Input
                  type="text"
                  value={formData.currency}
                  onChange={(e) => setFormData(prev => ({ ...prev, currency: e.target.value }))}
                  placeholder="계약통화를 입력하세요"
                  className={`${errors.currency ? 'border-red-500' : ''} ${formData.contractScope === '단가' || formData.contractScope === '물량(실적)' ? 'bg-gray-50' : ''}`}
                  disabled={formData.contractScope === '단가' || formData.contractScope === '물량(실적)'}
                />
                {errors.currency && formData.contractScope !== '단가' && formData.contractScope !== '물량(실적)' && (
                  <p className="text-sm text-red-600">계약통화는 필수값입니다.</p>
                )}
              </div>

              {/* 사외업체 야드투입 */}
              <div className="space-y-4 col-span-2">
                <Label className="text-base font-medium">사외업체 야드투입</Label>
                <div className="flex items-center space-x-4">
                  <div className="flex items-center space-x-2">
                    <input
                      type="radio"
                      id="yardEntryYes"
                      name="externalYardEntry"
                      value="Y"
                      checked={formData.externalYardEntry === 'Y'}
                      onChange={(e) => setFormData(prev => ({ ...prev, externalYardEntry: 'Y' as 'Y' | 'N' }))}
                      className="rounded"
                    />
                    <Label htmlFor="yardEntryYes">Y</Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <input
                      type="radio"
                      id="yardEntryNo"
                      name="externalYardEntry"
                      value="N"
                      checked={formData.externalYardEntry === 'N'}
                      onChange={(e) => {
                        // 이전 값이 'Y'였고 'N'으로 변경하는 경우 팝업 표시
                        if (formData.externalYardEntry === 'Y') {
                          setShowYardEntryConfirmDialog(true)
                        } else {
                          setFormData(prev => ({ ...prev, externalYardEntry: 'N' as 'Y' | 'N' }))
                        }
                      }}
                      className="rounded"
                    />
                    <Label htmlFor="yardEntryNo">N</Label>
                  </div>
                </div>
                {/* 사외업체 야드투입 'N' 선택 시 확인 팝업 */}
                <Dialog open={showYardEntryConfirmDialog} onOpenChange={setShowYardEntryConfirmDialog}>
                  <DialogContent>
                    <DialogHeader>
                      <DialogTitle>안전필수사항 확인</DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4">
                      <p className="text-sm text-muted-foreground">
                        안전필수사항으로 사내작업여부를 재확인 바랍니다.
                      </p>
                      <div className="flex justify-end gap-2">
                        <Button
                          variant="outline"
                          onClick={() => {
                            setShowYardEntryConfirmDialog(false)
                            // 라디오 버튼을 다시 'Y'로 되돌림
                            const yardEntryYesRadio = document.getElementById('yardEntryYes') as HTMLInputElement
                            if (yardEntryYesRadio) {
                              yardEntryYesRadio.checked = true
                            }
                          }}
                        >
                          취소
                        </Button>
                        <Button
                          onClick={() => {
                            setFormData(prev => ({ ...prev, externalYardEntry: 'N' as 'Y' | 'N' }))
                            setShowYardEntryConfirmDialog(false)
                          }}
                        >
                          확인
                        </Button>
                      </div>
                    </div>
                  </DialogContent>
                </Dialog>
              </div>

              {/* 계약성립조건 */}
              <div className="space-y-4 col-span-2">
                <Label className="text-base font-medium">계약성립조건</Label>
                <div className="space-y-3">
                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      id="regularVendorRegistration"
                      checked={formData.contractEstablishmentConditions.regularVendorRegistration}
                      onChange={(e) => setFormData(prev => ({ ...prev, contractEstablishmentConditions: { ...prev.contractEstablishmentConditions, regularVendorRegistration: e.target.checked } }))}
                      className="rounded"
                    />
                    <Label htmlFor="regularVendorRegistration">정규업체 등록(실사 포함) 시</Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      id="projectAward"
                      checked={formData.contractEstablishmentConditions.projectAward}
                      onChange={(e) => setFormData(prev => ({ ...prev, contractEstablishmentConditions: { ...prev.contractEstablishmentConditions, projectAward: e.target.checked } }))}
                      className="rounded"
                    />
                    <Label htmlFor="projectAward">프로젝트 수주 시</Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      id="ownerApproval"
                      checked={formData.contractEstablishmentConditions.ownerApproval}
                      onChange={(e) => setFormData(prev => ({ ...prev, contractEstablishmentConditions: { ...prev.contractEstablishmentConditions, ownerApproval: e.target.checked } }))}
                      className="rounded"
                    />
                    <Label htmlFor="ownerApproval">선주 승인 시</Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      id="establishmentOther"
                      checked={formData.contractEstablishmentConditions.other}
                      onChange={(e) => setFormData(prev => ({ ...prev, contractEstablishmentConditions: { ...prev.contractEstablishmentConditions, other: e.target.checked } }))}
                      className="rounded"
                    />
                    <Label htmlFor="establishmentOther">기타</Label>
                  </div>
                </div>
              </div>

              {/* 연동제적용 */}
              <div className="space-y-4">
                <Label className="text-base font-medium">연동제적용</Label>
                <div className="space-y-2">
                  <Select value={formData.interlockingSystem} onValueChange={(value) => setFormData(prev => ({ ...prev, interlockingSystem: value }))}>
                    <SelectTrigger>
                      <SelectValue placeholder="연동제적용을 선택하세요" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="Y">Y</SelectItem>
                      <SelectItem value="N">N</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              {/* 필수문서동의 */}
              {/* <div className="space-y-4">
                <Label className="text-base font-medium">필수문서동의</Label>
                <div className="space-y-3">
                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      id="technicalDataAgreement"
                      checked={formData.mandatoryDocuments.technicalDataAgreement}
                      onChange={(e) => setFormData(prev => ({ ...prev, mandatoryDocuments: { ...prev.mandatoryDocuments, technicalDataAgreement: e.target.checked } }))}
                      className="rounded"
                    />
                    <Label htmlFor="technicalDataAgreement">기술자료제공동의서</Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      id="nda"
                      checked={formData.mandatoryDocuments.nda}
                      onChange={(e) => setFormData(prev => ({ ...prev, mandatoryDocuments: { ...prev.mandatoryDocuments, nda: e.target.checked } }))}
                      className="rounded"
                    />
                    <Label htmlFor="nda">비밀유지계약서(NDA)</Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      id="basicCompliance"
                      checked={formData.mandatoryDocuments.basicCompliance}
                      onChange={(e) => setFormData(prev => ({ ...prev, mandatoryDocuments: { ...prev.mandatoryDocuments, basicCompliance: e.target.checked } }))}
                      className="rounded"
                    />
                    <Label htmlFor="basicCompliance">기본준수서약서</Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      id="safetyHealthAgreement"
                      checked={formData.mandatoryDocuments.safetyHealthAgreement}
                      onChange={(e) => setFormData(prev => ({ ...prev, mandatoryDocuments: { ...prev.mandatoryDocuments, safetyHealthAgreement: e.target.checked } }))}
                      className="rounded"
                    />
                    <Label htmlFor="safetyHealthAgreement">안전보건관리 약정서</Label>
                  </div>
                </div>
              </div> */}

              {/* 계약해지조건 */}
              <div className="space-y-4">
                <Label className="text-base font-medium">계약해지조건</Label>
                <div className="space-y-3">
                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      id="standardTermination"
                      checked={formData.contractTerminationConditions.standardTermination}
                      onChange={(e) => setFormData(prev => ({ ...prev, contractTerminationConditions: { ...prev.contractTerminationConditions, standardTermination: e.target.checked } }))}
                      className="rounded"
                    />
                    <Label htmlFor="standardTermination">표준 계약해지조건</Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      id="projectNotAwarded"
                      checked={formData.contractTerminationConditions.projectNotAwarded}
                      onChange={(e) => setFormData(prev => ({ ...prev, contractTerminationConditions: { ...prev.contractTerminationConditions, projectNotAwarded: e.target.checked } }))}
                      className="rounded"
                    />
                    <Label htmlFor="projectNotAwarded">프로젝트 미수주 시</Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      id="terminationOther"
                      checked={formData.contractTerminationConditions.other}
                      onChange={(e) => setFormData(prev => ({ ...prev, contractTerminationConditions: { ...prev.contractTerminationConditions, other: e.target.checked } }))}
                      className="rounded"
                    />
                    <Label htmlFor="terminationOther">기타</Label>
                  </div>
                </div>
              </div>

              <div className="space-y-2 col-span-2">
                <Label htmlFor="notes">비고</Label>
                <Textarea
                  value={formData.notes}
                  onChange={(e) => setFormData(prev => ({ ...prev, notes: e.target.value }))}
                  placeholder="비고사항을 입력하세요"
                  rows={4}
                />
              </div>
            </div>
          </CardContent>
        </Card>
      </TabsContent>


      {/* 계약첨부문서 탭 */}
      <TabsContent value="documents" className="space-y-6">
        <ContractDocuments
          contractId={contractId}
          userId={userId?.toString() || "1"}
        />
      </TabsContent>
      </Tabs>
        
        {/* 저장 버튼 */}
        <div className="flex justify-end mt-6 pt-4 border-t border-gray-200">
          <Button 
            onClick={handleSaveContractInfo}
            disabled={isLoading}
            className="flex items-center gap-2"
          >
            {isLoading ? (
              <LoaderIcon className="w-4 h-4 animate-spin" />
            ) : (
              <Save className="w-4 h-4" />
            )}
            계약 정보 저장
          </Button>
        </div>
      </CardContent>
    </Card>
  )
}
