"use client"

import * as React from "react"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Checkbox } from "@/components/ui/checkbox"
import { Textarea } from "@/components/ui/textarea"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { toast } from "sonner"
import type { AvlVendorInfoInput, AvlDetailItem } from "../types"
import { EngineeringDisciplineSelector, type DisciplineCode } from "@/components/common/discipline"
import { MaterialGroupSelectorDialogSingle } from "@/components/common/material/material-group-selector-dialog-single"
import type { MaterialSearchItem } from "@/lib/material/material-group-service"
import { VendorSelectorDialogSingle } from "@/components/common/vendor"
import type { VendorSearchItem } from "@/components/common/vendor"
import { PlaceOfShippingSelector } from "@/components/common/selectors/place-of-shipping"
import { VendorTierSelector } from "@/components/common/selectors/vendor-tier"
import { DatePicker } from "@/components/ui/date-picker"

interface AvlVendorAddAndModifyDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  onAddItem: (item: Omit<AvlVendorInfoInput, 'avlListId'>) => Promise<void>
  editingItem?: AvlDetailItem // 수정할 항목 (없으면 추가 모드)
  onUpdateItem?: (id: number, item: Omit<AvlVendorInfoInput, 'avlListId'>) => Promise<void>

  // 모드 설정
  isTemplate?: boolean // false: 프로젝트 AVL, true: 표준 AVL

  // 표준 AVL용 초기값들 (선택적)
  initialConstructionSector?: string
  initialShipType?: string
  initialAvlKind?: string
  initialHtDivision?: string

  // 프로젝트 AVL용 초기값들 (선택적)
  initialProjectCode?: string
}

