'use client'

import React, { useState, useEffect, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Progress } from '@/components/ui/progress';
import { Check, ChevronRight, User, Building, FileText, Plus, X, ChevronsUpDown, Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useRouter, useParams, useSearchParams } from 'next/navigation';
import { useTranslation } from '@/i18n/client';
import { toast } from '@/hooks/use-toast';
import {
  Popover,
  PopoverTrigger,
  PopoverContent,
} from '@/components/ui/popover';
import {
  Command,
  CommandList,
  CommandInput,
  CommandEmpty,
  CommandGroup,
  CommandItem,
} from '@/components/ui/command';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Dropzone,
  DropzoneZone,
  DropzoneInput,
  DropzoneUploadIcon,
  DropzoneTitle,
  DropzoneDescription,
} from '@/components/ui/dropzone';
import {
  FileList,
  FileListItem,
  FileListHeader,
  FileListIcon,
  FileListInfo,
  FileListName,
  FileListDescription,
  FileListAction,
} from '@/components/ui/file-list';
import { ScrollArea } from '@/components/ui/scroll-area';
import prettyBytes from 'pretty-bytes';
import { useToast } from "@/hooks/use-toast";

// libphonenumber-js 관련 imports
import {
  parsePhoneNumberFromString,
  isPossiblePhoneNumber,
  isValidPhoneNumber,
  validatePhoneNumberLength,
  getExampleNumber,
  AsYouType,
  getCountries,
  getCountryCallingCode
} from 'libphonenumber-js'
import examples from 'libphonenumber-js/examples.mobile.json'

// 기존 imports...
import i18nIsoCountries from "i18n-iso-countries";
import enLocale from "i18n-iso-countries/langs/en.json";
import koLocale from "i18n-iso-countries/langs/ko.json";
import { getVendorTypes } from '@/lib/vendors/service';
import ConsentStep from './conset-step';
import { checkEmailExists } from '@/lib/vendor-users/service';

i18nIsoCountries.registerLocale(enLocale);
i18nIsoCountries.registerLocale(koLocale);

const locale = "ko";
const countryMap = i18nIsoCountries.getNames(locale, { select: "official" });
const countryArray = Object.entries(countryMap).map(([code, label]) => ({
  code,
  label,
}));

const sortedCountryArray = [...countryArray].sort((a, b) => {
  if (a.code === "KR") return -1;
  if (b.code === "KR") return 1;
  return a.label.localeCompare(b.label);
});

const enhancedCountryArray = sortedCountryArray.map(country => ({
  ...country,
  label: locale === "ko" && country.code === "KR"
    ? "대한민국 (South Korea)"
    : country.label
}));

const contactTaskOptions = [
  { value: "PRESIDENT_DIRECTOR", label: "회사대표 President/Director" },
  { value: "SALES_MANAGEMENT", label: "영업관리 Sales Management" },
  { value: "ENGINEERING_DESIGN", label: "설계/기술 Engineering/Design" },
  { value: "PROCUREMENT", label: "구매 Procurement" },
  { value: "DELIVERY_CONTROL", label: "납기/출하/운송 Delivery Control" },
  { value: "PM_MANUFACTURING", label: "PM/생산관리 PM/Manufacturing" },
  { value: "QUALITY_MANAGEMENT", label: "품질관리 Quality Management" },
  { value: "SHIPPING_DOC_MANAGEMENT", label: "세금계산서/납품서관리 Shipping Doc. Management" },
  { value: "AS_MANAGEMENT", label: "A/S 관리 A/S Management" },
  { value: "FIELD_SERVICE_ENGINEER", label: "FSE(야드작업자) Field Service Engineer" }
];

const MAX_FILE_SIZE = 3e9;

// 스텝 정의
const STEPS = [
  { id: 1, title: '약관 동의', description: '서비스 이용 약관 동의', icon: FileText },
  { id: 2, title: '계정 생성', description: '개인 계정 정보 입력', icon: User },
  { id: 3, title: '업체 등록', description: '업체 정보 및 서류 제출', icon: Building }
];

// ========== 전화번호 처리 유틸리티 함수들 ==========

/**
 * 국가별 전화번호 예시를 가져오는 함수
 */
function getPhoneExample(countryCode) {
  if (!countryCode) return null;
  try {
    return getExampleNumber(countryCode, examples);
  } catch {
    return null;
  }
}

/**
 * 국가별 전화번호 플레이스홀더를 생성하는 함수
 */
function getPhonePlaceholder(countryCode) {
  if (!countryCode) return "국가를 먼저 선택해주세요";

  const example = getPhoneExample(countryCode);
  if (example) {
    // 국내 형식으로 표시 (더 친숙함)
    return example.formatNational();
  }

  // 예시가 없는 경우 국가 코드 기반 플레이스홀더
  try {
    const callingCode = getCountryCallingCode(countryCode);
    return `+${callingCode} ...`;
  } catch {
    return "전화번호를 입력하세요";
  }
}

/**
 * 국가별 전화번호 설명을 생성하는 함수
 */
