'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Input from '../../components/atoms/Input';
import Button from '../../components/atoms/Button';
import { getCountries, getCities, getStats } from '../../utils/countryStateCityAPI';
import Swal from 'sweetalert2';
import CountrySelect from '../../components/atoms/CountrySelect';
import { useUserStore } from '../../../store/useUserStore';
import { 
  FaGlobe, 
  FaBuilding, 
  FaUser, 
  FaPhone, 
  FaEnvelope, 
  FaMapMarkerAlt, 
  FaBriefcase, 
  FaUsers,
  FaGraduationCap,
  FaShieldAlt,
  FaCheckCircle,
  FaRocket,
  FaSearch,
  FaHandshake,
  FaChartLine,
  FaLock,
  FaAward,
  FaLanguage,
  FaClock,
  FaLaptop,
  FaMoneyBillAlt,
  FaStar,
  FaCamera,
  FaArrowRight,
  FaArrowLeft
} from 'react-icons/fa';

export default function ConsultantRegistration() {
  const router = useRouter();
  const setUser = useUserStore((state) => state.setUser);
  
  // Combined form state
  const [form, setForm] = useState({
    // Registration fields
    company_name: '',
    number_of_employees: '',
    nationality: '',
    state: '',
    city: '',
    address: '',
    first_name: '',
    last_name: '',
    designation: '',
    email: '',
    mobile_number: '',
    password: '',
    confirm_password: '',
    comment: '',
    agree: false,
    
    // Profile completion fields
    consultation_fee: 0,
    consultation_currency: 'USD',
    target_countries: [],
    services: [],
    specialization: [],
    languages: [],
    response_time: 'normal',
    digital_only: false,
    availability: 'normal',
    profile_picture: null,
  });

  const [errors, setErrors] = useState({});
  const [countries, setCountries] = useState([]);
  const [states, setStates] = useState([]);
  const [cities, setCities] = useState([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [selectedCountryName, setSelectedCountryName] = useState('');
  const [selectedStateName, setSelectedStateName] = useState('');
  const [selectedCityName, setSelectedCityName] = useState('');
  const [currentStep, setCurrentStep] = useState(1); // 1: Basic Info, 2: Company, 3: Professional
  const [selectedFile, setSelectedFile] = useState(null);
  const [previewUrl, setPreviewUrl] = useState(null);

  const employeeRanges = [
    { value: '1-5', label: '1-5 employees' },
    { value: '6-10', label: '6-10 employees' },
    { value: '11-20', label: '11-20 employees' },
    { value: '21-50', label: '21-50 employees' },
    { value: '51-100', label: '51-100 employees' },
    { value: '100+', label: '100+ employees' }
  ];

  const responseTimes = [
    { value: 'urgent', label: 'Within 24 hours' },
    { value: 'fast', label: '1-2 days' },
    { value: 'normal', label: '3-5 days' }
  ];

  const availabilityOptions = [
    { value: 'high', label: 'High availability' },
    { value: 'normal', label: 'Normal availability' },
    { value: 'limited', label: 'Limited availability' }
  ];

  // Multi-select options
  const serviceOptions = [
    'Visa Application',
    'University Admission',
    'Documentation Support',
    'Interview Preparation',
    'Language Test Prep',
    'Financial Documentation'
  ];

  const specializationOptions = [
    'Student Visa',
    'Work Visa',
    'Tourist Visa',
    'Family Visa',
    'Business Visa',
    'Permanent Residency'
  ];

  const languageOptions = [
    'English',
    'Urdu',
    'Hindi',
    'Arabic',
    'French',
    'Spanish'
  ];

  const targetCountryOptions = [
    'Canada',
    'USA',
    'UK',
    'Australia',
    'Germany',
    'UAE'
  ];

  const currencyOptions = [
    { value: 'USD', label: 'USD ($)' },
    { value: 'EUR', label: 'EUR (€)' },
    { value: 'GBP', label: 'GBP (£)' },
    { value: 'AED', label: 'AED (د.إ)' },
    { value: 'PKR', label: 'PKR (₨)' },
    { value: 'INR', label: 'INR (₹)' },
  ];

  const platformFeatures = [
    { icon: <FaSearch className="text-blue-500" />, title: "AI Matching", desc: "Get matched with students automatically" },
    { icon: <FaChartLine className="text-green-500" />, title: "Dashboard", desc: "Track all applications in one place" },
    { icon: <FaHandshake className="text-purple-500" />, title: "University Network", desc: "Access exclusive partnerships" },
    { icon: <FaShieldAlt className="text-amber-500" />, title: "Verified Badge", desc: "Build trust with verification" }
  ];

  // Helper functions
  const passwordValidate = (password) => {
    const minLength = password.length >= 8;
    const hasNumber = /\d/.test(password);
    const hasUppercase = /[A-Z]/.test(password);
    const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(password);
    
    return {
      isValid: minLength && hasNumber && hasUppercase && hasSpecialChar,
      minLength,
      hasNumber,
      hasUppercase,
      hasSpecialChar
    };
  };

  function toOptions(rows) {
    if (!Array.isArray(rows)) return [];
    return rows.map(r => ({ label: r.name, value: String(r.id) }));
  }
  
  function getLocationNameById(id, list) {
    const item = list.find(item => String(item.id) === String(id));
    return item ? item.name : '';
  }
  
  function readSelectValue(eOrValue) {
    if (eOrValue?.target?.value !== undefined) return eOrValue.target.value;
    return String(eOrValue ?? '');
  }

  // Location handlers
  const handleCountryChange = (eOrValue) => {
    const value = readSelectValue(eOrValue);
    const selectedCountry = countries.find((c) => String(c.id) === value);
    
    setForm(prev => ({
      ...prev,
      nationality: value,
      state: '',
      city: ''
    }));
    
    setSelectedCountryName(selectedCountry ? selectedCountry.name : '');
    setSelectedStateName('');
    setSelectedCityName('');
  };
  
  const handleStateChange = (eOrValue) => {
    const value = readSelectValue(eOrValue);
    const selectedState = states.find((s) => String(s.id) === value);
    
    setForm(prev => ({
      ...prev,
      state: value,
      city: ''
    }));
    
    setSelectedStateName(selectedState ? selectedState.name : '');
    setSelectedCityName('');
  };
  
  const handleCityChange = (eOrValue) => {
    const value = readSelectValue(eOrValue);
    const selectedCity = cities.find((c) => String(c.id) === value);
    
    setForm(prev => ({ ...prev, city: value }));
    setSelectedCityName(selectedCity ? selectedCity.name : '');
  };

  // Multi-select handlers
  const handleMultiSelect = (field, value) => {
    setForm(prev => {
      const currentArray = Array.isArray(prev[field]) ? prev[field] : [];
      const newArray = currentArray.includes(value)
        ? currentArray.filter(item => item !== value)
        : [...currentArray, value];
      return { ...prev, [field]: newArray };
    });
  };

  // File upload handler
// In the handleFileSelect function, ensure it's setting the base64 data
const handleFileSelect = (e) => {
  const file = e.target.files?.[0];
  if (!file) return;

  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
  if (!allowedTypes.includes(file.type)) {
    Swal.fire({
      icon: 'error',
      title: 'Invalid File Type',
      text: 'Please upload JPEG, PNG, GIF, or WebP image.',
      timer: 3000
    });
    return;
  }

  const maxSize = 5 * 1024 * 1024;
  if (file.size > maxSize) {
    Swal.fire({
      icon: 'error',
      title: 'File Too Large',
      text: 'Maximum file size is 5MB.',
      timer: 3000
    });
    return;
  }

  setSelectedFile(file);
  
  const reader = new FileReader();
  reader.onload = (e) => {
    const base64Data = e.target?.result;
    console.log('File read successfully, base64 length:', base64Data?.length);
    console.log('Base64 starts with:', base64Data?.substring(0, 50) + '...');
    
    setPreviewUrl(base64Data);
    setForm(prev => ({ 
      ...prev, 
      profile_picture: base64Data 
    }));
  };
  
  reader.onerror = (error) => {
    console.error('Error reading file:', error);
    Swal.fire({
      icon: 'error',
      title: 'File Read Error',
      text: 'Failed to read the selected file. Please try again.',
      timer: 3000
    });
  };
  
  reader.readAsDataURL(file);
};

  // Basic input handler
  const handleChange = (e) => {
    const { name, value, type } = e.target;
    
    if (type === 'checkbox') {
      const checked = e.target.checked;
      setForm(prev => ({ ...prev, [name]: checked }));
    } else if (type === 'number') {
      setForm(prev => ({ ...prev, [name]: parseFloat(value) || 0 }));
    } else {
      setForm(prev => ({ ...prev, [name]: value }));
    }
    
    if (errors[name]) {
      setErrors({ ...errors, [name]: null });
    }
  };

  // Currency change handler
  const handleCurrencyChange = (currency) => {
    setForm(prev => ({ ...prev, consultation_currency: currency }));
  };

  // Step validation
  const validateStep1 = () => {
    const newErrors = {};
    if (!form.first_name.trim()) newErrors.first_name = 'First name is required';
    if (!form.last_name.trim()) newErrors.last_name = 'Last name is required';
    if (!form.email.trim()) newErrors.email = 'Email is required';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) newErrors.email = 'Enter a valid email';
    if (!form.mobile_number.trim()) newErrors.mobile_number = 'Phone number is required';
    if (!form.password) {
      newErrors.password = 'Password is required';
    } else {
      const passwordValidation = passwordValidate(form.password);
      if (!passwordValidation.isValid) {
        newErrors.password = 'Password must be stronger';
      }
    }
    if (form.password !== form.confirm_password) newErrors.confirm_password = 'Passwords must match';
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const validateStep2 = () => {
    const newErrors = {};
    if (!form.company_name.trim()) newErrors.company_name = 'Company name is required';
    if (!form.designation.trim()) newErrors.designation = 'Designation is required';
    if (!form.address.trim()) newErrors.address = 'Address is required';
    if (!form.nationality) newErrors.nationality = 'Country is required';
    if (!form.state) newErrors.state = 'State is required';
    if (!form.city) newErrors.city = 'City is required';
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const validateStep3 = () => {
    const newErrors = {};
    // Profile picture is required
    if (!form.profile_picture) {
      newErrors.profile_picture = 'Profile picture is required';
    }
    
    // At least one selection for each multi-select
    if (form.target_countries.length === 0) newErrors.target_countries = 'Select at least one target country';
    if (form.services.length === 0) newErrors.services = 'Select at least one service';
    if (form.specialization.length === 0) newErrors.specialization = 'Select at least one specialization';
    if (form.languages.length === 0) newErrors.languages = 'Select at least one language';
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // Submit handler
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (currentStep === 1) {
      if (!validateStep1()) {
        Swal.fire({
          icon: 'warning',
          title: 'Please check your information',
          text: 'Some required fields are missing or incorrect.',
          timer: 3000
        });
        return;
      }
      
      const passwordValidation = passwordValidate(form.password);
      if (!passwordValidation.isValid) {
        Swal.fire({
          icon: 'error',
          title: 'Password Requirements',
          html: `
            <div class="text-left">
              <p class="mb-2">Your password needs:</p>
              <ul class="list-disc list-inside space-y-1">
                <li class="${passwordValidation.minLength ? 'text-green-600' : 'text-red-600'}">✓ 8+ characters</li>
                <li class="${passwordValidation.hasNumber ? 'text-green-600' : 'text-red-600'}">✓ 1 number</li>
                <li class="${passwordValidation.hasUppercase ? 'text-green-600' : 'text-red-600'}">✓ 1 uppercase letter</li>
                <li class="${passwordValidation.hasSpecialChar ? 'text-green-600' : 'text-red-600'}">✓ 1 special character</li>
              </ul>
            </div>
          `,
          confirmButtonColor: '#0a306b'
        });
        return;
      }
      
      setCurrentStep(2);
      window.scrollTo(0, 0);
    } else if (currentStep === 2) {
      if (!validateStep2()) {
        Swal.fire({
          icon: 'warning',
          title: 'Company Information Required',
          text: 'Please complete your company details.',
          timer: 3000
        });
        return;
      }
      
      setCurrentStep(3);
      window.scrollTo(0, 0);
    } else if (currentStep === 3) {
      if (!validateStep3()) {
        Swal.fire({
          icon: 'warning',
          title: 'Profile Information Required',
          text: 'Please complete your professional profile.',
          timer: 3000
        });
        return;
      }
      
      // Show confirmation
      const result = await Swal.fire({
        title: 'Ready to Register?',
        html: `
          <div class="text-left">
            <p class="mb-3">Your application will be submitted for approval.</p>
            <div class="bg-blue-50 p-3 rounded-lg mb-3">
              <p class="font-medium text-blue-800 mb-1">What happens next:</p>
              <ul class="text-blue-700 text-sm space-y-1">
                <li>✓ Account created instantly</li>
                <li>✓ Auto-login to dashboard</li>
                <li>✓ Status: Pending Approval</li>
                <li>✓ Review: 24-48 hours</li>
              </ul>
            </div>
          </div>
        `,
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#0a306b',
        cancelButtonColor: '#6b7280',
        confirmButtonText: 'Yes, submit my application',
        cancelButtonText: 'Review my information'
      });
      
      if (!result.isConfirmed) return;
      
      await submitRegistration();
    }
  };

  const submitRegistration = async () => {
    setIsSubmitting(true);

    try {
      // Convert location IDs to names
      const nationalityName = getLocationNameById(form.nationality, countries);
      const stateName = getLocationNameById(form.state, states);
      const cityName = getLocationNameById(form.city, cities);

      // Prepare data for API
      const requestData = {
        company_name: form.company_name,
        number_of_employees: form.number_of_employees,
        nationality: nationalityName,
        state: stateName,
        city: cityName,
        address: form.address,
        first_name: form.first_name,
        last_name: form.last_name,
        designation: form.designation,
        email: form.email,
        mobile_number: form.mobile_number,
        password: form.password,
        comment: form.comment,
        agree: form.agree,
        response_time: form.response_time,
      digital_only: form.digital_only,
      availability: form.availability,
        
        consultation_fee: form.consultation_fee,
        consultation_currency: form.consultation_currency,
        target_countries: JSON.stringify(form.target_countries),
        services: JSON.stringify(form.services),
        specialization: JSON.stringify(form.specialization),
        languages: JSON.stringify(form.languages),
        response_time: form.response_time,
        digital_only: form.digital_only,
        availability: form.availability,
        profile_picture: form.profile_picture
      };

      const response = await fetch('/api/frontend/consultant/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestData)
      });
      
      const data = await response.json();

      if (response.ok) {
        // Update user store
        setUser(data.data);
        
        // Show success message
        await Swal.fire({
          icon: 'success',
          title: 'Application Submitted!',
          html: `
            <div class="text-center">
              <div class="mb-4 text-4xl">🎉</div>
              <h3 class="text-xl font-semibold mb-2">Welcome to UniversitiesPage!</h3>
              <p class="text-gray-600 mb-3">Your consultant application has been submitted.</p>
              <div class="bg-blue-50 p-3 rounded-lg mb-3">
                <p class="font-medium text-blue-800 mb-1">Status: <span class="text-yellow-600">Pending Approval</span></p>
                <p class="text-blue-700 text-sm">Review time: 24-48 hours</p>
              </div>
              <p class="text-sm text-gray-500 mt-2">Redirecting to dashboard...</p>
            </div>
          `,
          showConfirmButton: false,
          timer: 3000
        });
        
        // Redirect to dashboard
        setTimeout(() => {
          router.push('/consultant-dashboard');
        }, 3000);
        
      } else {
        let errorMessage = data.message || 'Registration failed. Please try again.';
        
        if (data.message && data.message.includes('Email already registered')) {
          errorMessage = 'This email is already registered. Please login instead.';
        }
        
        Swal.fire({
          icon: 'error',
          title: 'Submission Failed',
          text: errorMessage,
          confirmButtonColor: '#0a306b'
        });
      }
    } catch (err) {
      console.error('Network Error:', err);
      Swal.fire({
        icon: 'error',
        title: 'Something went wrong',
        text: 'Network error. Please check your connection and try again.',
        confirmButtonColor: '#0a306b'
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  // Back to previous step
  const handleBack = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
      window.scrollTo(0, 0);
    }
  };

  // Fetch countries
  useEffect(() => {
    const fetchCountries = async () => {
      try {
        const res = await getCountries();
        setCountries(res || []);
      } catch (err) {
        console.error('Error fetching countries:', err);
        setCountries([]);
      }
    };
    fetchCountries();
  }, []);

  // Fetch states
  useEffect(() => {
    if (!form.nationality) {
      setStates([]);
      setCities([]);
      return;
    }

    const fetchStates = async () => {
      try {
        const countryId = Number(form.nationality);
        if (isNaN(countryId)) return;
        
        const res = await getStats(countryId);
        setStates(res || []);
        setCities([]);
      } catch (err) {
        console.error('Error fetching states:', err);
        setStates([]);
      }
    };
    
    fetchStates();
  }, [form.nationality]);

  // Fetch cities
  useEffect(() => {
    if (!form.state) {
      setCities([]);
      return;
    }

    const fetchCities = async () => {
      try {
        const stateId = Number(form.state);
        if (isNaN(stateId)) return;
        
        const res = await getCities(stateId);
        setCities(res || []);
      } catch (err) {
        console.error('Error fetching cities:', err);
        setCities([]);
      }
    };
    
    fetchCities();
  }, [form.state]);

  const countryOptions = toOptions(countries);
  const stateOptions = toOptions(states);
  const cityOptions = toOptions(cities);

  const togglePasswordVisibility = () => setShowPassword(!showPassword);
  const toggleConfirmPasswordVisibility = () => setShowConfirmPassword(!showConfirmPassword);

  // Progress steps
  const steps = [
    { number: 1, title: 'Personal Info', description: 'Your basic information' },
    { number: 2, title: 'Company Info', description: 'Business details' },
    { number: 3, title: 'Professional Info', description: 'Services & expertise' }
  ];

  // Step content based on current step
  const renderStepContent = () => {
    switch (currentStep) {
      case 1:
        return (
          <div className="space-y-6">
            <div className="text-center mb-8">
              <h2 className="text-2xl font-bold text-gray-900">Personal Information</h2>
              <p className="text-gray-600">Tell us about yourself</p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  First Name *
                </label>
                <Input
                  type="text"
                  name="first_name"
                  value={form.first_name}
                  onChange={handleChange}
                  placeholder="John"
                  error={errors.first_name}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Last Name *
                </label>
                <Input
                  type="text"
                  name="last_name"
                  value={form.last_name}
                  onChange={handleChange}
                  placeholder="Doe"
                  error={errors.last_name}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Email Address *
                </label>
                <Input
                  type="email"
                  name="email"
                  value={form.email}
                  onChange={handleChange}
                  placeholder="john@example.com"
                  error={errors.email}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Phone Number *
                </label>
                <Input
                  type="tel"
                  name="mobile_number"
                  value={form.mobile_number}
                  onChange={handleChange}
                  placeholder="+92 300 1234567"
                  error={errors.mobile_number}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Password *
                </label>
                <div className="relative">
                  <Input
                    type={showPassword ? 'text' : 'password'}
                    name="password"
                    value={form.password}
                    onChange={handleChange}
                    placeholder="Create a strong password"
                    error={errors.password}
                  />
                  <button
                    type="button"
                    onClick={togglePasswordVisibility}
                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500"
                  >
                    {showPassword ? '🙈' : '👁️'}
                  </button>
                </div>
                <div className="mt-2 text-xs text-gray-500">
                  <p>Password must include:</p>
                  <ul className="list-disc list-inside">
                    <li>8+ characters</li>
                    <li>1 number</li>
                    <li>1 uppercase letter</li>
                    <li>1 special character</li>
                  </ul>
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Confirm Password *
                </label>
                <div className="relative">
                  <Input
                    type={showConfirmPassword ? 'text' : 'password'}
                    name="confirm_password"
                    value={form.confirm_password}
                    onChange={handleChange}
                    placeholder="Re-enter your password"
                    error={errors.confirm_password}
                  />
                  <button
                    type="button"
                    onClick={toggleConfirmPasswordVisibility}
                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500"
                  >
                    {showConfirmPassword ? '🙈' : '👁️'}
                  </button>
                </div>
              </div>
            </div>

            <div className="bg-blue-50 p-4 rounded-lg">
              <p className="text-sm text-blue-800">
                <strong>Tip:</strong> Use a strong, unique password you haven't used elsewhere.
              </p>
            </div>
          </div>
        );

      case 2:
        return (
          <div className="space-y-6">
            <div className="text-center mb-8">
              <h2 className="text-2xl font-bold text-gray-900">Company Information</h2>
              <p className="text-gray-600">Tell us about your business</p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Company Name *
                </label>
                <Input
                  type="text"
                  name="company_name"
                  value={form.company_name}
                  onChange={handleChange}
                  placeholder="Global Education Consultants"
                  error={errors.company_name}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Your Designation *
                </label>
                <Input
                  type="text"
                  name="designation"
                  value={form.designation}
                  onChange={handleChange}
                  placeholder="e.g., Senior Consultant"
                  error={errors.designation}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Employee Count
                </label>
                <select
                  name="number_of_employees"
                  value={form.number_of_employees}
                  onChange={handleChange}
                  className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                >
                  <option value="">Select number of employees</option>
                  {employeeRanges.map(r => (
                    <option key={r.value} value={r.value}>{r.label}</option>
                  ))}
                </select>
              </div>

              <div className="md:col-span-2">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Company Address *
                </label>
                <textarea
                  name="address"
                  value={form.address}
                  onChange={handleChange}
                  placeholder="Full business address"
                  rows={3}
                  className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                />
                {errors.address && <p className="mt-1 text-sm text-red-500">{errors.address}</p>}
              </div>
            </div>

            <div className="bg-blue-50 p-4 rounded-lg">
              <h3 className="font-medium text-blue-800 mb-2">Business Location</h3>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Country *
                  </label>
                  <CountrySelect
                    name="nationality"
                    placeholder="Select Country"
                    value={form.nationality}
                    onChange={handleCountryChange}
                    options={countryOptions}
                    error={errors.nationality}
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    State *
                  </label>
                  <CountrySelect
                    name="state"
                    placeholder="Select State"
                    value={form.state}
                    onChange={handleStateChange}
                    options={stateOptions}
                    disabled={!form.nationality}
                    error={errors.state}
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    City *
                  </label>
                  <CountrySelect
                    name="city"
                    placeholder="Select City"
                    value={form.city}
                    onChange={handleCityChange}
                    options={cityOptions}
                    disabled={!form.state}
                    error={errors.city}
                  />
                </div>
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Additional Information (Optional)
              </label>
              <textarea
                name="comment"
                value={form.comment}
                onChange={handleChange}
                placeholder="Tell us about your services, experience, or any additional information..."
                rows={3}
                className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>
          </div>
        );

      case 3:
        return (
          <div className="space-y-6">
            <div className="text-center mb-8">
              <h2 className="text-2xl font-bold text-gray-900">Professional Profile</h2>
              <p className="text-gray-600">Tell us about your services</p>
            </div>

            {/* Profile Picture */}
            <div className="bg-blue-50 p-6 rounded-lg">
              <h3 className="font-medium text-gray-900 mb-4">Profile Picture *</h3>
              <div className="flex flex-col md:flex-row items-center gap-6">
                <div className="relative">
                  {previewUrl ? (
                    <img
                      src={previewUrl}
                      alt="Profile preview"
                      className="w-32 h-32 rounded-full object-cover border-4 border-white shadow-lg"
                    />
                  ) : (
                    <div className="w-32 h-32 rounded-full bg-gradient-to-r from-blue-500 to-blue-700 flex items-center justify-center text-white text-4xl font-bold">
                      {form.first_name?.[0]?.toUpperCase() || 'C'}
                    </div>
                  )}
                  <label
                    htmlFor="profile-picture"
                    className="absolute bottom-0 right-0 p-2 bg-blue-600 text-white rounded-full hover:bg-blue-700 cursor-pointer"
                  >
                    <FaCamera />
                  </label>
                  <input
                    type="file"
                    id="profile-picture"
                    onChange={handleFileSelect}
                    accept="image/jpeg,image/jpg,image/png,image/gif,image/webp"
                    className="hidden"
                  />
                </div>
                <div className="flex-1">
                  <p className="text-gray-600 mb-3">
                    Upload a professional headshot. This helps build trust with clients.
                  </p>
                  <p className="text-sm text-gray-500">
                    Max 5MB • JPG, PNG, GIF, WebP
                  </p>
                  {errors.profile_picture && (
                    <p className="mt-2 text-sm text-red-500">{errors.profile_picture}</p>
                  )}
                </div>
              </div>
            </div>

            {/* Consultation Fee */}
            <div>
              <h3 className="font-medium text-gray-900 mb-4">Consultation Fee (Optional)</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Amount
                  </label>
                  <div className="relative">
                    <span className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500">
                      <FaMoneyBillAlt />
                    </span>
                    <input
                      type="number"
                      name="consultation_fee"
                      value={form.consultation_fee}
                      onChange={handleChange}
                      placeholder="0.00"
                      className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    />
                  </div>
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Currency
                  </label>
                  <select
                    value={form.consultation_currency}
                    onChange={(e) => handleCurrencyChange(e.target.value)}
                    className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  >
                    {currencyOptions.map((currency) => (
                      <option key={currency.value} value={currency.value}>
                        {currency.label}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
            </div>


             <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* Digital Consultation */}
        <div className="bg-gray-50 p-4 rounded-lg">
          <h3 className="font-medium text-gray-900 mb-3">Consultation Type</h3>
          <div className="space-y-2">
            <label className="flex items-center space-x-3">
              <input
                type="checkbox"
                name="digital_only"
                checked={form.digital_only}
                onChange={handleChange}
                className="w-4 h-4 text-blue-600 rounded focus:ring-blue-500"
              />
              <span className="text-gray-700">
                <FaLaptop className="inline mr-2 text-gray-500" />
                Offer Digital/Online Consultations Only
              </span>
            </label>
            <p className="text-sm text-gray-500 ml-7">
              Check this if you only provide online consultations
            </p>
          </div>
        </div>

        {/* Availability */}
        <div className="bg-gray-50 p-4 rounded-lg">
          <h3 className="font-medium text-gray-900 mb-3">Your Availability</h3>
          <select
            name="availability"
            value={form.availability}
            onChange={handleChange}
            className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
          >
            <option value="">Select availability</option>
            {availabilityOptions.map(option => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
          <p className="text-sm text-gray-500 mt-2">
            <FaClock className="inline mr-1 text-gray-500" />
            Let clients know when you're available
          </p>
        </div>
      </div>

      {/* Add Response Time Section (if not already included) */}
      <div className="bg-gray-50 p-4 rounded-lg">
        <h3 className="font-medium text-gray-900 mb-3">Response Time</h3>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
          {responseTimes.map(option => (
            <label
              key={option.value}
              className={`flex items-center p-3 rounded-lg cursor-pointer border-2 ${form.response_time === option.value
                  ? 'border-blue-500 bg-blue-50'
                  : 'border-gray-200 bg-white hover:border-gray-300'
                }`}
            >
              <input
                type="radio"
                name="response_time"
                value={option.value}
                checked={form.response_time === option.value}
                onChange={handleChange}
                className="w-4 h-4 text-blue-600 focus:ring-blue-500"
              />
              <span className="ml-3 text-gray-700">
                <FaClock className="inline mr-2 text-gray-500" />
                {option.label}
              </span>
            </label>
          ))}
        </div>
      </div>

            {/* Quick Selection Sections */}
            <div className="space-y-6">
              <div>
                <div className="flex justify-between items-center mb-3">
                  <h3 className="font-medium text-gray-900">Target Countries *</h3>
                  <span className="text-sm text-gray-500">{form.target_countries.length} selected</span>
                </div>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-2">
                  {targetCountryOptions.map(country => (
                    <button
                      key={country}
                      type="button"
                      onClick={() => handleMultiSelect('target_countries', country)}
                      className={`px-3 py-2 text-sm rounded-lg transition-all ${form.target_countries.includes(country)
                          ? 'bg-blue-600 text-white'
                          : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                        }`}
                    >
                      {country}
                    </button>
                  ))}
                </div>
                {errors.target_countries && (
                  <p className="mt-1 text-sm text-red-500">{errors.target_countries}</p>
                )}
              </div>

              <div>
                <div className="flex justify-between items-center mb-3">
                  <h3 className="font-medium text-gray-900">Services Offered *</h3>
                  <span className="text-sm text-gray-500">{form.services.length} selected</span>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
                  {serviceOptions.map(service => (
                    <div key={service} className="flex items-center">
                      <input
                        type="checkbox"
                        id={`service-${service}`}
                        checked={form.services.includes(service)}
                        onChange={() => handleMultiSelect('services', service)}
                        className="w-4 h-4 text-blue-600 rounded focus:ring-blue-500"
                      />
                      <label htmlFor={`service-${service}`} className="ml-2 text-gray-700">
                        {service}
                      </label>
                    </div>
                  ))}
                </div>
                {errors.services && (
                  <p className="mt-1 text-sm text-red-500">{errors.services}</p>
                )}
              </div>

              <div>
                <div className="flex justify-between items-center mb-3">
                  <h3 className="font-medium text-gray-900">Specializations *</h3>
                  <span className="text-sm text-gray-500">{form.specialization.length} selected</span>
                </div>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-2">
                  {specializationOptions.map(spec => (
                    <button
                      key={spec}
                      type="button"
                      onClick={() => handleMultiSelect('specialization', spec)}
                      className={`px-3 py-2 text-sm rounded-lg transition-all ${form.specialization.includes(spec)
                          ? 'bg-green-600 text-white'
                          : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                        }`}
                    >
                      {spec}
                    </button>
                  ))}
                </div>
                {errors.specialization && (
                  <p className="mt-1 text-sm text-red-500">{errors.specialization}</p>
                )}
              </div>

              <div>
                <div className="flex justify-between items-center mb-3">
                  <h3 className="font-medium text-gray-900">Languages Spoken *</h3>
                  <span className="text-sm text-gray-500">{form.languages.length} selected</span>
                </div>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-2">
                  {languageOptions.map(language => (
                    <button
                      key={language}
                      type="button"
                      onClick={() => handleMultiSelect('languages', language)}
                      className={`px-3 py-2 text-sm rounded-lg transition-all ${form.languages.includes(language)
                          ? 'bg-purple-600 text-white'
                          : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                        }`}
                    >
                      {language}
                    </button>
                  ))}
                </div>
                {errors.languages && (
                  <p className="mt-1 text-sm text-red-500">{errors.languages}</p>
                )}
              </div>
            </div>

            {/* Terms and Agreement */}
            <div className="bg-blue-50 p-4 rounded-lg">
              <div className="flex items-start">
                <input
                  type="checkbox"
                  id="agree"
                  name="agree"
                  checked={form.agree}
                  onChange={handleChange}
                  className="mt-1 w-4 h-4 text-blue-600"
                />
                <label htmlFor="agree" className="ml-2 text-gray-700">
                  I agree to the Terms and Conditions and Privacy Policy. I understand that my profile will be reviewed before appearing in search results.
                </label>
              </div>
              {errors.agree && <p className="mt-1 text-sm text-red-500">{errors.agree}</p>}
            </div>
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-blue-50 to-gray-50 py-8">
      <div className="max-w-4xl mx-auto px-4">
        {/* Header */}
        <div className="text-center mb-8">
          <h1 className="text-3xl md:text-4xl font-bold text-gray-900 mb-3">
            Join <span className="text-blue-600">UniversitiesPage</span>
          </h1>
          <p className="text-gray-600">Register as a Study Abroad Consultant in 3 simple steps</p>
        </div>

        {/* Progress Steps */}
        <div className="mb-8">
          <div className="flex items-center justify-between mb-4">
            {steps.map((step, index) => (
              <div key={step.number} className="flex items-center flex-1">
                <div className={`flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center font-bold
                  ${currentStep === step.number 
                    ? 'bg-blue-600 text-white' 
                    : currentStep > step.number
                    ? 'bg-green-500 text-white'
                    : 'bg-gray-200 text-gray-400'
                  }`}>
                  {currentStep > step.number ? '✓' : step.number}
                </div>
                <div className="ml-3">
                  <p className={`text-sm font-medium ${currentStep >= step.number ? 'text-gray-900' : 'text-gray-400'}`}>
                    {step.title}
                  </p>
                  <p className="text-xs text-gray-500">{step.description}</p>
                </div>
                {index < steps.length - 1 && (
                  <div className="flex-1 h-1 bg-gray-200 mx-4">
                    <div className={`h-full ${currentStep > step.number ? 'bg-green-500' : 'bg-gray-200'}`}></div>
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Left Side - Benefits & Stats */}
          <div className="lg:col-span-1 space-y-6">
            <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-200">
              <h3 className="font-bold text-gray-900 mb-4">Why Register With Us?</h3>
              <div className="space-y-4">
                {platformFeatures.map((feature, index) => (
                  <div key={index} className="flex items-start gap-3">
                    <div className="p-2 bg-blue-50 rounded-lg">
                      {feature.icon}
                    </div>
                    <div>
                      <h4 className="font-medium text-gray-900">{feature.title}</h4>
                      <p className="text-sm text-gray-600">{feature.desc}</p>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            <div className="bg-gradient-to-r from-blue-600 to-blue-700 rounded-xl p-6 text-white">
              <h3 className="font-bold mb-4">Our Network</h3>
              <div className="grid grid-cols-2 gap-4">
                <div className="text-center">
                  <div className="text-2xl font-bold">500+</div>
                  <div className="text-sm text-blue-100">Consultants</div>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-bold">50K+</div>
                  <div className="text-sm text-blue-100">Students</div>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-bold">95%</div>
                  <div className="text-sm text-blue-100">Success Rate</div>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-bold">100+</div>
                  <div className="text-sm text-blue-100">Universities</div>
                </div>
              </div>
            </div>

            <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-200">
              <h3 className="font-bold text-gray-900 mb-3">Already Registered?</h3>
              <p className="text-gray-600 text-sm mb-4">Sign in to access your dashboard</p>
              <Button
                onClick={() => router.push('/consultant-login')}
                className="w-full py-3 bg-gray-100 text-gray-700 hover:bg-gray-200"
              >
                Sign In Here
              </Button>
            </div>
          </div>

          {/* Right Side - Registration Form */}
          <div className="lg:col-span-2">
            <form onSubmit={handleSubmit} className="bg-white rounded-xl p-6 md:p-8 shadow-sm border border-gray-200">
              {renderStepContent()}

              {/* Navigation Buttons */}
              <div className="flex justify-between mt-8 pt-6 border-t border-gray-200">
                <div>
                  {currentStep > 1 && (
                    <button
                      type="button"
                      onClick={handleBack}
                      className="flex items-center gap-2 px-6 py-3 text-gray-600 hover:text-gray-900"
                    >
                      <FaArrowLeft />
                      Back
                    </button>
                  )}
                </div>
                
                <div>
                  {currentStep < 3 ? (
                    <button
                      type="submit"
                      className="flex items-center gap-2 px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
                    >
                      Continue
                      <FaArrowRight />
                    </button>
                  ) : (
                    <button
                      type="submit"
                      disabled={isSubmitting}
                      className="flex items-center gap-2 px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-70"
                    >
                      {isSubmitting ? (
                        <>
                          <svg className="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                          </svg>
                          Submitting...
                        </>
                      ) : (
                        <>
                          <FaCheckCircle />
                          Submit Application
                        </>
                      )}
                    </button>
                  )}
                </div>
              </div>

              {/* Step Indicator */}
              <div className="text-center mt-6 text-sm text-gray-500">
                Step {currentStep} of 3
              </div>

              {/* Tips */}
              <div className="mt-6 p-4 bg-blue-50 rounded-lg">
                <p className="text-sm text-blue-800">
                  <strong>Need help?</strong> All fields marked with * are required. Your profile will be reviewed within 24-48 hours.
                </p>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
}