export function AvlVendorAddAndModifyDialog({
  open,
  onOpenChange,
  onAddItem,
  editingItem,
  onUpdateItem,
  isTemplate = false, // 기본값: 프로젝트 AVL
  initialConstructionSector,
  initialShipType,
  initialAvlKind,
  initialHtDivision,
  initialProjectCode
}: AvlVendorAddAndModifyDialogProps) {
  // 설계공종 선택 상태
  const [selectedDiscipline, setSelectedDiscipline] = React.useState<DisciplineCode | undefined>(undefined)
  // 자재그룹 선택 상태
  const [selectedMaterialGroup, setSelectedMaterialGroup] = React.useState<MaterialSearchItem | null>(null)
  // 벤더 선택 상태
  const [selectedVendor, setSelectedVendor] = React.useState<VendorSearchItem | null>(null)
  // 날짜 상태 (Date 객체로 관리)
  const [quoteReceivedDate, setQuoteReceivedDate] = React.useState<Date | undefined>(undefined)
  const [recentQuoteDate, setRecentQuoteDate] = React.useState<Date | undefined>(undefined)
  const [recentOrderDate, setRecentOrderDate] = React.useState<Date | undefined>(undefined)
  const [formData, setFormData] = React.useState<Omit<AvlVendorInfoInput, 'avlListId'>>({
    // 공통 기본 설정
    isTemplate: isTemplate,

    // 프로젝트 AVL용 필드들
    projectCode: initialProjectCode || "",

    // 표준 AVL용 필드들
    constructionSector: initialConstructionSector || "",
    shipType: initialShipType || "",
    avlKind: initialAvlKind || "",
    htDivision: initialHtDivision || "",

    // 설계 정보
    equipBulkDivision: "EQUIP",
    disciplineCode: "",
    disciplineName: "",

    // 자재 정보
    materialNameCustomerSide: "",

    // 패키지 정보
    packageCode: "",
    packageName: "",

    // 자재그룹 정보
    materialGroupCode: "",
    materialGroupName: "",

    // 협력업체 정보
    vendorName: "",
    vendorCode: "",

    // AVL 정보
    avlVendorName: "",
    tier: "",

    // 제안방향
    ownerSuggestion: false,
    shiSuggestion: false,

    // 위치 정보
    headquarterLocation: "",
    manufacturingLocation: "",

    // FA 정보
    faTarget: false,
    faStatus: "",

    // Agent 정보
    isAgent: false,

    // 계약 서명주체
    contractSignerName: "",
    contractSignerCode: "",

    // SHI Qualification
    shiAvl: false,
    shiBlacklist: false,
    shiBcc: false,

    // 기술영업 견적결과
    salesQuoteNumber: "",
    quoteCode: "",
    salesVendorInfo: "",
    salesCountry: "",
    totalAmount: "",
    quoteReceivedDate: "",

    // 업체 실적 현황
    recentQuoteDate: "",
    recentQuoteNumber: "",
    recentOrderDate: "",
    recentOrderNumber: "",

    // 기타
    remarks: ""
  })

  // 수정 모드일 때 설계공종 선택 상태 및 폼 데이터 초기화
  React.useEffect(() => {
    if (editingItem) {
      // 설계공종 선택 상태 초기화
      if (editingItem.disciplineCode && editingItem.disciplineName) {
        setSelectedDiscipline({
          CD: editingItem.disciplineCode,
          USR_DF_CHAR_18: editingItem.disciplineName
        })
      } else {
        setSelectedDiscipline(undefined)
      }

      // 자재그룹 선택 상태 초기화
      if (editingItem.materialGroupCode && editingItem.materialGroupName) {
        setSelectedMaterialGroup({
          materialGroupCode: editingItem.materialGroupCode,
          materialGroupDescription: editingItem.materialGroupName,
          displayText: `${editingItem.materialGroupCode} - ${editingItem.materialGroupName}`
        })
      } else {
        setSelectedMaterialGroup(null)
      }

      // 벤더 선택 상태 초기화 (기존 데이터가 있으면 가상의 벤더 객체 생성)
      if (editingItem.vendorCode || editingItem.vendorName) {
        setSelectedVendor({
          id: -1, // 임시 ID (실제 벤더 ID는 알 수 없음)
          vendorName: editingItem.vendorName || "",
          vendorCode: editingItem.vendorCode || null,
          status: "UNKNOWN", // 상태 정보 없음
          displayText: editingItem.vendorCode 
            ? `${editingItem.vendorName} (${editingItem.vendorCode})`
            : editingItem.vendorName || ""
        })
      } else {
        setSelectedVendor(null)
      }

      // 날짜 상태 초기화
      setQuoteReceivedDate(editingItem.quoteReceivedDate ? new Date(editingItem.quoteReceivedDate) : undefined)
      setRecentQuoteDate(editingItem.recentQuoteDate ? new Date(editingItem.recentQuoteDate) : undefined)
      setRecentOrderDate(editingItem.recentOrderDate ? new Date(editingItem.recentOrderDate) : undefined)

      setFormData({
        // 공통 기본 설정
        isTemplate: editingItem.isTemplate ?? isTemplate,

        // 프로젝트 AVL용 필드들
        projectCode: editingItem.projectCode || initialProjectCode || "",

        // 표준 AVL용 필드들
        constructionSector: editingItem.constructionSector || initialConstructionSector || "",
        shipType: editingItem.shipType || initialShipType || "",
        avlKind: editingItem.avlKind || initialAvlKind || "",
        htDivision: editingItem.htDivision || initialHtDivision || "",

        // 설계 정보
        equipBulkDivision: editingItem.equipBulkDivision === "EQUIP" ? "EQUIP" : "BULK",
        disciplineCode: editingItem.disciplineCode || "",
        disciplineName: editingItem.disciplineName || "",

        // 자재 정보
        materialNameCustomerSide: editingItem.materialNameCustomerSide || "",

        // 패키지 정보
        packageCode: editingItem.packageCode || "",
        packageName: editingItem.packageName || "",

        // 자재그룹 정보
        materialGroupCode: editingItem.materialGroupCode || "",
        materialGroupName: editingItem.materialGroupName || "",

        // 협력업체 정보
        vendorName: editingItem.vendorName || "",
        vendorCode: editingItem.vendorCode || "",

        // AVL 정보
        avlVendorName: editingItem.avlVendorName || "",
        tier: editingItem.tier || "",

        // 제안방향
        ownerSuggestion: editingItem.ownerSuggestion || false,
        shiSuggestion: editingItem.shiSuggestion || false,

        // 위치 정보
        headquarterLocation: editingItem.headquarterLocation || "",
        manufacturingLocation: editingItem.manufacturingLocation || "",

        // FA 정보
        faTarget: editingItem.faTarget || false,
        faStatus: editingItem.faStatus || "",

        // Agent 정보
        isAgent: editingItem.isAgent || false,

        // 계약 서명주체
        contractSignerName: editingItem.contractSignerName || "",
        contractSignerCode: editingItem.contractSignerCode || "",

        // SHI Qualification
        shiAvl: editingItem.shiAvl || false,
        shiBlacklist: editingItem.shiBlacklist || false,
        shiBcc: editingItem.shiBcc || false,

        // 기술영업 견적결과
        salesQuoteNumber: editingItem.salesQuoteNumber || "",
        quoteCode: editingItem.quoteCode || "",
        salesVendorInfo: editingItem.salesVendorInfo || "",
        salesCountry: editingItem.salesCountry || "",
        totalAmount: editingItem.totalAmount || "",
        quoteReceivedDate: editingItem.quoteReceivedDate || "",

        // 업체 실적 현황
        recentQuoteDate: editingItem.recentQuoteDate || "",
        recentQuoteNumber: editingItem.recentQuoteNumber || "",
        recentOrderDate: editingItem.recentOrderDate || "",
        recentOrderNumber: editingItem.recentOrderNumber || "",

        // 기타
        remarks: editingItem.remarks || ""
      })
    }
  }, [editingItem, isTemplate, initialProjectCode, initialConstructionSector, initialShipType, initialAvlKind, initialHtDivision])

  // 다이얼로그가 열릴 때 초기값 재설정 (수정 모드가 아닐 때만)
  React.useEffect(() => {
    if (open && !editingItem) {
      // 설계공종 선택 상태 초기화
      setSelectedDiscipline(undefined)
      // 자재그룹 선택 상태 초기화
      setSelectedMaterialGroup(null)
      // 벤더 선택 상태 초기화
      setSelectedVendor(null)
      // 날짜 상태 초기화
      setQuoteReceivedDate(undefined)
      setRecentQuoteDate(undefined)
      setRecentOrderDate(undefined)
      
      setFormData(prev => ({
        ...prev,
        isTemplate: isTemplate,
        projectCode: initialProjectCode || "",
        constructionSector: initialConstructionSector || "",
        shipType: initialShipType || "",
        avlKind: initialAvlKind || "",
        htDivision: initialHtDivision || "",
      }))
    }
  }, [open, editingItem, isTemplate, initialProjectCode, initialConstructionSector, initialShipType, initialAvlKind, initialHtDivision])

  // 설계공종 선택 핸들러
  const handleDisciplineSelect = React.useCallback((discipline: DisciplineCode) => {
    setSelectedDiscipline(discipline)
    setFormData(prev => ({
      ...prev,
      disciplineCode: discipline.CD,
      disciplineName: discipline.USR_DF_CHAR_18
    }))
  }, [])

  // 자재그룹 선택 핸들러
  const handleMaterialGroupSelect = React.useCallback((materialGroup: MaterialSearchItem | null) => {
    setSelectedMaterialGroup(materialGroup)
    setFormData(prev => ({
      ...prev,
      materialGroupCode: materialGroup?.materialGroupCode || "",
      materialGroupName: materialGroup?.materialGroupDescription || ""
    }))
  }, [])

  // 벤더 선택 핸들러 (선택기에서 벤더를 선택했을 때 Input 필드에 자동 입력)
  const handleVendorSelect = React.useCallback((vendor: VendorSearchItem | null) => {
    setSelectedVendor(vendor)
    if (vendor) {
      setFormData(prev => ({
        ...prev,
        vendorCode: vendor.vendorCode || "",
        vendorName: vendor.vendorName || "",
        // AVL 등재업체명도 기본적으로 벤더명으로 설정 (사용자가 수정 가능)
        avlVendorName: vendor.vendorName || ""
      }))
    }
  }, [])

  const handleSubmit = async () => {
    // 공통 필수 필드 검증
    if (!formData.disciplineName || !formData.materialNameCustomerSide) {
      toast.error("설계공종과 고객사 AVL 자재명은 필수 입력 항목입니다.")
      return
    }

    // 모드별 필수 필드 검증
    if (isTemplate) {
      // 표준 AVL 모드
      if (!formData.constructionSector || !formData.shipType || !formData.avlKind || !formData.htDivision) {
        toast.error("공사부문, 선종, AVL종류, H/T 구분은 필수 입력 항목입니다.")
        return
      }
    } else {
      // 프로젝트 AVL 모드
      if (!formData.projectCode) {
        toast.error("프로젝트 코드는 필수 입력 항목입니다.")
        return
      }
    }

    try {
      // 날짜 필드들을 문자열로 변환
      const formatDate = (date: Date | undefined): string => {
        if (!date) return ""
        return date.toISOString().split('T')[0] // YYYY-MM-DD 형식
      }

      const submissionData = {
        ...formData,
        quoteReceivedDate: formatDate(quoteReceivedDate),
        recentQuoteDate: formatDate(recentQuoteDate),
        recentOrderDate: formatDate(recentOrderDate),
      }

      if (editingItem && onUpdateItem) {
        // 수정 모드
        await onUpdateItem(editingItem.id, submissionData)
      } else {
        // 추가 모드
        await onAddItem(submissionData)
      }

      // 폼 및 선택 상태 초기화
      setSelectedDiscipline(undefined)
      setSelectedMaterialGroup(null)
      setSelectedVendor(null)
      setQuoteReceivedDate(undefined)
      setRecentQuoteDate(undefined)
      setRecentOrderDate(undefined)
      setFormData({
        isTemplate: isTemplate,
        projectCode: initialProjectCode || "",
        constructionSector: initialConstructionSector || "",
        shipType: initialShipType || "",
        avlKind: initialAvlKind || "",
        htDivision: initialHtDivision || "",
        equipBulkDivision: "EQUIP",
        disciplineCode: "",
        disciplineName: "",
        materialNameCustomerSide: "",
        packageCode: "",
        packageName: "",
        materialGroupCode: "",
        materialGroupName: "",
        vendorName: "",
        vendorCode: "",
        avlVendorName: "",
        tier: "",
        ownerSuggestion: false,
        shiSuggestion: false,
        headquarterLocation: "",
        manufacturingLocation: "",
        faTarget: false,
        faStatus: "",
        isAgent: false,
        contractSignerName: "",
        contractSignerCode: "",
        shiAvl: false,
        shiBlacklist: false,
        shiBcc: false,
        salesQuoteNumber: "",
        quoteCode: "",
        salesVendorInfo: "",
        salesCountry: "",
        totalAmount: "",
        quoteReceivedDate: "",
        recentQuoteDate: "",
        recentQuoteNumber: "",
        recentOrderDate: "",
        recentOrderNumber: "",
        remarks: ""
      } as Omit<AvlVendorInfoInput, 'avlListId'>)

      onOpenChange(false)
    } catch {
      // 에러 처리는 호출하는 쪽에서 담당
    }
  }

  const handleCancel = () => {
    setSelectedDiscipline(undefined)
    setSelectedMaterialGroup(null)
    setSelectedVendor(null)
    setQuoteReceivedDate(undefined)
    setRecentQuoteDate(undefined)
    setRecentOrderDate(undefined)
    setFormData({
      isTemplate: isTemplate,
      projectCode: initialProjectCode || "",
      constructionSector: initialConstructionSector || "",
      shipType: initialShipType || "",
      avlKind: initialAvlKind || "",
      htDivision: initialHtDivision || "",
      equipBulkDivision: "EQUIP",
      disciplineCode: "",
      disciplineName: "",
      materialNameCustomerSide: "",
      packageCode: "",
      packageName: "",
      materialGroupCode: "",
      materialGroupName: "",
      vendorName: "",
      vendorCode: "",
      avlVendorName: "",
      tier: "",
      ownerSuggestion: false,
      shiSuggestion: false,
      headquarterLocation: "",
      manufacturingLocation: "",
      faTarget: false,
      faStatus: "",
      isAgent: false,
      contractSignerName: "",
      contractSignerCode: "",
      shiAvl: false,
      shiBlacklist: false,
      shiBcc: false,
      salesQuoteNumber: "",
      quoteCode: "",
      salesVendorInfo: "",
      salesCountry: "",
      totalAmount: "",
      quoteReceivedDate: "",
      recentQuoteDate: "",
      recentQuoteNumber: "",
      recentOrderDate: "",
      recentOrderNumber: "",
      remarks: ""
    } as Omit<AvlVendorInfoInput, 'avlListId'>)
    onOpenChange(false)
  }


  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[800px] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>
            {isTemplate ? "표준 AVL" : "프로젝트 AVL"} {editingItem ? "항목 수정" : "항목 추가"}
          </DialogTitle>
          <DialogDescription>
            {editingItem
              ? `${isTemplate ? "표준 AVL" : "프로젝트 AVL"} 항목을 수정합니다. 필수 항목을 입력해주세요.`
              : `새로운 ${isTemplate ? "표준 AVL" : "프로젝트 AVL"} 항목을 추가합니다. 필수 항목을 입력해주세요.`
            } * 표시된 항목은 필수 입력사항입니다.
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-6 py-4">
          {/* 모드별 필수 정보 */}
          {!isTemplate ? (
            // 프로젝트 AVL 모드
            <div className="space-y-4">
              <h4 className="text-sm font-semibold text-muted-foreground border-b pb-2">프로젝트 정보 *</h4>
              <div className="grid grid-cols-1 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="projectCode">프로젝트 코드 *</Label>
                  <Input
                    id="projectCode"
                    value={formData.projectCode}
                    onChange={(e) => setFormData(prev => ({ ...prev, projectCode: e.target.value }))}
                    placeholder="프로젝트 코드를 입력하세요"
                    readOnly
                    className="bg-muted"
                  />
                </div>
              </div>
            </div>
          ) : (
            // 표준 AVL 모드
            <div className="space-y-4">
              <h4 className="text-sm font-semibold text-muted-foreground border-b pb-2">표준 AVL 기본 정보 *</h4>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="constructionSector">공사부문 *</Label>
                  <Input
                    value={formData.constructionSector}
                    readOnly
                    className="bg-muted"
                    placeholder="공사부문이 설정되지 않았습니다"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="shipType">선종 *</Label>
                  <Input
                    value={formData.shipType}
                    readOnly
                    className="bg-muted"
                    placeholder="선종이 설정되지 않았습니다"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="avlKind">AVL종류 *</Label>
                  <Input
                    value={formData.avlKind}
                    readOnly
                    className="bg-muted"
                    placeholder="AVL종류가 설정되지 않았습니다"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="htDivision">H/T 구분 *</Label>
                  <Input
                    value={formData.htDivision}
                    readOnly
                    className="bg-muted"
                    placeholder="H/T 구분이 설정되지 않았습니다"
                  />
                </div>
              </div>
            </div>
          )}

          {/* 공통 정보들 (나머지 폼 필드들은 동일하게 유지) */}
          {/* 기본 정보 */}
          <div className="space-y-4">
            <h4 className="text-sm font-semibold text-muted-foreground border-b pb-2">기본 정보</h4>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="equipBulkDivision">EQUIP/BULK 구분</Label>
                <Select
                  value={formData.equipBulkDivision}
                  onValueChange={(value: "EQUIP" | "BULK") =>
                    setFormData(prev => ({ ...prev, equipBulkDivision: value }))
                  }
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="EQUIP">EQUIP</SelectItem>
                    <SelectItem value="BULK">BULK</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2 col-span-2">
                <Label htmlFor="discipline">설계공종 *</Label>
                <EngineeringDisciplineSelector
                  selectedDiscipline={selectedDiscipline}
                  onDisciplineSelect={handleDisciplineSelect}
                  placeholder="설계공종을 선택하세요"
                  className="h-9"
                />
                <div className="text-xs text-muted-foreground">
                  {selectedDiscipline && (
                    <span>선택됨: [{selectedDiscipline.CD}] {selectedDiscipline.USR_DF_CHAR_18}</span>
                  )}
                </div>
              </div>
              <div className="space-y-2 col-span-2">
                <Label htmlFor="materialNameCustomerSide">고객사 AVL 자재명 *</Label>
                <Input
                  id="materialNameCustomerSide"
                  value={formData.materialNameCustomerSide}
                  onChange={(e) => setFormData(prev => ({ ...prev, materialNameCustomerSide: e.target.value }))}
                  placeholder="고객사 AVL 자재명을 입력하세요"
                />
              </div>
            </div>
          </div>

          {/* 패키지 정보 */}
          <div className="space-y-4">
            <h4 className="text-sm font-semibold text-muted-foreground border-b pb-2">패키지 정보</h4>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="packageCode">패키지 코드</Label>
                <Input
                  id="packageCode"
                  value={formData.packageCode}
                  onChange={(e) => setFormData(prev => ({ ...prev, packageCode: e.target.value }))}
                  placeholder="패키지 코드를 입력하세요"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="packageName">패키지 명</Label>
                <Input
                  id="packageName"
                  value={formData.packageName}
                  onChange={(e) => setFormData(prev => ({ ...prev, packageName: e.target.value }))}
                  placeholder="패키지 명을 입력하세요"
                />
              </div>
            </div>
          </div>

          {/* 자재그룹 정보 */}
          <div className="space-y-4">
            <h4 className="text-sm font-semibold text-muted-foreground border-b pb-2">자재그룹 정보</h4>
            <div className="space-y-4">
              <div className="space-y-2">
                {/* <Label htmlFor="materialGroup">자재그룹 선택</Label> */}
                <MaterialGroupSelectorDialogSingle
                  triggerLabel="자재그룹 선택"
                  selectedMaterial={selectedMaterialGroup}
                  onMaterialSelect={handleMaterialGroupSelect}
                  placeholder="자재그룹을 검색하세요..."
                  title="자재그룹 선택"
                  description="AVL에 등록할 자재그룹을 선택해주세요."
                  triggerVariant="outline"
                />
                <div className="text-xs text-muted-foreground">
                  {selectedMaterialGroup && (
                    <>
                      <span>자재그룹코드: {selectedMaterialGroup.materialGroupCode}</span>
                      <br />
                      <span>자재그룹명: {selectedMaterialGroup.materialGroupDescription}</span>
                    </>
                  )}
                </div>
              </div>
            </div>
          </div>

          {/* 협력업체 정보 */}
          <div className="space-y-4">
            <div className="flex items-center justify-between border-b pb-2">
              <h4 className="text-sm font-semibold text-muted-foreground">협력업체 정보</h4>
              <VendorSelectorDialogSingle
                triggerLabel="협력업체 로드"
                selectedVendor={selectedVendor}
                onVendorSelect={handleVendorSelect}
                title="협력업체 선택"
                description="등록된 협력업체 목록에서 선택하여 정보를 자동으로 입력할 수 있습니다."
                triggerVariant="outline"
                statusFilter="ACTIVE"
              />
            </div>
            {selectedVendor && (
              <div className="text-xs text-muted-foreground bg-blue-50 p-2 rounded">
                <span>선택된 협력업체: [{selectedVendor.vendorCode || '-'}] {selectedVendor.vendorName}</span>
                <span className="ml-2 text-blue-600">({selectedVendor.status})</span>
              </div>
            )}
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="vendorCode">협력업체 코드</Label>
                <Input
                  id="vendorCode"
                  value={formData.vendorCode}
                  onChange={(e) => setFormData(prev => ({ ...prev, vendorCode: e.target.value }))}
                  placeholder="협력업체 코드를 입력하세요"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="vendorName">협력업체 명</Label>
                <Input
                  id="vendorName"
                  value={formData.vendorName}
                  onChange={(e) => setFormData(prev => ({ ...prev, vendorName: e.target.value }))}
                  placeholder="협력업체 명을 입력하세요"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="avlVendorName">AVL 등재업체명</Label>
                <Input
                  id="avlVendorName"
                  value={formData.avlVendorName}
                  onChange={(e) => setFormData(prev => ({ ...prev, avlVendorName: e.target.value }))}
                  placeholder="AVL 등재업체명을 입력하세요"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="tier">등급 (Tier)</Label>
                <VendorTierSelector
                  value={formData.tier}
                  onValueChange={(value) => setFormData(prev => ({ ...prev, tier: value }))}
                  placeholder="등급을 선택하세요"
                  className="h-9"
                />
              </div>
            </div>
          </div>

          {/* 제안방향 */}
          <div className="space-y-4">
            <h4 className="text-sm font-semibold text-muted-foreground border-b pb-2">제안방향</h4>
            <div className="flex gap-6">
              <div className="flex items-center space-x-2">
                <Checkbox
                  id="ownerSuggestion"
                  checked={formData.ownerSuggestion}
                  onCheckedChange={(checked) =>
                    setFormData(prev => ({ ...prev, ownerSuggestion: !!checked }))
                  }
                />
                <Label htmlFor="ownerSuggestion">선주제안</Label>
              </div>
              <div className="flex items-center space-x-2">
                <Checkbox
                  id="shiSuggestion"
                  checked={formData.shiSuggestion}
                  onCheckedChange={(checked) =>
                    setFormData(prev => ({ ...prev, shiSuggestion: !!checked }))
                  }
                />
                <Label htmlFor="shiSuggestion">SHI 제안</Label>
              </div>
            </div>
          </div>

          {/* 위치 정보 */}
          <div className="space-y-4">
            <h4 className="text-sm font-semibold text-muted-foreground border-b pb-2">위치 정보</h4>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="headquarterLocation">본사 위치 (국가)</Label>
                <Input
                  id="headquarterLocation"
                  value={formData.headquarterLocation}
                  onChange={(e) => setFormData(prev => ({ ...prev, headquarterLocation: e.target.value }))}
                  placeholder="본사 위치를 입력하세요"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="manufacturingLocation">제작/선적지 (국가)</Label>
                <PlaceOfShippingSelector
                  value={formData.manufacturingLocation}
                  onValueChange={(value) => setFormData(prev => ({ ...prev, manufacturingLocation: value }))}
                  placeholder="제작/선적지를 선택하세요"
                  className="h-9"
                />
              </div>
            </div>
          </div>

          {/* FA 정보 */}
          <div className="space-y-4">
            <h4 className="text-sm font-semibold text-muted-foreground border-b pb-2">FA 정보</h4>
            <div className="grid grid-cols-2 gap-4">
              <div className="flex items-center space-x-2">
                <Checkbox
                  id="faTarget"
                  checked={formData.faTarget}
                  onCheckedChange={(checked) =>
                    setFormData(prev => ({ ...prev, faTarget: !!checked }))
                  }
                />
                <Label htmlFor="faTarget">FA 대상</Label>
              </div>
              <div className="space-y-2">
                <Label htmlFor="faStatus">FA 현황</Label>
                <Input
                  id="faStatus"
                  value={formData.faStatus}
                  onChange={(e) => setFormData(prev => ({ ...prev, faStatus: e.target.value }))}
                  placeholder="FA 현황을 입력하세요"
                />
              </div>
            </div>
          </div>

          {/* Agent 정보 */}
          <div className="space-y-4">
            <h4 className="text-sm font-semibold text-muted-foreground border-b pb-2">Agent 정보</h4>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="isAgent"
                checked={formData.isAgent}
                onCheckedChange={(checked) =>
                  setFormData(prev => ({ ...prev, isAgent: !!checked }))
                }
              />
              <Label htmlFor="isAgent">Agent 여부</Label>
            </div>
          </div>

          {/* 계약 서명주체 */}
          <div className="space-y-4">
            <h4 className="text-sm font-semibold text-muted-foreground border-b pb-2">계약 서명주체</h4>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="contractSignerCode">계약서명주체 코드</Label>
                <Input
                  id="contractSignerCode"
                  value={formData.contractSignerCode}
                  onChange={(e) => setFormData(prev => ({ ...prev, contractSignerCode: e.target.value }))}
                  placeholder="계약서명주체 코드를 입력하세요"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="contractSignerName">계약서명주체 명</Label>
                <Input
                  id="contractSignerName"
                  value={formData.contractSignerName}
                  onChange={(e) => setFormData(prev => ({ ...prev, contractSignerName: e.target.value }))}
                  placeholder="계약서명주체 명을 입력하세요"
                />
              </div>
            </div>
          </div>

          {/* SHI Qualification */}
          <div className="space-y-4">
            <h4 className="text-sm font-semibold text-muted-foreground border-b pb-2">SHI Qualification</h4>
            <div className="flex gap-6">
              <div className="flex items-center space-x-2">
                <Checkbox
                  id="shiAvl"
                  checked={formData.shiAvl}
                  onCheckedChange={(checked) =>
                    setFormData(prev => ({ ...prev, shiAvl: !!checked }))
                  }
                />
                <Label htmlFor="shiAvl">AVL</Label>
              </div>
              <div className="flex items-center space-x-2">
                <Checkbox
                  id="shiBlacklist"
                  checked={formData.shiBlacklist}
                  onCheckedChange={(checked) =>
                    setFormData(prev => ({ ...prev, shiBlacklist: !!checked }))
                  }
                />
                <Label htmlFor="shiBlacklist">Blacklist</Label>
              </div>
              <div className="flex items-center space-x-2">
                <Checkbox
                  id="shiBcc"
                  checked={formData.shiBcc}
                  onCheckedChange={(checked) =>
                    setFormData(prev => ({ ...prev, shiBcc: !!checked }))
                  }
                />
                <Label htmlFor="shiBcc">BCC</Label>
              </div>
            </div>
          </div>

          {/* 기술영업 견적결과 */}
          <div className="space-y-4">
            <h4 className="text-sm font-semibold text-muted-foreground border-b pb-2">기술영업 견적결과</h4>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="salesQuoteNumber">기술영업 견적번호</Label>
                <Input
                  id="salesQuoteNumber"
                  value={formData.salesQuoteNumber}
                  onChange={(e) => setFormData(prev => ({ ...prev, salesQuoteNumber: e.target.value }))}
                  placeholder="기술영업 견적번호를 입력하세요"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="quoteCode">견적서 Code</Label>
                <Input
                  id="quoteCode"
                  value={formData.quoteCode}
                  onChange={(e) => setFormData(prev => ({ ...prev, quoteCode: e.target.value }))}
                  placeholder="견적서 Code를 입력하세요"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="salesVendorInfo">견적 협력업체 명</Label>
                <Input
                  id="salesVendorInfo"
                  value={formData.salesVendorInfo}
                  onChange={(e) => setFormData(prev => ({ ...prev, salesVendorInfo: e.target.value }))}
                  placeholder="견적 협력업체 명을 입력하세요"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="salesCountry">국가</Label>
                <Input
                  id="salesCountry"
                  value={formData.salesCountry}
                  onChange={(e) => setFormData(prev => ({ ...prev, salesCountry: e.target.value }))}
                  placeholder="국가를 입력하세요"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="totalAmount">총 금액</Label>
                <Input
                  id="totalAmount"
                  type="number"
                  value={formData.totalAmount}
                  onChange={(e) => setFormData(prev => ({ ...prev, totalAmount: e.target.value }))}
                  placeholder="총 금액을 입력하세요"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="quoteReceivedDate">견적접수일</Label>
                <DatePicker
                  date={quoteReceivedDate}
                  onSelect={setQuoteReceivedDate}
                  placeholder="견적접수일 선택"
                  className="h-9"
                />
              </div>
            </div>
          </div>

          {/* 업체 실적 현황 */}
          <div className="space-y-4">
            <h4 className="text-sm font-semibold text-muted-foreground border-b pb-2">업체 실적 현황</h4>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="recentQuoteNumber">최근견적번호</Label>
                <Input
                  id="recentQuoteNumber"
                  value={formData.recentQuoteNumber}
                  onChange={(e) => setFormData(prev => ({ ...prev, recentQuoteNumber: e.target.value }))}
                  placeholder="최근견적번호를 입력하세요"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="recentQuoteDate">최근견적일</Label>
                <DatePicker
                  date={recentQuoteDate}
                  onSelect={setRecentQuoteDate}
                  placeholder="최근견적일 선택"
                  className="h-9"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="recentOrderNumber">최근발주번호</Label>
                <Input
                  id="recentOrderNumber"
                  value={formData.recentOrderNumber}
                  onChange={(e) => setFormData(prev => ({ ...prev, recentOrderNumber: e.target.value }))}
                  placeholder="최근발주번호를 입력하세요"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="recentOrderDate">최근발주일</Label>
                <DatePicker
                  date={recentOrderDate}
                  onSelect={setRecentOrderDate}
                  placeholder="최근발주일 선택"
                  className="h-9"
                />
              </div>
            </div>
          </div>

          {/* 기타 */}
          <div className="space-y-4">
            <h4 className="text-sm font-semibold text-muted-foreground border-b pb-2">기타</h4>
            <div className="space-y-2">
              <Label htmlFor="remarks">비고</Label>
              <Textarea
                id="remarks"
                value={formData.remarks}
                onChange={(e) => setFormData(prev => ({ ...prev, remarks: e.target.value }))}
                placeholder="비고를 입력하세요"
                rows={3}
              />
            </div>
          </div>
        </div>
        <DialogFooter>
          <Button type="button" variant="outline" onClick={handleCancel}>
            취소
          </Button>
          <Button type="button" onClick={handleSubmit}>
            {editingItem ? "수정" : "추가"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