function getPhoneDescription(countryCode) {
  if (!countryCode) return "국가를 먼저 선택하여 올바른 전화번호 형식을 확인하세요.";

  const example = getPhoneExample(countryCode);
  if (example) {
    return `예시: ${example.formatNational()} 또는 ${example.formatInternational()}`;
  }

  try {
    const callingCode = getCountryCallingCode(countryCode);
    return `국가 코드: +${callingCode}. 국내 형식 또는 국제 형식으로 입력 가능합니다.`;
  } catch {
    return "올바른 전화번호 형식으로 입력해주세요.";
  }
}

/**
 * 전화번호 검증 결과를 반환하는 함수
 */
function validatePhoneNumber(phoneNumber, countryCode) {
  if (!phoneNumber || !countryCode) {
    return { isValid: false, error: null, formatted: phoneNumber };
  }

  try {
    // 1. 기본 파싱 시도
    const parsed = parsePhoneNumberFromString(phoneNumber, countryCode);

    if (!parsed) {
      return {
        isValid: false,
        error: "올바른 전화번호 형식이 아닙니다.",
        formatted: phoneNumber
      };
    }

    // 2. 길이 검증
    const lengthValidation = validatePhoneNumberLength(phoneNumber, countryCode);
    if (lengthValidation !== undefined) {
      const lengthErrors = {
        'TOO_SHORT': '전화번호가 너무 짧습니다.',
        'TOO_LONG': '전화번호가 너무 깁니다.',
        'INVALID_LENGTH': '전화번호 길이가 올바르지 않습니다.'
      };
      return {
        isValid: false,
        error: lengthErrors[lengthValidation] || '전화번호 길이가 올바르지 않습니다.',
        formatted: phoneNumber
      };
    }

    // 3. 가능성 검증
    if (!isPossiblePhoneNumber(phoneNumber, countryCode)) {
      return {
        isValid: false,
        error: "이 국가에서 가능하지 않은 전화번호 형식입니다.",
        formatted: phoneNumber
      };
    }

    // 4. 유효성 검증
    if (!isValidPhoneNumber(phoneNumber, countryCode)) {
      return {
        isValid: false,
        error: "유효하지 않은 전화번호입니다.",
        formatted: phoneNumber
      };
    }

    // 모든 검증 통과
    return {
      isValid: true,
      error: null,
      formatted: parsed.formatNational(),
      international: parsed.formatInternational()
    };

  } catch (error) {
    return {
      isValid: false,
      error: "전화번호 형식을 확인해주세요.",
      formatted: phoneNumber
    };
  }
}

/**
 * 실시간 전화번호 포맷팅을 위한 커스텀 훅
 */
function usePhoneFormatter(countryCode) {
  const [formatter, setFormatter] = useState(null);

  useEffect(() => {
    if (countryCode) {
      setFormatter(new AsYouType(countryCode));
    } else {
      setFormatter(null);
    }
  }, [countryCode]);

  const formatPhone = useCallback((value) => {
    if (!formatter) return value;

    // AsYouType은 매번 새로운 인스턴스를 사용해야 함
    const newFormatter = new AsYouType(countryCode);
    return newFormatter.input(value);
  }, [countryCode, formatter]);

  return formatPhone;
}

// ========== 전화번호 입력 컴포넌트 ==========

function PhoneInput({
  value,
  onChange,
  countryCode,
  placeholder,
  disabled = false,
  onBlur = null,
  className = "",
  showValidation = true
}) {
  const [touched, setTouched] = useState(false);
  const [localValue, setLocalValue] = useState(value || '');
  const formatPhone = usePhoneFormatter(countryCode);

  // value prop이 변경될 때 localValue 동기화
  useEffect(() => {
    setLocalValue(value || '');
  }, [value]);

  const validation = validatePhoneNumber(localValue, countryCode);

  const handleInputChange = (e) => {
    const inputValue = e.target.value;

    // 실시간 포맷팅 적용
    const formattedValue = countryCode ? formatPhone(inputValue) : inputValue;

    setLocalValue(formattedValue);
    onChange(formattedValue);
  };

  const handleBlur = () => {
    setTouched(true);
    if (onBlur) onBlur();
  };

  const showError = showValidation && touched && localValue && !validation.isValid;
  const showSuccess = showValidation && touched && localValue && validation.isValid;

  return (
    <div className="space-y-2">
      <Input
        type="tel"
        value={localValue}
        onChange={handleInputChange}
        onBlur={handleBlur}
        placeholder={placeholder || getPhonePlaceholder(countryCode)}
        disabled={disabled}
        className={cn(
          className,
          showError && "border-red-500 focus:border-red-500",
          showSuccess && "border-green-500 focus:border-green-500"
        )}
      />

      {showValidation && (
        <div className="text-xs space-y-1">
          {/* 설명 텍스트 */}
          <p className="text-muted-foreground">
            {getPhoneDescription(countryCode)}
          </p>

          {/* 오류 메시지 */}
          {showError && (
            <p className="text-red-500 font-medium">
              {validation.error}
            </p>
          )}

          {/* 성공 메시지 */}
          {showSuccess && (
            <p className="text-green-600 font-medium">
              ✓ 올바른 전화번호입니다.
              {validation.international && ` (${validation.international})`}
            </p>
          )}
        </div>
      )}
    </div>
  );
}

// ========== 메인 컴포넌트 ==========

export default function JoinForm() {
  const params = useParams() || {};
  const lng = params.lng ? String(params.lng) : "ko";
  const { t } = useTranslation(lng, "translation");
  const router = useRouter();
  const searchParams = useSearchParams() || new URLSearchParams();
  const defaultTaxId = searchParams.get("taxID") ?? "";
  const { toast } = useToast();

  const [currentStep, setCurrentStep] = useState(1);
  const [completedSteps, setCompletedSteps] = useState(new Set());

  // 각 스텝별 데이터
  const [consentData, setConsentData] = useState({
    privacy: false,
    terms: false,
    marketing: false
  });

  const [accountData, setAccountData] = useState({
    name: '',
    email: '',
    phone: '',
    country: 'KR' // 기본값을 한국으로 설정
  });

  const [vendorData, setVendorData] = useState({
    vendorName: "",
    vendorTypeId: undefined,
    items: "",
    taxId: defaultTaxId,
    address: "",
    email: "",
    phone: "",
    country: "", // 기본값을 빈 문자열로 설정하여 계정 데이터에서 가져오도록 함
    website: "",
    representativeName: "",
    representativeBirth: "",
    representativeEmail: "",
    representativePhone: "",
    corporateRegistrationNumber: "",
    representativeWorkExpirence: false,
    contacts: [
      {
        contactName: "",
        contactPosition: "",
        contactDepartment: "",
        contactTask: "",
        contactEmail: "",
        contactPhone: "",
      },
    ],
  });

  // 업체 타입 및 파일 상태
  const [vendorTypes, setVendorTypes] = useState([]);
  const [isLoadingVendorTypes, setIsLoadingVendorTypes] = useState(true);
  const [businessRegistrationFiles, setBusinessRegistrationFiles] = useState([]);
  const [isoCertificationFiles, setIsoCertificationFiles] = useState([]);
  const [creditReportFiles, setCreditReportFiles] = useState([]);
  const [bankAccountFiles, setBankAccountFiles] = useState([]);

  const [policyVersions, setPolicyVersions] = useState({
    privacy_policy: '1.0',
    terms_of_service: '1.0'
  });

  const progress = ((currentStep - 1) / (STEPS.length - 1)) * 100;

  // 정책 버전 및 업체 타입 로드
  useEffect(() => {
    loadVendorTypes();
  }, []);

  const loadVendorTypes = async () => {
    setIsLoadingVendorTypes(true);
    try {
      const result = await getVendorTypes();
      if (result.data) {
        setVendorTypes(result.data);
      }
    } catch (error) {
      console.error("Failed to load vendor types:", error);
      toast({
        variant: "destructive",
        title: "Error",
        description: "Failed to load vendor types",
      });
    } finally {
      setIsLoadingVendorTypes(false);
    }
  };

  const handleStepComplete = (step) => {
    setCompletedSteps(prev => new Set([...prev, step]));
    if (step < STEPS.length) {
      setCurrentStep(step + 1);
    }
  };

  const handleStepClick = (stepId) => {
    if (stepId <= Math.max(...completedSteps) + 1) {
      setCurrentStep(stepId);
    }
  };

  return (
    <div className="w-full max-w-4xl mx-auto py-8 px-4">
      {/* 진행률 표시 */}
      <div className="mb-8">
        <div className="flex items-center justify-between mb-4">
          <h1 className="text-2xl font-bold">파트너 등록</h1>
          <span className="text-sm text-muted-foreground">
            {currentStep} / {STEPS.length}
          </span>
        </div>
        <Progress value={progress} className="mb-6" />

        {/* 스텝 네비게이션 */}
        <div className="flex items-center justify-between">
          {STEPS.map((step, index) => {
            const Icon = step.icon;
            const isCompleted = completedSteps.has(step.id);
            const isCurrent = currentStep === step.id;
            const isAccessible = step.id <= Math.max(...completedSteps) + 1;

            return (
              <React.Fragment key={step.id}>
                <div
                  className={cn(
                    "flex flex-col items-center cursor-pointer transition-all ",
                    isAccessible ? "opacity-100" : "opacity-50 cursor-not-allowed"
                  )}
                  onClick={() => handleStepClick(step.id)}
                >
                  <div className={cn(
                    "w-12 h-12 rounded-full flex items-center justify-center mb-2 border-2 transition-all",
                    isCompleted
                      ? "bg-green-500 border-green-500 text-white"
                      : isCurrent
                        ? "bg-blue-500 border-blue-500 text-white"
                        : "border-gray-300 text-gray-400"
                  )}>
                    {isCompleted ? (
                      <Check className="w-6 h-6" />
                    ) : (
                      <Icon className="w-6 h-6" />
                    )}
                  </div>
                  <div className="text-center">
                    <div className={cn(
                      "text-sm font-medium",
                      isCurrent ? "text-blue-600" : isCompleted ? "text-green-600" : "text-gray-500"
                    )}>
                      {step.title}
                    </div>
                    <div className="text-xs text-gray-400 mt-1">
                      {step.description}
                    </div>
                  </div>
                </div>

                {index < STEPS.length - 1 && (
                  <ChevronRight className="w-5 h-5 text-gray-300 mx-4" />
                )}
              </React.Fragment>
            );
          })}
        </div>
      </div>

      {/* 스텝 콘텐츠 */}
      <div className="bg-white rounded-lg border shadow-sm p-6">
        {currentStep === 1 && (
          <ConsentStep
            data={consentData}
            onChange={setConsentData}
            onNext={() => handleStepComplete(1)}
          />
        )}

        {currentStep === 2 && (
          <AccountStep
            data={accountData}
            onChange={setAccountData}
            onNext={() => handleStepComplete(2)}
            onBack={() => setCurrentStep(1)}
            enhancedCountryArray={enhancedCountryArray}
          />
        )}

        {currentStep === 3 && (
          <VendorStep
            data={{
              ...vendorData,
              // 업체 국가가 설정되지 않았다면 계정의 국가를 사용
              country: vendorData.country || accountData.country,
            }}
            onChange={setVendorData}
            onBack={() => setCurrentStep(2)}
            onComplete={() => {
              handleStepComplete(3);
              router.push(`/${lng}/partners/dashboard`);
            }}
            accountData={accountData}
            consentData={consentData}
            vendorTypes={vendorTypes}
            isLoadingVendorTypes={isLoadingVendorTypes}
            businessRegistrationFiles={businessRegistrationFiles}
            setBusinessRegistrationFiles={setBusinessRegistrationFiles}
            isoCertificationFiles={isoCertificationFiles}
            setIsoCertificationFiles={setIsoCertificationFiles}
            creditReportFiles={creditReportFiles}
            setCreditReportFiles={setCreditReportFiles}
            bankAccountFiles={bankAccountFiles}
            setBankAccountFiles={setBankAccountFiles}
            enhancedCountryArray={enhancedCountryArray}
            contactTaskOptions={contactTaskOptions}
            lng={lng}
            policyVersions={policyVersions}
          />
        )}
      </div>
    </div>
  );
}

// Step 2: 계정 생성
function AccountStep({
  data, onChange, onNext, onBack,
  enhancedCountryArray
}) {
  const [isLoading, setIsLoading] = useState(false);
  const [emailCheckError, setEmailCheckError] = useState('');

  // 입력 핸들러
  const handleInputChange = (field, value) => {
    onChange(prev => ({ ...prev, [field]: value }));
  };

  // 전화번호 validation
  const phoneValidation = validatePhoneNumber(data.phone, data.country);

  // 전체 입력 유효성
  const isValid =
    data.name &&
    data.email &&
    data.country &&
    data.phone &&
    phoneValidation.isValid;

  // 이메일 중복체크 + 다음단계
  const handleNext = async () => {
    if (!isValid) return;

    setIsLoading(true);
    setEmailCheckError('');
    try {
      const isUsed = await checkEmailExists(data.email);
      if (isUsed) {
        setEmailCheckError('이미 사용 중인 이메일입니다.');
        return;
      }
      onNext();
    } catch (error) {
      setEmailCheckError('이메일 확인 중 오류가 발생했습니다.');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-xl font-semibold mb-2">계정 정보 입력</h2>
        <p className="text-gray-600 text-sm">
          서비스 이용을 위한 개인 계정을 생성합니다.
        </p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium mb-1">
            이름 <span className="text-red-500">*</span>
          </label>
          <Input
            type="text"
            placeholder="이름을 입력하세요"
            value={data.name}
            onChange={(e) => handleInputChange('name', e.target.value)}
          />
        </div>

        <div>
          <label className="block text-sm font-medium mb-1">
            이메일 <span className="text-red-500">*</span>
          </label>
          <Input
            type="email"
            placeholder="이메일을 입력하세요"
            value={data.email}
            onChange={(e) => handleInputChange('email', e.target.value)}
          />
          {emailCheckError && (
            <p className="text-xs text-red-500 mt-1">{emailCheckError}</p>
          )}
        </div>

        <div>
          <label className="block text-sm font-medium mb-1">
            국가 <span className="text-red-500">*</span>
          </label>
          <Popover>
            <PopoverTrigger asChild>
              <Button
                variant="outline"
                role="combobox"
                className={cn(
                  "w-full justify-between",
                  !data.country && "text-muted-foreground"
                )}
              >
                {enhancedCountryArray.find(c => c.code === data.country)?.label || "국가 선택"}
                <ChevronsUpDown className="ml-2 opacity-50" />
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-full p-0">
              <Command>
                <CommandInput placeholder="국가 검색..." />
                <CommandList>
                  <CommandEmpty>No country found.</CommandEmpty>
                  <CommandGroup>
                    {enhancedCountryArray.map((country) => (
                      <CommandItem
                        key={country.code}
                        value={country.label}
                        onSelect={() => handleInputChange('country', country.code)}
                      >
                        <Check
                          className={cn(
                            "mr-2",
                            country.code === data.country
                              ? "opacity-100"
                              : "opacity-0"
                          )}
                        />
                        {country.label}
                      </CommandItem>
                    ))}
                  </CommandGroup>
                </CommandList>
              </Command>
            </PopoverContent>
          </Popover>
        </div>

        <div>
          <label className="block text-sm font-medium mb-1">
            전화번호 <span className="text-red-500">*</span>
          </label>
          <PhoneInput
            value={data.phone}
            onChange={(value) => handleInputChange('phone', value)}
            countryCode={data.country}
            showValidation={true}
          />
        </div>
      </div>

      <div className="flex justify-between">
        <Button variant="outline" onClick={onBack}>
          이전
        </Button>
        <Button onClick={handleNext} disabled={!isValid || isLoading}>
          {isLoading ? '확인 중...' : '다음 단계'}
        </Button>
      </div>
    </div>
  );
}

// Step 3: 업체 등록
function VendorStep(props) {
  return <CompleteVendorForm {...props} />;
}

// 나머지 CompeleteVendorForm과 FileUploadSection은 기존과 동일하되, 
// PhoneInput 컴포넌트를 사용하도록 수정
function CompleteVendorForm({
  data, onChange, onBack, onComplete, accountData, consentData,
  vendorTypes, isLoadingVendorTypes, businessRegistrationFiles, setBusinessRegistrationFiles,
  isoCertificationFiles, setIsoCertificationFiles, creditReportFiles, setCreditReportFiles,
  bankAccountFiles, setBankAccountFiles, enhancedCountryArray, contactTaskOptions, lng, policyVersions
}) {
  const [isSubmitting, setIsSubmitting] = useState(false);

  // 담당자 관리 함수들
  const addContact = () => {
    onChange(prev => ({
      ...prev,
      contacts: [...prev.contacts, {
        contactName: "",
        contactPosition: "",
        contactDepartment: "",
        contactTask: "",
        contactEmail: "",
        contactPhone: "",
      }]
    }));
  };

  const removeContact = (index) => {
    onChange(prev => ({
      ...prev,
      contacts: prev.contacts.filter((_, i) => i !== index)
    }));
  };

  const updateContact = (index, field, value) => {
    onChange(prev => ({
      ...prev,
      contacts: prev.contacts.map((contact, i) =>
        i === index ? { ...contact, [field]: value } : contact
      )
    }));
  };

  // 폼 입력 변경 핸들러
  const handleInputChange = (field, value) => {
    onChange(prev => ({ ...prev, [field]: value }));
  };

  // 파일 업로드 핸들러들
  const createFileUploadHandler = (setFiles, currentFiles) => ({
    onDropAccepted: (acceptedFiles) => {
      const newFiles = [...currentFiles, ...acceptedFiles];
      setFiles(newFiles);
    },
    onDropRejected: (fileRejections) => {
      fileRejections.forEach((rej) => {
        toast({
          variant: "destructive",
          title: "File Error",
          description: `${rej.file.name}: ${rej.errors[0]?.message || "Upload failed"}`,
        });
      });
    },
    removeFile: (index) => {
      const updated = [...currentFiles];
      updated.splice(index, 1);
      setFiles(updated);
    }
  });

  const businessRegistrationHandler = createFileUploadHandler(setBusinessRegistrationFiles, businessRegistrationFiles);
  const isoCertificationHandler = createFileUploadHandler(setIsoCertificationFiles, isoCertificationFiles);
  const creditReportHandler = createFileUploadHandler(setCreditReportFiles, creditReportFiles);
  const bankAccountHandler = createFileUploadHandler(setBankAccountFiles, bankAccountFiles);

  // 유효성 검사
  const validateRequiredFiles = () => {
    const errors = [];

    if (businessRegistrationFiles.length === 0) {
      errors.push("사업자등록증을 업로드해주세요.");
    }

    if (isoCertificationFiles.length === 0) {
      errors.push("ISO 인증서를 업로드해주세요.");
    }

    if (creditReportFiles.length === 0) {
      errors.push("신용평가보고서를 업로드해주세요.");
    }

    if (data.country !== "KR" && bankAccountFiles.length === 0) {
      errors.push("대금지급 통장사본을 업로드해주세요.");
    }

    return errors;
  };

  // 전화번호 검증
  const vendorPhoneValidation = validatePhoneNumber(data.phone, data.country);
  const contactsValid = data.contacts.length > 0 &&
    data.contacts[0].contactName &&
    data.contacts.every(contact =>
      contact.contactPhone ? validatePhoneNumber(contact.contactPhone, data.country).isValid : true
    );

  const isFormValid = data.vendorName && data.vendorTypeId && data.items &&
    data.country && data.phone && vendorPhoneValidation.isValid && data.email &&
    contactsValid &&
    validateRequiredFiles().length === 0;

  // 최종 제출 (기존과 동일)
  const handleSubmit = async () => {
    const fileErrors = validateRequiredFiles();
    if (fileErrors.length > 0) {
      toast({
        variant: "destructive",
        title: "파일 업로드 필수",
        description: fileErrors.join("\n"),
      });
      return;
    }

    setIsSubmitting(true);
    try {
      const formData = new FormData();

      const completeData = {
        account: accountData,
        vendor: {
          ...data,
          email: data.email || accountData.email,
        },
        consents: {
          privacy_policy: {
            agreed: consentData.privacy,
            version: policyVersions.privacy_policy
          },
          terms_of_service: {
            agreed: consentData.terms,
            version: policyVersions.terms_of_service
          },
          marketing: {
            agreed: consentData.marketing,
            version: policyVersions.privacy_policy
          }
        }
      };

      formData.append('completeData', JSON.stringify(completeData));

      businessRegistrationFiles.forEach(file => {
        formData.append('businessRegistration', file);
      });

      isoCertificationFiles.forEach(file => {
        formData.append('isoCertification', file);
      });

      creditReportFiles.forEach(file => {
        formData.append('creditReport', file);
      });

      if (data.country !== "KR") {
        bankAccountFiles.forEach(file => {
          formData.append('bankAccountCopy', file);
        });
      }

      const response = await fetch('/api/auth/signup-with-vendor', {
        method: 'POST',
        body: formData,
      });

      const result = await response.json();

      if (response.ok) {
        toast({
          title: "등록 완료",
          description: "회원가입 및 업체 등록이 완료되었습니다. 관리자 승인 후 서비스를 이용하실 수 있습니다.",
        });
        onComplete();
      } else {
        toast({
          variant: "destructive",
          title: "오류",
          description: result.error || "등록에 실패했습니다.",
        });
      }
    } catch (error) {
      console.error(error);
      toast({
        variant: "destructive",
        title: "서버 에러",
        description: error.message || "에러가 발생했습니다.",
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="space-y-8">
      <div>
        <h2 className="text-xl font-semibold mb-2">업체 정보 등록</h2>
        <p className="text-gray-600 text-sm">
          업체 정보와 필요한 서류를 등록해주세요. 모든 정보는 관리자 검토 후 승인됩니다.
        </p>
      </div>

      {/* 기본 정보 */}
      <div className="rounded-md border p-6 space-y-4">
        <h4 className="text-md font-semibold">기본 정보</h4>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {/* 업체 유형 */}
          <div>
            <label className="block text-sm font-medium mb-1">
              업체유형 <span className="text-red-500">*</span>
            </label>
            <Popover>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  role="combobox"
                  className={cn(
                    "w-full justify-between",
                    !data.vendorTypeId && "text-muted-foreground"
                  )}
                  disabled={isSubmitting || isLoadingVendorTypes}
                >
                  {isLoadingVendorTypes
                    ? "Loading..."
                    : vendorTypes.find(type => type.id === data.vendorTypeId)?.[lng === "ko" ? "nameKo" : "nameEn"] || "업체유형 선택"}
                  <ChevronsUpDown className="ml-2 opacity-50" />
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-full p-0">
                <Command>
                  <CommandInput placeholder="업체유형 검색..." />
                  <CommandList>
                    <CommandEmpty>No vendor type found.</CommandEmpty>
                    <CommandGroup>
                      {vendorTypes.map((type) => (
                        <CommandItem
                          key={type.id}
                          value={lng === "ko" ? type.nameKo : type.nameEn}
                          onSelect={() => handleInputChange('vendorTypeId', type.id)}
                        >
                          <Check
                            className={cn(
                              "mr-2",
                              type.id === data.vendorTypeId
                                ? "opacity-100"
                                : "opacity-0"
                            )}
                          />
                          {lng === "ko" ? type.nameKo : type.nameEn}
                        </CommandItem>
                      ))}
                    </CommandGroup>
                  </CommandList>
                </Command>
              </PopoverContent>
            </Popover>
          </div>

          {/* 업체명 */}
          <div>
            <label className="block text-sm font-medium mb-1">
              업체명 <span className="text-red-500">*</span>
            </label>
            <Input
              value={data.vendorName}
              onChange={(e) => handleInputChange('vendorName', e.target.value)}
              disabled={isSubmitting}
            />
            <p className="text-xs text-gray-500 mt-1">
              {(data.country || accountData.country) === "KR"
                ? "사업자 등록증에 표기된 정확한 회사명을 입력하세요."
                : "해외 업체의 경우 영문 회사명을 입력하세요."}
            </p>
          </div>

          {/* 공급품목 */}
          <div>
            <label className="block text-sm font-medium mb-1">
              공급품목 <span className="text-red-500">*</span>
            </label>
            <Input
              value={data.items}
              onChange={(e) => handleInputChange('items', e.target.value)}
              disabled={isSubmitting}
            />
            <p className="text-xs text-gray-500 mt-1">
              공급 가능한 제품/서비스를 입력하세요
            </p>
          </div>

          {/* 사업자등록번호 */}
          <div>
            <label className="block text-sm font-medium mb-1">
              사업자등록번호 <span className="text-red-500">*</span>
            </label>
            <Input
              value={data.taxId}
              onChange={(e) => handleInputChange('taxId', e.target.value)}
              disabled={isSubmitting}
              placeholder="123-45-67890"
            />
          </div>

          {/* 주소 */}
          <div>
            <label className="block text-sm font-medium mb-1">주소</label>
            <Input
              value={data.address}
              onChange={(e) => handleInputChange('address', e.target.value)}
              disabled={isSubmitting}
            />
          </div>

          {/* 국가 */}
          <div>
            <label className="block text-sm font-medium mb-1">
              국가 <span className="text-red-500">*</span>
            </label>
            <Popover>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  role="combobox"
                  className={cn(
                    "w-full justify-between",
                    !data.country && "text-muted-foreground"
                  )}
                  disabled={isSubmitting}
                >
                  {enhancedCountryArray.find(c => c.code === data.country)?.label || "국가 선택"}
                  <ChevronsUpDown className="ml-2 opacity-50" />
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-full p-0">
                <Command>
                  <CommandInput placeholder="국가 검색..." />
                  <CommandList>
                    <CommandEmpty>No country found.</CommandEmpty>
                    <CommandGroup>
                      {enhancedCountryArray.map((country) => (
                        <CommandItem
                          key={country.code}
                          value={country.label}
                          onSelect={() => handleInputChange('country', country.code)}
                        >
                          <Check
                            className={cn(
                              "mr-2",
                              country.code === data.country
                                ? "opacity-100"
                                : "opacity-0"
                            )}
                          />
                          {country.label}
                        </CommandItem>
                      ))}
                    </CommandGroup>
                  </CommandList>
                </Command>
              </PopoverContent>
            </Popover>
          </div>

          {/* 대표 전화 - PhoneInput 사용 */}
          <div>
            <label className="block text-sm font-medium mb-1">
              대표 전화 <span className="text-red-500">*</span>
            </label>
            <PhoneInput
              value={data.phone}
              onChange={(value) => handleInputChange('phone', value)}
              countryCode={data.country}
              disabled={isSubmitting}
              showValidation={true}
            />
          </div>

          {/* 대표 이메일 */}
          <div>
            <label className="block text-sm font-medium mb-1">
              대표 이메일 <span className="text-red-500">*</span>
            </label>
            <Input
              value={data.email}
              onChange={(e) => handleInputChange('email', e.target.value)}
              disabled={isSubmitting}
              placeholder={accountData.email}
            />
            <p className="text-xs text-gray-500 mt-1">
              비워두면 계정 이메일({accountData.email})을 사용합니다.
            </p>
          </div>

          {/* 웹사이트 */}
          <div>
            <label className="block text-sm font-medium mb-1">웹사이트</label>
            <Input
              value={data.website}
              onChange={(e) => handleInputChange('website', e.target.value)}
              disabled={isSubmitting}
            />
          </div>
        </div>
      </div>

      {/* 담당자 정보 - PhoneInput 사용 */}
      <div className="rounded-md border p-6 space-y-4">
        <div className="flex items-center justify-between">
          <h4 className="text-md font-semibold">담당자 정보 (최소 1명)</h4>
          <Button
            type="button"
            variant="outline"
            onClick={addContact}
            disabled={isSubmitting}
          >
            <Plus className="mr-1 h-4 w-4" />
            담당자 추가
          </Button>
        </div>

        <div className="space-y-4">
          {data.contacts.map((contact, index) => (
            <div
              key={index}
              className="bg-muted/10 rounded-md p-4 space-y-4"
            >
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium mb-1">
                    담당자명 <span className="text-red-500">*</span>
                  </label>
                  <Input
                    value={contact.contactName}
                    onChange={(e) => updateContact(index, 'contactName', e.target.value)}
                    disabled={isSubmitting}
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium mb-1">
                    직급 <span className="text-red-500">*</span>
                  </label>
                  <Input
                    value={contact.contactPosition}
                    onChange={(e) => updateContact(index, 'contactPosition', e.target.value)}
                    disabled={isSubmitting}
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium mb-1">
                    부서 <span className="text-red-500">*</span>
                  </label>
                  <Input
                    value={contact.contactDepartment}
                    onChange={(e) => updateContact(index, 'contactDepartment', e.target.value)}
                    disabled={isSubmitting}
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium mb-1">
                    담당업무 <span className="text-red-500">*</span>
                  </label>
                  <Select
                    value={contact.contactTask}
                    onValueChange={(value) => updateContact(index, 'contactTask', value)}
                    disabled={isSubmitting}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="담당업무를 선택하세요" />
                    </SelectTrigger>
                    <SelectContent>
                      {contactTaskOptions.map((option) => (
                        <SelectItem key={option.value} value={option.value}>
                          {option.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div>
                  <label className="block text-sm font-medium mb-1">
                    이메일 <span className="text-red-500">*</span>
                  </label>
                  <Input
                    value={contact.contactEmail}
                    onChange={(e) => updateContact(index, 'contactEmail', e.target.value)}
                    disabled={isSubmitting}
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium mb-1">
                    전화번호 <span className="text-red-500">*</span>
                  </label>
                  <PhoneInput
                    value={contact.contactPhone}
                    onChange={(value) => updateContact(index, 'contactPhone', value)}
                    countryCode={data.country}
                    disabled={isSubmitting}
                    showValidation={true}
                  />
                </div>
              </div>

              {data.contacts.length > 1 && (
                <div className="flex justify-end">
                  <Button
                    variant="destructive"
                    onClick={() => removeContact(index)}
                    disabled={isSubmitting}
                  >
                    <X className="mr-1 h-4 w-4" />
                    삭제
                  </Button>
                </div>
              )}
            </div>
          ))}
        </div>
      </div>

      {/* 한국 사업자 정보 - PhoneInput 사용 */}
      {data.country === "KR" && (
        <div className="rounded-md border p-6 space-y-4">
          <h4 className="text-md font-semibold">한국 사업자 정보</h4>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium mb-1">
                대표자 이름 <span className="text-red-500">*</span>
              </label>
              <Input
                value={data.representativeName}
                onChange={(e) => handleInputChange('representativeName', e.target.value)}
                disabled={isSubmitting}
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">
                대표자 생년월일 <span className="text-red-500">*</span>
              </label>
              <Input
                placeholder="YYYY-MM-DD"
                value={data.representativeBirth}
                onChange={(e) => handleInputChange('representativeBirth', e.target.value)}
                disabled={isSubmitting}
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">
                대표자 이메일 <span className="text-red-500">*</span>
              </label>
              <Input
                value={data.representativeEmail}
                onChange={(e) => handleInputChange('representativeEmail', e.target.value)}
                disabled={isSubmitting}
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">
                대표자 전화번호 <span className="text-red-500">*</span>
              </label>
              <PhoneInput
                value={data.representativePhone}
                onChange={(value) => handleInputChange('representativePhone', value)}
                countryCode="KR"
                disabled={isSubmitting}
                showValidation={true}
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">
                법인등록번호 <span className="text-red-500">*</span>
              </label>
              <Input
                value={data.corporateRegistrationNumber}
                onChange={(e) => handleInputChange('corporateRegistrationNumber', e.target.value)}
                disabled={isSubmitting}
              />
            </div>
            <div className="flex items-center space-x-2">
              <input
                type="checkbox"
                id="work-experience"
                checked={data.representativeWorkExpirence}
                onChange={(e) => handleInputChange('representativeWorkExpirence', e.target.checked)}
                disabled={isSubmitting}
                className="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
              />
              <label htmlFor="work-experience" className="text-sm">
                대표자 삼성중공업 근무이력
              </label>
            </div>
          </div>
        </div>
      )}

      {/* 필수 첨부 서류 */}
      <div className="rounded-md border p-6 space-y-6">
        <h4 className="text-md font-semibold">필수 첨부 서류</h4>

        <FileUploadSection
          title="사업자등록증"
          description="사업자등록증 스캔본 또는 사진을 업로드해주세요."
          files={businessRegistrationFiles}
          onDropAccepted={businessRegistrationHandler.onDropAccepted}
          onDropRejected={businessRegistrationHandler.onDropRejected}
          removeFile={businessRegistrationHandler.removeFile}
          isSubmitting={isSubmitting}
        />

        <FileUploadSection
          title="ISO 인증서"
          description="ISO 9001, ISO 14001 등 품질/환경 관리 인증서를 업로드해주세요."
          files={isoCertificationFiles}
          onDropAccepted={isoCertificationHandler.onDropAccepted}
          onDropRejected={isoCertificationHandler.onDropRejected}
          removeFile={isoCertificationHandler.removeFile}
          isSubmitting={isSubmitting}
        />

        <FileUploadSection
          title="신용평가보고서"
          description="신용평가기관에서 발급한 발행 1년 이내의 신용평가보고서를 업로드해주세요."
          files={creditReportFiles}
          onDropAccepted={creditReportHandler.onDropAccepted}
          onDropRejected={creditReportHandler.onDropRejected}
          removeFile={creditReportHandler.removeFile}
          isSubmitting={isSubmitting}
        />

        {data.country !== "KR" && (
          <FileUploadSection
            title="대금지급 통장사본"
            description="대금 지급용 은행 계좌의 통장 사본 또는 계좌증명서를 업로드해주세요."
            files={bankAccountFiles}
            onDropAccepted={bankAccountHandler.onDropAccepted}
            onDropRejected={bankAccountHandler.onDropRejected}
            removeFile={bankAccountHandler.removeFile}
            isSubmitting={isSubmitting}
          />
        )}
      </div>

      <div className="flex justify-between">
        <Button variant="outline" onClick={onBack}>
          이전
        </Button>
        <Button onClick={handleSubmit} disabled={!isFormValid || isSubmitting}>
          {isSubmitting ? (
            <>
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              등록 중...
            </>
          ) : (
            "등록 완료"
          )}
        </Button>
      </div>
    </div>
  );
}

// 파일 업로드 섹션 컴포넌트 (기존과 동일)
function FileUploadSection({
  title,
  description,
  files,
  onDropAccepted,
  onDropRejected,
  removeFile,
  isSubmitting,
  required = true
}) {
  return (
    <div className="space-y-4">
      <div>
        <h5 className="text-sm font-medium">
          {title}
          {required && <span className="text-red-500 ml-1">*</span>}
        </h5>
        <p className="text-xs text-muted-foreground mt-1">{description}</p>
      </div>

      <Dropzone
        maxSize={MAX_FILE_SIZE}
        multiple
        onDropAccepted={onDropAccepted}
        onDropRejected={onDropRejected}
        disabled={isSubmitting}
      >
        {({ maxSize }) => (
          <DropzoneZone className="flex justify-center">
            <DropzoneInput />
            <div className="flex items-center gap-4">
              <DropzoneUploadIcon />
              <div className="grid gap-1">
                <DropzoneTitle>파일 업로드</DropzoneTitle>
                <DropzoneDescription>
                  드래그 또는 클릭
                  {maxSize ? ` (최대: ${prettyBytes(maxSize)})` : null}
                </DropzoneDescription>
              </div>
            </div>
          </DropzoneZone>
        )}
      </Dropzone>

      {files.length > 0 && (
        <div className="mt-2">
          <ScrollArea className="max-h-32">
            <FileList className="gap-2">
              {files.map((file, i) => (
                <FileListItem key={file.name + i}>
                  <FileListHeader>
                    <FileListIcon />
                    <FileListInfo>
                      <FileListName>{file.name}</FileListName>
                      <FileListDescription>
                        {prettyBytes(file.size)}
                      </FileListDescription>
                    </FileListInfo>
                    <FileListAction onClick={() => removeFile(i)}>
                      <X className="h-4 w-4" />
                    </FileListAction>
                  </FileListHeader>
                </FileListItem>
              ))}
            </FileList>
          </ScrollArea>
        </div>
      )}
    </div>
  );
}