'use client';

import React, { useEffect, useState, useRef } from 'react';
import { useRouter } from 'next/navigation';
import Swal from 'sweetalert2';
import { useUserStore } from '../../../../store/useUserStore';
import { 
  FaGlobe, 
  FaBuilding, 
  FaUser, 
  FaPhone, 
  FaEnvelope, 
  FaMapMarkerAlt, 
  FaBriefcase, 
  FaUsers,
  FaGraduationCap,
  FaLanguage,
  FaClock,
  FaLaptop,
  FaStar,
  FaCheckCircle,
  FaEdit,
  FaSpinner,
  FaExclamationTriangle,
  FaTimesCircle,
  FaCamera,
  FaTrash,
  FaUpload,
  FaMoneyBillAlt
} from 'react-icons/fa';

// Components
import Heading from '../../atoms/Heading';
import Button from '../../atoms/Button';
import Input from '../../atoms/Input';
import CountrySelect from '../../atoms/CountrySelect';
import { getCountries, getCities, getStats } from '../../../utils/countryStateCityAPI';

// Add currency options constant
const currencyOptions = [
  { value: 'USD', label: 'US Dollar ($)', symbol: '$' },
  { value: 'EUR', label: 'Euro (€)', symbol: '€' },
  { value: 'GBP', label: 'British Pound (£)', symbol: '£' },
  { value: 'CAD', label: 'Canadian Dollar (CA$)', symbol: 'CA$' },
  { value: 'AUD', label: 'Australian Dollar (AU$)', symbol: 'AU$' },
  { value: 'AED', label: 'UAE Dirham (د.إ)', symbol: 'د.إ' },
  { value: 'SAR', label: 'Saudi Riyal (﷼)', symbol: '﷼' },
  { value: 'PKR', label: 'Pakistani Rupee (₨)', symbol: '₨' },
  { value: 'INR', label: 'Indian Rupee (₹)', symbol: '₹' },
  { value: 'CNY', label: 'Chinese Yuan (¥)', symbol: '¥' },
  { value: 'JPY', label: 'Japanese Yen (¥)', symbol: '¥' },
];

// Currency Selector Component
const CurrencySelector = ({ value, onChange, disabled = false }) => {
  const selectedCurrency = currencyOptions.find(curr => curr.value === value) || currencyOptions[0];

  return (
    <div className="relative">
      <select
        value={value}
        onChange={(e) => onChange(e.target.value)}
        disabled={disabled}
        className={`w-full appearance-none bg-white border-2 border-gray-200 rounded-xl px-4 py-3.5 pl-12 pr-10 text-gray-900 font-medium focus:border-[#0B6F78] focus:ring-2 focus:ring-[#0B6F78]/20 outline-none transition-all ${disabled ? 'cursor-not-allowed opacity-60' : 'cursor-pointer hover:border-gray-300'}`}
      >
        {currencyOptions.map((currency) => (
          <option key={currency.value} value={currency.value}>
            {currency.label}
          </option>
        ))}
      </select>
      
      <div className="absolute left-4 top-1/2 transform -translate-y-1/2 pointer-events-none">
        <div className="flex items-center gap-2">
          <span className="text-sm font-medium text-gray-600">{selectedCurrency.value}</span>
        </div>
      </div>
      
      <svg 
        className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 pointer-events-none w-5 h-5" 
        fill="none" 
        stroke="currentColor" 
        viewBox="0 0 24 24"
      >
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
      </svg>
    </div>
  );
};

const ConsultantProfile = () => {
  const router = useRouter();
  const fileInputRef = useRef(null);
  const { user, fetchUser, updateConsultantProfile } = useUserStore();
  
  // Form state
  const [form, setForm] = useState({
    // Personal Info
    first_name: '',
    last_name: '',
    designation: '',
    email: '',
    phone: '',
    
    // Company Info
    company_name: '',
    number_of_employees: '',
    address: '',
    
    // Location - Store NAMES, not IDs
    nationality: '',
    state: '',
    city: '',
    
    // AI search optimization fields
    consultation_fee: 0,
    consultation_currency: 'USD',
    target_countries: [],
    services: [],
    specialization: [],
    languages: [],
    response_time: 'normal',
    digital_only: false,
    availability: 'normal',
    comment: '',
    
    // SEO Fields (Auto-generated, not shown in form)
    seo_title: '',
    seo_description: '',
    seo_keywords: '',
    seo_slug: '',
    
    // Profile Picture - REQUIRED FIELD
    profile_picture: null,
    
    // Approval Status Fields
    active_profile: '0',
    profile_status: 'incomplete',
    profile_completed_date: null,
    approval_requested_date: null,
    approved_date: null,
    rejection_reason: null,
    completeness_percentage: 0,
    is_eligible_for_approval: false,
    is_approved: false,
    is_pending: false
  });

  // Available options
  const [countries, setCountries] = useState([]);
  const [states, setStates] = useState([]);
  const [cities, setCities] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const [errors, setErrors] = useState({});
  const [completeness, setCompleteness] = useState(0);
  const [selectedFile, setSelectedFile] = useState(null);
  const [previewUrl, setPreviewUrl] = useState(null);

  // Predefined options
  const employeeRanges = ['1-5', '6-10', '11-20', '21-50', '51-100', '100+'];
  const responseTimes = [
    { value: 'urgent', label: 'Urgent (Within 24 hours)' },
    { value: 'fast', label: 'Fast (1-2 days)' },
    { value: 'normal', label: 'Normal (3-5 days)' }
  ];
  const availabilityOptions = [
    { value: 'high', label: 'High (Immediate availability)' },
    { value: 'normal', label: 'Normal (Available within a week)' },
    { value: 'limited', label: 'Limited (By appointment only)' }
  ];
  
  // Multi-select options
  const serviceOptions = [
    'Visa Application',
    'Documentation Support',
    'Interview Preparation',
    'University Admission',
    'Language Test Preparation',
    'Financial Documentation',
    'Accommodation Assistance',
    'Post-Arrival Support',
    'Work Permit Assistance',
    'PR Application'
  ];
  
  const specializationOptions = [
    'Student Visa',
    'Work Visa',
    'Tourist Visa',
    'Family Visa',
    'Business Visa',
    'Permanent Residency',
    'Refugee/Asylum',
    'Investment Visa',
    'Medical Visa',
    'Cultural/Exchange Visa'
  ];
  
  const languageOptions = [
    'English',
    'Urdu',
    'Hindi',
    'Arabic',
    'German',
    'French',
    'Spanish',
    'Chinese',
    'Russian',
    'Turkish',
    'Persian',
    'Bengali'
  ];
  
  const targetCountryOptions = [
    'Germany',
    'Canada',
    'USA',
    'UK',
    'Australia',
    'UAE',
    'Singapore',
    'Japan',
    'New Zealand',
    'Ireland',
    'Netherlands',
    'Sweden',
    'Norway',
    'Denmark',
    'Switzerland',
    'Austria',
    'France',
    'Italy',
    'Spain',
    'Portugal'
  ];

  // Helper functions
  const toOptions = (rows) => {
    if (!Array.isArray(rows)) return [];
    return rows.map(r => ({ 
      label: r.name, 
      value: r.name, // Use NAME as value
      id: r.id
    }));
  };

  const readSelectValue = (eOrValue) => {
    if (eOrValue?.target?.value !== undefined) return eOrValue.target.value;
    return String(eOrValue ?? '');
  };

  // Calculate profile completeness - UPDATED: Profile Picture is required
  const calculateCompleteness = (formData) => {
    let filledFields = 0;
    let totalFields = 0;

    // Required fields with weights
    const requiredFields = [
      // Personal Info (20%)
      { field: 'first_name', weight: 4 },
      { field: 'last_name', weight: 4 },
      { field: 'designation', weight: 4 },
      { field: 'email', weight: 4 },
      { field: 'phone', weight: 4 },
      
      // Company Info (15%)
      { field: 'company_name', weight: 5 },
      { field: 'address', weight: 5 },
      { field: 'number_of_employees', weight: 5 },
      
      // Location (15%)
      { field: 'nationality', weight: 5 },
      { field: 'state', weight: 5 },
      { field: 'city', weight: 5 },
      
      // AI Optimization (30%)
      { field: 'target_countries', weight: 7.5, isArray: true },
      { field: 'services', weight: 7.5, isArray: true },
      { field: 'specialization', weight: 7.5, isArray: true },
      { field: 'languages', weight: 7.5, isArray: true },
      
      // Profile Picture (20%) - REQUIRED FIELD
      { field: 'profile_picture', weight: 20, isRequired: true },
    ];

    requiredFields.forEach(({ field, weight, isArray, isRequired }) => {
      totalFields += weight;
      
      if (isArray) {
        if (formData[field] && Array.isArray(formData[field]) && formData[field].length > 0) {
          filledFields += weight;
        }
      } else {
        if (formData[field] && formData[field].toString().trim() !== '') {
          filledFields += weight;
        }
      }
    });

    // Add bonus for additional fields (10%)
    const bonusFields = [
      'consultation_fee',
      'consultation_currency',
      'response_time',
      'availability',
      'comment'
    ];
    
    const bonusWeight = 2; // 10% total divided by 5 fields
    bonusFields.forEach(field => {
      totalFields += bonusWeight;
      if (formData[field]) {
        if (Array.isArray(formData[field])) {
          if (formData[field].length > 0) filledFields += bonusWeight;
        } else if (typeof formData[field] === 'boolean') {
          filledFields += bonusWeight;
        } else if (formData[field].toString().trim() !== '') {
          filledFields += bonusWeight;
        }
      }
    });

    const percentage = totalFields > 0 ? Math.round((filledFields / totalFields) * 100) : 0;
    return Math.min(100, percentage);
  };

  // Update completeness whenever form changes
  useEffect(() => {
    const calculatedCompleteness = calculateCompleteness(form);
    setCompleteness(calculatedCompleteness);
    
    if (calculatedCompleteness >= 100 && !form.is_eligible_for_approval) {
      setForm(prev => ({ ...prev, is_eligible_for_approval: true }));
    } else if (calculatedCompleteness < 100 && form.is_eligible_for_approval) {
      setForm(prev => ({ ...prev, is_eligible_for_approval: false }));
    }
  }, [form]);

  const getCompletenessBadgeColor = (percentage) => {
    if (percentage >= 90) return 'from-green-500 to-emerald-600';
    if (percentage >= 75) return 'from-blue-500 to-cyan-600';
    if (percentage >= 50) return 'from-yellow-500 to-amber-500';
    return 'from-orange-500 to-red-500';
  };

  const getCompletenessText = (percentage) => {
    if (percentage >= 90) return 'Excellent';
    if (percentage >= 75) return 'Good';
    if (percentage >= 50) return 'Fair';
    return 'Needs Work';
  };

  // Profile Picture handlers
  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) => {
      setPreviewUrl(e.target?.result);
    };
    reader.readAsDataURL(file);
  };

  const handleUploadPicture = async () => {
    if (!selectedFile) return;

    setIsUploading(true);

    try {
      const formData = new FormData();
      formData.append('profile_picture', selectedFile);
      
      if (form.profile_picture) {
        formData.append('delete_old_picture', 'true');
      }

      const response = await fetch('/api/frontend/consultant/consultantdashboard/upload-profile-picture/', {
        method: 'POST',
        body: formData,
      });

      const data = await response.json();

      if (response.ok) {
        setForm(prev => ({
          ...prev,
          profile_picture: data.data.profile_picture
        }));
        
        updateConsultantProfile({
          profile_picture: data.data.profile_picture
        });
        
        setSelectedFile(null);
        if (fileInputRef.current) {
          fileInputRef.current.value = '';
        }
        
        // Clear profile picture error if it exists
        setErrors(prev => {
          const newErrors = { ...prev };
          delete newErrors.profile_picture;
          return newErrors;
        });
        
        Swal.fire({
          icon: 'success',
          title: 'Success!',
          text: 'Profile picture uploaded successfully',
          timer: 2000,
          background: '#0B6F78',
          color: 'white'
        });
      } else {
        Swal.fire({
          icon: 'error',
          title: 'Upload Failed',
          text: data.message || 'Failed to upload profile picture',
          confirmButtonColor: '#0B6F78'
        });
      }
    } catch (error) {
      console.error('Profile picture upload error:', error);
      Swal.fire({
        icon: 'error',
        title: 'Network Error',
        text: 'Please check your connection and try again',
        timer: 3000
      });
    } finally {
      setIsUploading(false);
    }
  };

  const handleCancelUpload = () => {
    setSelectedFile(null);
    setPreviewUrl(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  const handleRemovePicture = async () => {
    // Show warning about profile picture being required
    const result = await Swal.fire({
      title: 'Remove Profile Picture?',
      html: `
        <div class="text-left">
          <p class="mb-3">Are you sure you want to remove your profile picture?</p>
          <div class="bg-yellow-50 p-3 rounded-lg mb-3">
            <p class="font-medium text-yellow-800 mb-1">Important:</p>
            <p class="text-yellow-700 text-sm">
              Profile picture is required for profile submission. 
              You won't be able to submit your profile without a picture.
            </p>
          </div>
        </div>
      `,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#d33',
      cancelButtonColor: '#3085d6',
      confirmButtonText: 'Yes, remove it',
      cancelButtonText: 'Cancel'
    });

    if (result.isConfirmed) {
      setIsUploading(true);

      try {
        const formData = new FormData();
        formData.append('delete_old_picture', 'true');

        const response = await fetch('/api/frontend/consultant/consultantdashboard/upload-profile-picture/', {
          method: 'POST',
          body: formData,
        });

        const data = await response.json();

        if (response.ok) {
          setForm(prev => ({
            ...prev,
            profile_picture: null
          }));
          
          // Add profile picture error since it's now required
          setErrors(prev => ({
            ...prev,
            profile_picture: 'Profile picture is required'
          }));
          
          Swal.fire({
            icon: 'warning',
            title: 'Picture Removed!',
            html: `
              <div class="text-left">
                <p class="mb-3">Profile picture has been removed.</p>
                <div class="bg-red-50 p-3 rounded-lg">
                  <p class="font-medium text-red-800">Note:</p>
                  <p class="text-red-700 text-sm">You must upload a new profile picture to submit your profile.</p>
                </div>
              </div>
            `,
            timer: 3000,
            background: '#0B6F78',
            color: 'white'
          });
        } else {
          Swal.fire({
            icon: 'error',
            title: 'Failed',
            text: data.message || 'Failed to remove profile picture',
            confirmButtonColor: '#0B6F78'
          });
        }
      } catch (error) {
        console.error('Remove picture error:', error);
        Swal.fire({
          icon: 'error',
          title: 'Network Error',
          text: 'Please check your connection and try again',
          timer: 3000
        });
      } finally {
        setIsUploading(false);
      }
    }
  };

  // Dependent selects handlers
  const handleCountryChange = (eOrValue) => {
    const selectedName = readSelectValue(eOrValue);
    setForm(prev => ({
      ...prev,
      nationality: selectedName,
      state: '',
      city: ''
    }));
  };

  const handleStateChange = (eOrValue) => {
    const selectedName = readSelectValue(eOrValue);
    setForm(prev => ({
      ...prev,
      state: selectedName,
      city: ''
    }));
  };

  const handleCityChange = (eOrValue) => {
    const selectedName = readSelectValue(eOrValue);
    setForm(prev => ({ ...prev, city: selectedName }));
  };

  // 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 };
    });
  };

  // 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 }));
    }
  };

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

  // Function to convert ID-based data to name-based
  const convertLocationIdsToNames = (data, countriesList, statesList, citiesList) => {
    if (!data) return data;
    
    const result = { ...data };
    
    // Convert country ID to name
    if (result.nationality && !isNaN(result.nationality)) {
      const countryId = Number(result.nationality);
      const country = countriesList.find(c => c.id === countryId);
      if (country) {
        result.nationality = country.name;
      }
    }
    
    // Convert state ID to name
    if (result.state && !isNaN(result.state)) {
      const stateId = Number(result.state);
      const state = statesList.find(s => s.id === stateId);
      if (state) {
        result.state = state.name;
      }
    }
    
    // Convert city ID to name
    if (result.city && !isNaN(result.city)) {
      const cityId = Number(result.city);
      const city = citiesList.find(c => c.id === cityId);
      if (city) {
        result.city = city.name;
      }
    }
    
    return result;
  };

  // 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 based on country name
  useEffect(() => {
    if (!form.nationality) {
      setStates([]);
      setCities([]);
      return;
    }

    const fetchStates = async () => {
      try {
        // Find country by name
        const country = countries.find(c => c.name === form.nationality);
        
        if (!country) {
          // Try to find by ID if name lookup fails
          const countryId = Number(form.nationality);
          if (!isNaN(countryId)) {
            const countryById = countries.find(c => c.id === countryId);
            if (countryById) {
              // Update form with correct name
              setForm(prev => ({ ...prev, nationality: countryById.name }));
              const res = await getStats(countryById.id);
              setStates(res || []);
              setCities([]);
              return;
            }
          }
          setStates([]);
          setCities([]);
          return;
        }

        const res = await getStats(country.id);
        setStates(res || []);
        setCities([]);
      } catch (err) {
        console.error('Error fetching states:', err);
        setStates([]);
      }
    };
    
    fetchStates();
  }, [form.nationality, countries]);

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

    const fetchCities = async () => {
      try {
        // Find state by name
        const state = states.find(s => s.name === form.state);
        
        if (!state) {
          // Try to find by ID if name lookup fails
          const stateId = Number(form.state);
          if (!isNaN(stateId)) {
            const stateById = states.find(s => s.id === stateId);
            if (stateById) {
              // Update form with correct name
              setForm(prev => ({ ...prev, state: stateById.name }));
              const res = await getCities(stateById.id);
              setCities(res || []);
              return;
            }
          }
          setCities([]);
          return;
        }

        const res = await getCities(state.id);
        setCities(res || []);
      } catch (err) {
        console.error('Error fetching cities:', err);
        setCities([]);
      }
    };
    
    fetchCities();
  }, [form.state, states]);

  // Fetch consultant profile data
  useEffect(() => {
    const fetchProfileData = async () => {
      try {
        setIsLoading(true);
        
        // Fetch countries if needed
        if (countries.length === 0) {
          const countriesRes = await getCountries();
          setCountries(countriesRes || []);
        }

        // Try to get from store first
        if (user?.consultant_profile) {
          const convertedData = convertLocationIdsToNames(
            user.consultant_profile,
            countries,
            states,
            cities
          );

          setForm(prev => ({
            ...prev,
            first_name: convertedData.first_name || prev.first_name,
            last_name: convertedData.last_name || prev.last_name,
            email: user.email || prev.email,
            phone: convertedData.phone || prev.phone,
            designation: convertedData.designation || prev.designation,
            company_name: convertedData.company_name || prev.company_name,
            address: convertedData.address || prev.address,
            number_of_employees: convertedData.number_of_employees || prev.number_of_employees,
            nationality: convertedData.nationality || prev.nationality,
            state: convertedData.state || prev.state,
            city: convertedData.city || prev.city,
            consultation_fee: convertedData.consultation_fee || prev.consultation_fee,
            consultation_currency: convertedData.consultation_currency || 'USD',
            target_countries: convertedData.target_countries || prev.target_countries,
            services: convertedData.services || prev.services,
            specialization: convertedData.specialization || prev.specialization,
            languages: convertedData.languages || prev.languages,
            response_time: convertedData.response_time || prev.response_time,
            digital_only: convertedData.digital_only || prev.digital_only,
            availability: convertedData.availability || prev.availability,
            comment: convertedData.comment || prev.comment,
            seo_title: convertedData.seo_title || prev.seo_title,
            seo_description: convertedData.seo_description || prev.seo_description,
            seo_keywords: convertedData.seo_keywords || prev.seo_keywords,
            seo_slug: convertedData.seo_slug || prev.seo_slug,
            profile_picture: convertedData.profile_picture || prev.profile_picture,
            active_profile: convertedData.active_profile || prev.active_profile,
            profile_status: convertedData.profile_status || prev.profile_status,
            profile_completed_date: convertedData.profile_completed_date || prev.profile_completed_date,
            approval_requested_date: convertedData.approval_requested_date || prev.approval_requested_date,
            approved_date: convertedData.approved_date || prev.approved_date,
            rejection_reason: convertedData.rejection_reason || prev.rejection_reason,
            completeness_percentage: convertedData.completeness_percentage !== undefined 
              ? convertedData.completeness_percentage 
              : prev.completeness_percentage,
            is_eligible_for_approval: convertedData.is_eligible_for_approval !== undefined
              ? convertedData.is_eligible_for_approval
              : prev.is_eligible_for_approval,
            is_approved: convertedData.is_approved !== undefined
              ? convertedData.is_approved
              : prev.is_approved,
            is_pending: convertedData.is_pending !== undefined
              ? convertedData.is_pending
              : prev.is_pending
          }));
        }
        
        // Fetch fresh data from API
        try {
          const response = await fetch('/api/frontend/consultant/consultantdashboard/profile/', {
            method: 'POST'
          });

          if (response.ok) {
            const data = await response.json();
            
            // Parse JSON fields
            const parseJSONField = (value) => {
              if (!value) return [];
              try {
                return JSON.parse(value);
              } catch {
                return Array.isArray(value) ? value : [];
              }
            };

            // Convert location IDs to names
            const convertedData = convertLocationIdsToNames(
              data.data,
              countries,
              states,
              cities
            );

            setForm(prev => ({
              ...prev,
              first_name: convertedData?.first_name || prev.first_name,
              last_name: convertedData?.last_name || prev.last_name,
              designation: convertedData?.designation || prev.designation,
              email: convertedData?.email || prev.email,
              phone: convertedData?.phone || prev.phone,
              company_name: convertedData?.company_name || prev.company_name,
              number_of_employees: convertedData?.number_of_employees || prev.number_of_employees,
              address: convertedData?.address || prev.address,
              nationality: convertedData?.nationality || prev.nationality,
              state: convertedData?.state || prev.state,
              city: convertedData?.city || prev.city,
              consultation_fee: parseFloat(convertedData?.consultation_fee) || prev.consultation_fee,
              consultation_currency: convertedData?.consultation_currency || 'USD',
              target_countries: parseJSONField(convertedData?.target_countries),
              services: parseJSONField(convertedData?.services),
              specialization: parseJSONField(convertedData?.specialization),
              languages: parseJSONField(convertedData?.languages),
              response_time: convertedData?.response_time || prev.response_time,
              digital_only: Boolean(convertedData?.digital_only),
              availability: convertedData?.availability || prev.availability,
              comment: convertedData?.comment || prev.comment,
              seo_title: convertedData?.seo_title || prev.seo_title,
              seo_description: convertedData?.seo_description || prev.seo_description,
              seo_keywords: convertedData?.seo_keywords || prev.seo_keywords,
              seo_slug: convertedData?.seo_slug || prev.seo_slug,
              profile_picture: convertedData?.profile_picture || prev.profile_picture,
              active_profile: convertedData?.active_profile || prev.active_profile,
              profile_status: convertedData?.profile_status || prev.profile_status,
              profile_completed_date: convertedData?.profile_completed_date || prev.profile_completed_date,
              approval_requested_date: convertedData?.approval_requested_date || prev.approval_requested_date,
              approved_date: convertedData?.approved_date || prev.approved_date,
              rejection_reason: convertedData?.rejection_reason || prev.rejection_reason,
              completeness_percentage: convertedData?.completeness_percentage || prev.completeness_percentage,
              is_eligible_for_approval: convertedData?.is_eligible_for_approval !== undefined 
                ? convertedData.is_eligible_for_approval 
                : prev.is_eligible_for_approval,
              is_approved: convertedData?.is_approved !== undefined ? convertedData.is_approved : prev.is_approved,
              is_pending: convertedData?.is_pending !== undefined ? convertedData.is_pending : prev.is_pending
            }));
          }
        } catch (error) {
          console.error('Error fetching profile data from API:', error);
        }
      } catch (error) {
        console.error('Error in fetchProfileData:', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchProfileData();
  }, [user]);

  // Form validation - Profile Picture is required
  const validateForm = () => {
    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';
    if (!form.phone.trim()) newErrors.phone = 'Phone number is required';
    if (!form.company_name.trim()) newErrors.company_name = 'Company name is required';
    if (!form.designation.trim()) newErrors.designation = 'Designation is required';

    // Profile picture validation - REQUIRED
    if (!form.profile_picture) {
      newErrors.profile_picture = 'Profile picture is required';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // Render status badge
  const renderStatusBadge = () => {
    if (form.is_approved) {
      return (
        <div className="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-green-500 to-emerald-600 text-white rounded-full font-medium">
          <FaCheckCircle className="text-lg" />
          <span>Profile Approved ✓</span>
        </div>
      );
    }
    
    if (form.is_pending) {
      return (
        <div className="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-yellow-500 to-amber-500 text-white rounded-full font-medium">
          <FaClock className="text-lg animate-pulse" />
          <span>Pending Approval</span>
        </div>
      );
    }
    
    if (form.is_eligible_for_approval) {
      return (
        <div className="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-blue-500 to-cyan-600 text-white rounded-full font-medium">
          <FaStar className="text-lg" />
          <span>Ready for Approval</span>
        </div>
      );
    }
    
    return (
      <div className="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-orange-500 to-red-500 text-white rounded-full font-medium">
        <FaEdit className="text-lg" />
        <span>Profile Incomplete</span>
      </div>
    );
  };

  // Render approval message
  const renderApprovalMessage = () => {
    if (form.is_approved) {
      return (
        <div className="bg-gradient-to-r from-green-100 to-emerald-100 border-l-4 border-green-500 p-4 rounded-lg mb-6">
          <div className="flex items-center gap-3">
            <FaCheckCircle className="text-green-600 text-xl" />
            <div>
              <h4 className="font-bold text-green-800">Profile Approved!</h4>
              <p className="text-green-700 text-sm">
                Your profile is now live and visible in search results. 
                {form.approved_date && ` Approved on ${new Date(form.approved_date).toLocaleDateString()}.`}
              </p>
            </div>
          </div>
        </div>
      );
    }
    
    if (form.is_pending) {
      return (
        <div className="bg-gradient-to-r from-yellow-100 to-amber-100 border-l-4 border-yellow-500 p-4 rounded-lg mb-6">
          <div className="flex items-center gap-3">
            <FaClock className="text-yellow-600 text-xl animate-pulse" />
            <div>
              <h4 className="font-bold text-yellow-800">Awaiting Approval</h4>
              <p className="text-yellow-700 text-sm">
                Your profile is under review by our team. This usually takes 24-48 hours. 
                {form.approval_requested_date && ` Submitted on ${new Date(form.approval_requested_date).toLocaleDateString()}.`}
              </p>
              <p className="text-yellow-600 text-xs mt-1">
                Note: You cannot make changes while your profile is under review.
              </p>
            </div>
          </div>
        </div>
      );
    }
    
    if (form.is_eligible_for_approval && !form.is_pending && !form.is_approved) {
      return (
        <div className="bg-gradient-to-r from-blue-100 to-cyan-100 border-l-4 border-blue-500 p-4 rounded-lg mb-6">
          <div className="flex items-center gap-3">
            <FaStar className="text-blue-600 text-xl" />
            <div>
              <h4 className="font-bold text-blue-800">Ready for Approval!</h4>
              <p className="text-blue-700 text-sm">
                Your profile is 100% complete! Submit for approval to appear in search results.
                {form.profile_completed_date && ` Completed on ${new Date(form.profile_completed_date).toLocaleDateString()}.`}
              </p>
            </div>
          </div>
        </div>
      );
    }
    
    return null;
  };

  // Render rejection message if applicable
  const renderRejectionMessage = () => {
    if (form.rejection_reason && form.profile_status === 'rejected') {
      return (
        <div className="bg-gradient-to-r from-red-100 to-pink-100 border-l-4 border-red-500 p-4 rounded-lg mb-6">
          <div className="flex items-center gap-3">
            <FaExclamationTriangle className="text-red-600 text-xl" />
            <div>
              <h4 className="font-bold text-red-800">Profile Needs Revision</h4>
              <p className="text-red-700 text-sm mb-2">
                Your profile was not approved. Please review the feedback below and update your profile:
              </p>
              <div className="text-red-600 bg-red-50 p-3 rounded-lg text-sm">
                <p className="font-medium mb-1">Admin Feedback:</p>
                <p className="italic">{form.rejection_reason}</p>
              </div>
              <p className="text-red-600 text-xs mt-2">
                After making the necessary changes, you can resubmit for approval.
              </p>
            </div>
          </div>
        </div>
      );
    }
    
    return null;
  };

  // Check if form is editable based on status
  const isFormEditable = () => {
    if (form.is_pending) {
      return false;
    }
    return true;
  };

  // Handle form submission
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // Check if profile picture is uploaded - REQUIRED FIELD
    if (!form.profile_picture) {
      const result = await Swal.fire({
        title: 'Profile Picture Required',
        html: `
          <div class="text-left">
            <p class="mb-3">You must upload a profile picture before submitting your profile.</p>
            <div class="bg-yellow-50 p-3 rounded-lg mb-3">
              <p class="font-medium text-yellow-800 mb-1">Why is this required?</p>
              <ul class="text-yellow-700 text-sm space-y-1">
                <li>✓ Builds trust with potential clients</li>
                <li>✓ Increases profile credibility</li>
                <li>✓ Required for profile approval</li>
                <li>✓ Makes your profile stand out</li>
                <li>✓ Professional appearance is essential</li>
              </ul>
            </div>
          </div>
        `,
        icon: 'warning',
        confirmButtonText: 'Upload Picture Now',
        confirmButtonColor: '#0B6F78',
        showCancelButton: true,
        cancelButtonText: 'Cancel'
      });
      
      if (result.isConfirmed) {
        // Trigger file input click
        setTimeout(() => {
          fileInputRef.current?.click();
        }, 300);
      }
      return;
    }
    
    if (!validateForm()) {
      Swal.fire({
        icon: 'warning',
        title: 'Validation Error',
        text: 'Please fix all validation errors before submitting.',
        timer: 3000
      });
      return;
    }

    if (!isFormEditable()) {
      Swal.fire({
        icon: 'warning',
        title: 'Cannot Edit',
        text: 'Your profile is currently under review and cannot be edited. Please wait for approval or rejection.',
        timer: 3000
      });
      return;
    }

    let shouldRequestApproval = false;
    if (completeness >= 100 && !form.is_approved && !form.is_pending) {
      const result = await Swal.fire({
        title: 'Submit for Approval?',
        html: `
          <div class="text-left">
            <p class="mb-3">Your profile is 100% complete and SEO optimized!</p>
            <div class="bg-blue-50 p-3 rounded-lg mb-3">
              <p class="font-medium text-blue-800 mb-1">Once approved, you will:</p>
              <ul class="text-blue-700 text-sm space-y-1">
                <li>✓ Appear in AI search results</li>
                <li>✓ Receive client inquiries</li>
                <li>✓ Get verified badge on profile</li>
                <li>✓ Be visible to potential clients</li>
                <li>✓ Appear in search engines with auto-generated SEO</li>
              </ul>
            </div>
            <p class="text-sm text-gray-600">Our team will review your profile within 24-48 hours.</p>
          </div>
        `,
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#0B6F78',
        cancelButtonColor: '#6b7280',
        confirmButtonText: 'Yes, submit for approval',
        cancelButtonText: 'No, just save for now',
        width: 500
      });
      
      if (result.isConfirmed) {
        shouldRequestApproval = true;
      }
    }

    if (form.is_approved && !shouldRequestApproval) {
      const warningResult = await Swal.fire({
        title: 'Profile Update',
        text: 'Your profile is already approved. Changes will require re-approval to appear in search results. Do you want to continue?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#0B6F78',
        cancelButtonColor: '#6b7280',
        confirmButtonText: 'Yes, update profile',
        cancelButtonText: 'Cancel'
      });
      
      if (!warningResult.isConfirmed) {
        return;
      }
    }

    setIsSaving(true);

    try {
      const response = await fetch('/api/frontend/consultant/consultantdashboard/profile/', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          first_name: form.first_name,
          last_name: form.last_name,
          designation: form.designation,
          email: form.email,
          phone: form.phone,
          company_name: form.company_name,
          number_of_employees: form.number_of_employees,
          address: form.address,
          nationality: form.nationality,
          state: form.state,
          city: form.city,
          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 ? 1 : 0,
          availability: form.availability,
          comment: form.comment,
          request_approval: shouldRequestApproval
        }),
      });

      const result = await response.json();

      if (response.ok) {
        const newStatus = result.data?.profile_status || form.profile_status;
        
        const minimalUpdate = {
          profile_status: newStatus,
          is_pending: newStatus === 'pending',
          is_approved: newStatus === 'approved',
          is_eligible_for_approval: newStatus === 'pending' ? false : result.data?.is_eligible_for_approval || false
        };
        
        updateConsultantProfile(minimalUpdate);
        
        // Convert any IDs in API response to names
        const convertedData = convertLocationIdsToNames(
          result.data,
          countries,
          states,
          cities
        );
        
        setForm(prev => ({
          ...prev,
          profile_status: newStatus,
          is_pending: result.data?.is_pending || false,
          is_approved: result.data?.is_approved || false,
          is_eligible_for_approval: result.data?.is_eligible_for_approval || false,
          completeness_percentage: result.data?.completeness_percentage || completeness,
          profile_picture: result.data?.profile_picture || prev.profile_picture,
          seo_title: result.data?.seo_title || prev.seo_title,
          seo_description: result.data?.seo_description || prev.seo_description,
          seo_keywords: result.data?.seo_keywords || prev.seo_keywords,
          seo_slug: result.data?.seo_slug || prev.seo_slug,
          approval_requested_date: shouldRequestApproval || prev.is_approved 
            ? new Date().toISOString() 
            : prev.approval_requested_date
        }));

        let title = 'Success!';
        let message = result.message || 'Profile updated successfully';
        let icon = 'success';
        
        if (shouldRequestApproval) {
          title = 'Submitted for Approval!';
          icon = 'info';
        } else if (form.is_approved) {
          title = 'Profile Updated';
          message = 'Your profile has been updated. Note: These changes will require re-approval to appear in search results.';
        }

        await Swal.fire({
          icon: icon,
          title: title,
          text: message,
          timer: shouldRequestApproval ? 4000 : 3000,
          showConfirmButton: !shouldRequestApproval,
          background: '#0B6F78',
          color: 'white',
          confirmButtonColor: '#ffffff',
          confirmButtonText: 'OK'
        });
        
        await fetchUser();
        
      } else {
        const errorMessage = result.message || 'Failed to update profile';
        
        if (typeof errorMessage === 'object') {
          const errorString = Object.values(errorMessage).join('\n');
          Swal.fire({
            icon: 'error',
            title: 'Update Failed',
            text: errorString,
            confirmButtonColor: '#0B6F78'
          });
        } else {
          Swal.fire({
            icon: 'error',
            title: 'Update Failed',
            text: errorMessage,
            confirmButtonColor: '#0B6F78'
          });
        }
      }
    } catch (error) {
      console.error('Profile update error:', error);
      Swal.fire({
        icon: 'error',
        title: 'Network Error',
        text: 'Please check your connection and try again',
        timer: 3000
      });
    } finally {
      setIsSaving(false);
    }
  };

  // Render loading state
  if (isLoading) {
    return (
      <div className="min-h-screen flex justify-center items-center bg-gradient-to-b from-gray-50 to-white">
        <div className="text-center">
          <div className="animate-spin rounded-full h-16 w-16 border-4 border-[#0B6F78] border-t-transparent mx-auto mb-4"></div>
          <p className="text-gray-600 text-lg">Loading your profile...</p>
          <p className="text-gray-400 text-sm mt-2">Please wait a moment</p>
        </div>
      </div>
    );
  }

  // Build options for selects
  const countryOptions = toOptions(countries);
  const stateOptions = toOptions(states);
  const cityOptions = toOptions(cities);

  // Get current picture URL for display
  const displayPicture = previewUrl || form.profile_picture;

  return (
    <div className="min-h-screen bg-gradient-to-b from-gray-50 to-white py-8">
      <div className="max-w-6xl mx-auto px-4">
        {/* Header Section */}
        <div className="text-center mb-10">
          <div className="flex flex-col md:flex-row items-center justify-center gap-4 mb-4">
            <div className="flex items-center gap-3">
              <div className="relative">
                {displayPicture ? (
                  <div className="relative">
                    <img
                      src={displayPicture}
                      alt="Profile"
                      className="w-24 h-24 rounded-full object-cover border-4 border-white shadow-lg"
                    />
                    <button
                      type="button"
                      onClick={() => fileInputRef.current?.click()}
                      className="absolute bottom-0 right-0 p-2 bg-[#0B6F78] text-white rounded-full hover:bg-[#0a306b] transition-all"
                      disabled={!isFormEditable()}
                    >
                      <FaCamera />
                    </button>
                    <div className="absolute -top-2 -right-2 w-6 h-6 bg-green-500 rounded-full flex items-center justify-center text-white text-xs">
                      ✓
                    </div>
                  </div>
                ) : (
                  <div className="relative">
                    <div className="w-24 h-24 rounded-full bg-gradient-to-r from-[#0B6F78] to-[#0a306b] flex items-center justify-center text-white text-3xl font-bold border-4 border-white shadow-lg">
                      {form.first_name?.[0]?.toUpperCase() || 'C'}
                      {form.last_name?.[0]?.toUpperCase() || 'P'}
                    </div>
                    <button
                      type="button"
                      onClick={() => fileInputRef.current?.click()}
                      className="absolute bottom-0 right-0 p-2 bg-[#0B6F78] text-white rounded-full hover:bg-[#0a306b] transition-all"
                      disabled={!isFormEditable()}
                    >
                      <FaCamera />
                    </button>
                    <div className="absolute -top-2 -right-2 w-6 h-6 bg-red-500 rounded-full flex items-center justify-center text-white text-xs">
                      !
                    </div>
                  </div>
                )}
                <input
                  type="file"
                  ref={fileInputRef}
                  onChange={handleFileSelect}
                  accept="image/jpeg,image/jpg,image/png,image/gif,image/webp"
                  className="hidden"
                  disabled={!isFormEditable()}
                />
              </div>
              <div>
                <Heading level={4} className="text-3xl md:text-4xl font-bold text-gray-900">
                  Consultant Profile
                </Heading>
                <p className="text-gray-600 mt-2">
                  {form.first_name} {form.last_name} • {form.designation}
                </p>
                <div className="mt-2">
                  <p className="text-sm text-gray-600 mb-1">
                    Profile Picture Status: 
                    <span className={`font-medium ml-2 ${form.profile_picture ? 'text-green-600' : 'text-red-600'}`}>
                      {form.profile_picture ? 'Uploaded ✓' : 'Required ⚠️'}
                    </span>
                  </p>
                  <p className="text-xs text-gray-500">
                    A professional photo is required for profile approval
                  </p>
                </div>
              </div>
            </div>
            <div className="ml-0 md:ml-4">
              {renderStatusBadge()}
            </div>
          </div>
          <p className="text-gray-600 text-lg max-w-2xl mx-auto">
            Complete your profile to appear in AI-powered searches and connect with potential clients
          </p>
          <div className="mt-4 flex flex-wrap justify-center gap-2">
            <span className="px-3 py-1 bg-blue-100 text-blue-700 text-sm font-medium rounded-full">
              AI Search Optimized
            </span>
            <span className="px-3 py-1 bg-green-100 text-green-700 text-sm font-medium rounded-full">
              Verified Consultant
            </span>
            <span className={`px-3 py-1 bg-gradient-to-r ${getCompletenessBadgeColor(completeness)} text-white text-sm font-medium rounded-full`}>
              Profile Completeness: {completeness}% ({getCompletenessText(completeness)})
            </span>
            {form.seo_slug && (
              <span className="px-3 py-1 bg-purple-100 text-purple-700 text-sm font-medium rounded-full">
                SEO Auto-Generated
              </span>
            )}
            {!form.profile_picture && (
              <span className="px-3 py-1 bg-red-100 text-red-700 text-sm font-medium rounded-full">
                Picture Required
              </span>
            )}
          </div>
        </div>

        {/* Profile Picture Upload Section */}
        {selectedFile && (
          <div className="mb-6 bg-white rounded-xl p-6 border border-gray-200 shadow-sm">
            <div className="flex flex-col md:flex-row items-center justify-between gap-6">
              <div className="flex items-center gap-4">
                <div className="relative">
                  <img
                    src={previewUrl || ''}
                    alt="Preview"
                    className="w-20 h-20 rounded-full object-cover border-2 border-gray-300"
                  />
                  <div className="absolute -top-2 -right-2 w-6 h-6 bg-blue-500 rounded-full flex items-center justify-center text-white text-xs">
                    NEW
                  </div>
                </div>
                <div>
                  <h3 className="font-bold text-gray-800">New Profile Picture</h3>
                  <p className="text-gray-600 text-sm">
                    {selectedFile.name} • {(selectedFile.size / 1024).toFixed(2)} KB
                  </p>
                  <p className="text-gray-500 text-xs">Click upload to save this picture</p>
                </div>
              </div>
              <div className="flex gap-3">
                <Button
                  type="button"
                  onClick={handleUploadPicture}
                  className="px-6 py-2 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white font-medium rounded-lg hover:opacity-90 transition-all"
                  disabled={isUploading}
                >
                  {isUploading ? (
                    <span className="flex items-center gap-2">
                      <FaSpinner className="animate-spin" />
                      Uploading...
                    </span>
                  ) : (
                    <span className="flex items-center gap-2">
                      <FaUpload />
                      Upload Picture
                    </span>
                  )}
                </Button>
                <Button
                  type="button"
                  onClick={handleCancelUpload}
                  className="px-6 py-2 bg-gray-200 text-gray-700 font-medium rounded-lg hover:bg-gray-300 transition-all"
                >
                  Cancel
                </Button>
              </div>
            </div>
          </div>
        )}

        {/* Approval Status Messages */}
        {renderRejectionMessage()}
        {renderApprovalMessage()}

        {/* Profile Status Info */}
        {form.is_pending && (
          <div className="mb-6 bg-white rounded-xl p-4 border border-yellow-200 shadow-sm">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-yellow-100 rounded-full">
                <FaClock className="text-yellow-600" />
              </div>
              <div className="flex-1">
                <h3 className="font-semibold text-gray-800">Profile Under Review</h3>
                <p className="text-gray-600 text-sm">
                  Your profile is currently being reviewed by our admin team. During this period:
                </p>
                <ul className="mt-2 space-y-1 text-sm text-gray-600">
                  <li className="flex items-center gap-2">
                    <span className="w-2 h-2 bg-yellow-400 rounded-full"></span>
                    You cannot make changes to your profile
                  </li>
                  <li className="flex items-center gap-2">
                    <span className="w-2 h-2 bg-yellow-400 rounded-full"></span>
                    Your profile is not visible in search results
                  </li>
                  <li className="flex items-center gap-2">
                    <span className="w-2 h-2 bg-yellow-400 rounded-full"></span>
                    You will receive an email notification once approved
                  </li>
                </ul>
              </div>
            </div>
          </div>
        )}

        {/* Progress Bar Section */}
        <div className="mb-8 bg-white rounded-xl p-6 border border-gray-200 shadow-sm">
          <div className="flex items-center justify-between mb-3">
            <h3 className="font-semibold text-gray-800">Profile Completion Progress</h3>
            <span className="text-lg font-bold text-[#0B6F78]">{completeness}%</span>
          </div>
          
          {/* Progress Bar */}
          <div className="w-full bg-gray-200 rounded-full h-3 mb-4 overflow-hidden">
            <div 
              className="h-full bg-gradient-to-r from-[#0B6F78] to-[#0a306b] transition-all duration-500"
              style={{ width: `${completeness}%` }}
            />
          </div>
          
          {/* Tips for Completeness */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="text-sm">
              <p className="font-medium text-gray-700 mb-2">To reach 100%, make sure you:</p>
              <ul className="space-y-1 text-gray-600">
                <li className={`flex items-center gap-2 ${form.profile_picture ? 'text-green-600' : 'text-red-500 font-medium'}`}>
                  {form.profile_picture ? <FaCheckCircle /> : <FaTimesCircle />} 
                  {form.profile_picture ? 'Profile picture uploaded' : 'Profile picture REQUIRED'}
                </li>
                <li className={`flex items-center gap-2 ${form.target_countries.length > 0 ? 'text-green-600' : 'text-red-500'}`}>
                  {form.target_countries.length > 0 ? <FaCheckCircle /> : <FaTimesCircle />} 
                  Select at least 1 target country
                </li>
                <li className={`flex items-center gap-2 ${form.services.length > 0 ? 'text-green-600' : 'text-red-500'}`}>
                  {form.services.length > 0 ? <FaCheckCircle /> : <FaTimesCircle />} 
                  Select at least 1 service
                </li>
                <li className={`flex items-center gap-2 ${form.specialization.length > 0 ? 'text-green-600' : 'text-red-500'}`}>
                  {form.specialization.length > 0 ? <FaCheckCircle /> : <FaTimesCircle />} 
                  Select at least 1 specialization
                </li>
                <li className={`flex items-center gap-2 ${form.languages.length > 0 ? 'text-green-600' : 'text-red-500'}`}>
                  {form.languages.length > 0 ? <FaCheckCircle /> : <FaTimesCircle />} 
                  Select at least 1 language
                </li>
                <li className={`flex items-center gap-2 ${form.consultation_fee > 0 ? 'text-green-600' : 'text-red-500'}`}>
                  {form.consultation_fee > 0 ? <FaCheckCircle /> : <FaTimesCircle />} 
                  Set your consultation fee
                </li>
                <li className={`flex items-center gap-2 ${form.seo_slug ? 'text-green-600' : 'text-green-600'}`}>
                  <FaCheckCircle className="text-green-600" /> 
                  SEO will be auto-generated
                </li>
              </ul>
            </div>
            
            <div className="text-sm">
              <p className="font-medium text-gray-700 mb-2">Benefits of Approval:</p>
              <ul className="space-y-1 text-gray-600">
                <li className="flex items-center gap-2">⭐ Appear in AI search results</li>
                <li className="flex items-center gap-2">⭐ Get 3x more client inquiries</li>
                <li className="flex items-center gap-2">⭐ Higher ranking in search</li>
                <li className="flex items-center gap-2">⭐ Verified badge on profile</li>
                <li className="flex items-center gap-2">⭐ Priority support access</li>
                <li className="flex items-center gap-2">⭐ Auto SEO optimized profile pages</li>
              </ul>
            </div>
          </div>
        </div>

        <form onSubmit={handleSubmit} className="space-y-8">
          {/* Personal Information Card */}
          <div className={`bg-white rounded-2xl shadow-xl p-6 border border-gray-200 ${!isFormEditable() ? 'opacity-75' : ''}`}>
            <div className="flex items-center justify-between mb-6">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-blue-100 rounded-lg">
                  <FaUser className="text-blue-600 text-xl" />
                </div>
                <div>
                  <h2 className="text-xl font-bold text-gray-900">Personal Information</h2>
                  <p className="text-gray-500 text-sm">Your personal details for identification</p>
                </div>
              </div>
              {form.profile_picture && !selectedFile && (
                <Button
                  type="button"
                  onClick={handleRemovePicture}
                  className="px-4 py-2 bg-red-100 text-red-600 hover:bg-red-200 rounded-lg flex items-center gap-2"
                  disabled={!isFormEditable()}
                >
                  <FaTrash />
                  Remove Picture
                </Button>
              )}
            </div>

            {errors.profile_picture && (
              <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-xl">
                <div className="flex items-center gap-3">
                  <FaExclamationTriangle className="text-red-500" />
                  <div>
                    <h3 className="font-semibold text-red-700">Profile Picture Required</h3>
                    <p className="text-red-600 text-sm">{errors.profile_picture}</p>
                  </div>
                </div>
              </div>
            )}

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-2">
                <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                  <FaUser className="text-gray-400" />
                  First Name *
                </label>
                <Input
                  name="first_name"
                  value={form.first_name}
                  onChange={handleChange}
                  placeholder="Enter your first name"
                  required
                  error={errors.first_name}
                  icon={<FaUser />}
                  disabled={!isFormEditable()}
                />
              </div>

              <div className="space-y-2">
                <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                  <FaUser className="text-gray-400" />
                  Last Name *
                </label>
                <Input
                  name="last_name"
                  value={form.last_name}
                  onChange={handleChange}
                  placeholder="Enter your last name"
                  required
                  error={errors.last_name}
                  icon={<FaUser />}
                  disabled={!isFormEditable()}
                />
              </div>

              <div className="space-y-2">
                <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                  <FaBriefcase className="text-gray-400" />
                  Designation *
                </label>
                <Input
                  name="designation"
                  value={form.designation}
                  onChange={handleChange}
                  placeholder="e.g., CEO, Immigration Consultant"
                  required
                  error={errors.designation}
                  icon={<FaBriefcase />}
                  disabled={!isFormEditable()}
                />
              </div>

              <div className="space-y-2">
                <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                  <FaEnvelope className="text-gray-400" />
                  Email *
                </label>
                <Input
                  name="email"
                  type="email"
                  value={form.email}
                  onChange={handleChange}
                  placeholder="your.email@example.com"
                  required
                  error={errors.email}
                  icon={<FaEnvelope />}
                  disabled={!isFormEditable()}
                />
              </div>

              <div className="space-y-2">
                <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                  <FaPhone className="text-gray-400" />
                  Phone Number *
                </label>
                <Input
                  name="phone"
                  value={form.phone}
                  onChange={handleChange}
                  placeholder="+92 300 1234567"
                  required
                  error={errors.phone}
                  icon={<FaPhone />}
                  disabled={!isFormEditable()}
                />
              </div>
            </div>
          </div>

          {/* Company Information Card */}
          <div className={`bg-white rounded-2xl shadow-xl p-6 border border-gray-200 ${!isFormEditable() ? 'opacity-75' : ''}`}>
            <div className="flex items-center gap-3 mb-6">
              <div className="p-2 bg-green-100 rounded-lg">
                <FaBuilding className="text-green-600 text-xl" />
              </div>
              <div>
                <h2 className="text-xl font-bold text-gray-900">Company Information</h2>
                <p className="text-gray-500 text-sm">Details about your consulting firm</p>
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-2">
                <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                  <FaBuilding className="text-gray-400" />
                  Company Name *
                </label>
                <Input
                  name="company_name"
                  value={form.company_name}
                  onChange={handleChange}
                  placeholder="Enter company name"
                  required
                  error={errors.company_name}
                  icon={<FaBuilding />}
                  disabled={!isFormEditable()}
                />
              </div>

              <div className="space-y-2">
                <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                  <FaUsers className="text-gray-400" />
                  Number of Employees
                </label>
                <div className="relative">
                  <select
                    name="number_of_employees"
                    value={form.number_of_employees}
                    onChange={handleChange}
                    className={`w-full px-4 py-3 pl-12 bg-gray-50 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-gray-700 ${!isFormEditable() ? 'cursor-not-allowed opacity-60' : ''}`}
                    disabled={!isFormEditable()}
                  >
                    <option value="">Select employee range</option>
                    {employeeRanges.map(range => (
                      <option key={range} value={range}>{range} employees</option>
                    ))}
                  </select>
                  <FaUsers className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" />
                </div>
              </div>

              <div className="md:col-span-2 space-y-2">
                <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                  <FaMapMarkerAlt className="text-gray-400" />
                  Company Address
                </label>
                <textarea
                  name="address"
                  value={form.address}
                  onChange={handleChange}
                  placeholder="Enter complete company address"
                  rows={3}
                  className={`w-full px-4 py-3 bg-gray-50 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-gray-700 resize-none ${!isFormEditable() ? 'cursor-not-allowed opacity-60' : ''}`}
                  disabled={!isFormEditable()}
                />
              </div>
            </div>
          </div>

          {/* Location Information Card */}
          <div className={`bg-white rounded-2xl shadow-xl p-6 border border-gray-200 ${!isFormEditable() ? 'opacity-75' : ''}`}>
            <div className="flex items-center gap-3 mb-6">
              <div className="p-2 bg-purple-100 rounded-lg">
                <FaGlobe className="text-purple-600 text-xl" />
              </div>
              <div>
                <h2 className="text-xl font-bold text-gray-900">Location Information</h2>
                <p className="text-gray-500 text-sm">Where you're based and operate from</p>
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              <div className="space-y-2">
                <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                  <FaGlobe className="text-gray-400" />
                  Country
                </label>
                <CountrySelect
                  name="nationality"
                  icon={<FaGlobe />}
                  placeholder="Select Country"
                  value={form.nationality}
                  onChange={handleCountryChange}
                  options={countryOptions}
                  error={errors.nationality}
                  disabled={!isFormEditable()}
                />
              </div>

              <div className="space-y-2">
                <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                  <FaGlobe className="text-gray-400" />
                  State/Province
                </label>
                <CountrySelect
                  name="state"
                  icon={<FaGlobe />}
                  placeholder={form.nationality ? "Select State" : "Select Country first"}
                  value={form.state}
                  onChange={handleStateChange}
                  options={stateOptions}
                  disabled={!form.nationality || !isFormEditable()}
                />
              </div>

              <div className="space-y-2">
                <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                  <FaGlobe className="text-gray-400" />
                  City
                </label>
                <CountrySelect
                  name="city"
                  icon={<FaGlobe />}
                  placeholder={form.state ? "Select City" : "Select State first"}
                  value={form.city}
                  onChange={handleCityChange}
                  options={cityOptions}
                  disabled={!form.state || !isFormEditable()}
                />
              </div>
            </div>
          </div>

          {/* AI Optimization Card */}
          <div className={`bg-white rounded-2xl shadow-xl p-6 border border-gray-200 ${!isFormEditable() ? 'opacity-75' : ''}`}>
            <div className="flex items-center justify-between mb-6">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] rounded-lg">
                  <FaStar className="text-white text-xl" />
                </div>
                <div>
                  <h2 className="text-xl font-bold text-gray-900">AI Search Optimization</h2>
                  <p className="text-gray-500 text-sm">Improve your visibility in AI-powered searches</p>
                </div>
              </div>
              <div className="px-3 py-1 bg-gradient-to-r from-green-100 to-emerald-100 text-green-800 text-sm font-medium rounded-full">
                Auto SEO Included
              </div>
            </div>

            <div className="space-y-8">
              {/* Consultation Fee with Currency */}
              <div className="space-y-2">
                <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                  <FaMoneyBillAlt className="text-gray-400" />
                  Consultation Fee
                </label>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <div className="relative group">
                      <div className="flex items-center">
                        <span className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400">
                          <FaMoneyBillAlt />
                        </span>
                        <input
                          name="consultation_fee"
                          type="number"
                          value={form.consultation_fee}
                          onChange={handleChange}
                          placeholder="0.00"
                          min="0"
                          step="0.01"
                          disabled={!isFormEditable()}
                          className={`w-full pl-12 pr-4 py-3 bg-gray-50 border-2 border-gray-200 rounded-xl focus:outline-none focus:border-[#0B6F78] focus:ring-2 focus:ring-[#0B6F78]/20 transition-all ${!isFormEditable() ? 'cursor-not-allowed opacity-60' : 'hover:border-gray-300'}`}
                        />
                      </div>
                    </div>
                    <p className="text-xs text-gray-500">Enter your standard consultation fee</p>
                  </div>
                  
                  <div className="space-y-2">
                    <CurrencySelector
                      value={form.consultation_currency}
                      onChange={handleCurrencyChange}
                      disabled={!isFormEditable()}
                    />
                    <p className="text-xs text-gray-500">Select your preferred currency</p>
                  </div>
                </div>
                
                {/* Fee Preview */}
                {form.consultation_fee > 0 && (
                  <div className="mt-4 p-4 bg-gradient-to-r from-emerald-50 to-green-50 rounded-xl border border-emerald-200">
                    <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
                      <div>
                        <h4 className="font-semibold text-gray-800 mb-1">Fee Preview</h4>
                        <p className="text-sm text-gray-600">
                          This is how clients will see your consultation fee
                        </p>
                      </div>
                      <div className="text-right">
                        <div className="text-2xl font-bold text-gray-900">
                          {parseFloat(form.consultation_fee).toLocaleString('en-US', {
                            minimumFractionDigits: 2,
                            maximumFractionDigits: 2
                          })}
                          {currencyOptions.find(c => c.value === form.consultation_currency)?.value || '$'}                          
                        </div>
                        <div className="text-sm text-gray-500 mt-1">
                          {currencyOptions.find(c => c.value === form.consultation_currency)?.label?.split('(')[0]?.trim()} 
                          ({form.consultation_currency})
                        </div>
                      </div>
                    </div>
                    
                  </div>
                )}
              </div>

              {/* Target Countries */}
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                    <FaGlobe className="text-gray-400" />
                    Target Countries
                  </label>
                  <span className={`text-xs font-medium px-2 py-1 rounded-full ${form.target_countries.length > 0 ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-600'}`}>
                    {form.target_countries.length} selected
                  </span>
                </div>
                <p className="text-gray-500 text-sm mb-3">Select countries you specialize in</p>
                <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-2">
                  {targetCountryOptions.map(country => (
                    <button
                      key={country}
                      type="button"
                      onClick={() => isFormEditable() && handleMultiSelect('target_countries', country)}
                      className={`px-3 py-2 rounded-lg text-sm font-medium transition-all ${form.target_countries.includes(country)
                          ? 'bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white shadow-md'
                          : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                        } ${!isFormEditable() ? 'cursor-not-allowed opacity-60' : 'cursor-pointer'}`}
                      disabled={!isFormEditable()}
                    >
                      {country}
                    </button>
                  ))}
                </div>
              </div>

              {/* Services Offered */}
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                    <FaCheckCircle className="text-gray-400" />
                    Services Offered
                  </label>
                  <span className={`text-xs font-medium px-2 py-1 rounded-full ${form.services.length > 0 ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-600'}`}>
                    {form.services.length} selected
                  </span>
                </div>
                <p className="text-gray-500 text-sm mb-3">Select services you provide</p>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
                  {serviceOptions.map(service => (
                    <div key={service} className="flex items-center gap-3">
                      <input
                        type="checkbox"
                        id={`service-${service}`}
                        checked={form.services.includes(service)}
                        onChange={() => isFormEditable() && handleMultiSelect('services', service)}
                        className={`w-4 h-4 text-[#0B6F78] rounded focus:ring-[#0B6F78] ${!isFormEditable() ? 'cursor-not-allowed opacity-60' : 'cursor-pointer'}`}
                        disabled={!isFormEditable()}
                      />
                      <label htmlFor={`service-${service}`} className={`text-gray-700 ${!isFormEditable() ? 'opacity-60' : ''}`}>
                        {service}
                      </label>
                    </div>
                  ))}
                </div>
              </div>

              {/* Specializations */}
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                    <FaGraduationCap className="text-gray-400" />
                    Specializations
                  </label>
                  <span className={`text-xs font-medium px-2 py-1 rounded-full ${form.specialization.length > 0 ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-600'}`}>
                    {form.specialization.length} selected
                  </span>
                </div>
                <p className="text-gray-500 text-sm mb-3">Select your visa specializations</p>
                <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-2">
                  {specializationOptions.map(spec => (
                    <button
                      key={spec}
                      type="button"
                      onClick={() => isFormEditable() && handleMultiSelect('specialization', spec)}
                      className={`px-3 py-2 rounded-lg text-sm font-medium transition-all ${form.specialization.includes(spec)
                          ? 'bg-gradient-to-r from-blue-500 to-blue-600 text-white shadow-md'
                          : 'bg-blue-50 text-blue-700 hover:bg-blue-100'
                        } ${!isFormEditable() ? 'cursor-not-allowed opacity-60' : 'cursor-pointer'}`}
                      disabled={!isFormEditable()}
                    >
                      {spec}
                    </button>
                  ))}
                </div>
              </div>

              {/* Languages */}
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                    <FaLanguage className="text-gray-400" />
                    Languages Spoken
                  </label>
                  <span className={`text-xs font-medium px-2 py-1 rounded-full ${form.languages.length > 0 ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-600'}`}>
                    {form.languages.length} selected
                  </span>
                </div>
                <p className="text-gray-500 text-sm mb-3">Select languages you're fluent in</p>
                <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-2">
                  {languageOptions.map(language => (
                    <button
                      key={language}
                      type="button"
                      onClick={() => isFormEditable() && handleMultiSelect('languages', language)}
                      className={`px-3 py-2 rounded-lg text-sm font-medium transition-all ${form.languages.includes(language)
                          ? 'bg-gradient-to-r from-green-500 to-emerald-600 text-white shadow-md'
                          : 'bg-green-50 text-green-700 hover:bg-green-100'
                        } ${!isFormEditable() ? 'cursor-not-allowed opacity-60' : 'cursor-pointer'}`}
                      disabled={!isFormEditable()}
                    >
                      {language}
                    </button>
                  ))}
                </div>
              </div>

              {/* Response Settings */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div className="space-y-2">
                  <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                    <FaClock className="text-gray-400" />
                    Response Time
                  </label>
                  <select
                    name="response_time"
                    value={form.response_time}
                    onChange={handleChange}
                    className={`w-full px-4 py-3 bg-gray-50 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-gray-700 ${!isFormEditable() ? 'cursor-not-allowed opacity-60' : ''}`}
                    disabled={!isFormEditable()}
                  >
                    {responseTimes.map(option => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </div>

                <div className="space-y-2">
                  <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                    <FaLaptop className="text-gray-400" />
                    Consultation Type
                  </label>
                  <div className={`flex items-center gap-3 p-4 rounded-xl ${!isFormEditable() ? 'bg-gray-50 opacity-60' : 'bg-gray-50'}`}>
                    <input
                      type="checkbox"
                      id="digital_only"
                      name="digital_only"
                      checked={form.digital_only}
                      onChange={handleChange}
                      className={`w-5 h-5 text-[#0B6F78] rounded focus:ring-[#0B6F78] ${!isFormEditable() ? 'cursor-not-allowed' : 'cursor-pointer'}`}
                      disabled={!isFormEditable()}
                    />
                    <label htmlFor="digital_only" className={`text-gray-700 ${!isFormEditable() ? 'opacity-60' : ''}`}>
                      Offer Digital/Online Consultations Only
                    </label>
                  </div>
                </div>

                <div className="space-y-2">
                  <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                    <FaClock className="text-gray-400" />
                    Availability
                  </label>
                  <select
                    name="availability"
                    value={form.availability}
                    onChange={handleChange}
                    className={`w-full px-4 py-3 bg-gray-50 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-gray-700 ${!isFormEditable() ? 'cursor-not-allowed opacity-60' : ''}`}
                    disabled={!isFormEditable()}
                  >
                    {availabilityOptions.map(option => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              {/* Additional Comments */}
              <div className="space-y-2">
                <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                  <FaEdit className="text-gray-400" />
                  Additional Information
                </label>
                <textarea
                  name="comment"
                  value={form.comment}
                  onChange={handleChange}
                  placeholder="Add any additional information about your services, experience, or specializations..."
                  rows={4}
                  className={`w-full px-4 py-3 bg-gray-50 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-gray-700 resize-none ${!isFormEditable() ? 'cursor-not-allowed opacity-60' : ''}`}
                  disabled={!isFormEditable()}
                />
              </div>
            </div>
          </div>

          {/* Submit Section */}
          <div className="bg-gradient-to-r from-[#0B6F78] to-[#0a306b] rounded-2xl p-6 text-center">
            <div className="max-w-2xl mx-auto">
              <h3 className="text-xl font-bold text-white mb-3">
                {form.is_pending ? 'Profile Under Review' : 
                 form.is_approved ? 'Update Your Profile' : 
                 'Complete Your Profile'}
              </h3>
              
              {form.is_pending ? (
                <div className="mb-6">
                  <p className="text-blue-100 mb-4">
                    Your profile is currently under review by our admin team. You cannot make changes at this time.
                  </p>
                  <div className="inline-flex items-center gap-2 px-4 py-2 bg-yellow-500 bg-opacity-20 rounded-full">
                    <FaClock className="text-yellow-300 animate-pulse" />
                    <span className="text-yellow-100">Estimated review time: 24-48 hours</span>
                  </div>
                </div>
              ) : form.is_approved ? (
                <p className="text-blue-100 mb-6">
                  Update your profile information. Note: Changes will require re-approval to appear in search results.
                </p>
              ) : (
                <p className="text-blue-100 mb-6">
                  {completeness >= 100
                    ? 'Your profile is 100% complete! Submit for approval to appear in search results.'
                    : 'Complete profiles receive 3x more inquiries and appear higher in AI search results'}
                </p>
              )}
              
              <div className="flex flex-col sm:flex-row gap-4 justify-center">
                {form.is_pending ? (
                  <Button
                    type="button"
                    className="px-8 py-3 bg-white/10 text-white font-bold rounded-xl cursor-not-allowed opacity-70"
                    disabled
                  >
                    <span className="flex items-center gap-2">
                      <FaClock className="animate-pulse" />
                      Under Review - Cannot Edit
                    </span>
                  </Button>
                ) : (
                  <>
                    <Button
                      type="submit"
                      className={`px-8 py-3 font-bold rounded-xl transition-all shadow-lg ${form.profile_picture ? 'bg-white text-[#0B6F78] hover:bg-gray-100' : 'bg-gray-300 text-gray-500 cursor-not-allowed'}`}
                      disabled={isSaving || !form.profile_picture}
                    >
                      {!form.profile_picture ? (
                        <span className="flex items-center gap-2">
                          <FaExclamationTriangle />
                          Upload Profile Picture First
                        </span>
                      ) : isSaving ? (
                        <span className="flex items-center gap-2">
                          <FaSpinner className="animate-spin" />
                          {completeness >= 100 && !form.is_approved ? 'Submitting...' : 'Saving Changes...'}
                        </span>
                      ) : (
                        <span className="flex items-center gap-2">
                          <FaCheckCircle />
                          {completeness >= 100 && !form.is_approved ? 'Submit for Approval' : 
                           form.is_approved ? 'Update Profile' : 'Save All Changes'}
                        </span>
                      )}
                    </Button>
                    
                    <Button
                      type="button"
                      onClick={() => router.back()}
                      className="px-8 py-3 bg-transparent border-2 border-white text-white font-bold rounded-xl hover:bg-white/10 transition-all"
                    >
                      Cancel
                    </Button>
                  </>
                )}
              </div>
              
              {!form.is_pending && !form.profile_picture && (
                <div className="mt-4">
                  <p className="text-yellow-300 text-sm font-medium mb-2">
                    ⚠️ Profile picture is required for submission
                  </p>
                  <p className="text-blue-100 text-xs">
                    Click the camera icon above to upload a professional photo
                  </p>
                </div>
              )}
              
              {!form.is_pending && form.profile_picture && (
                <div className="mt-4">
                  <p className="text-blue-100 text-sm">
                    Note: {form.is_approved 
                      ? 'Approval changes will take effect after admin review.' 
                      : 'It may take a few minutes for changes to reflect in search results.'}
                  </p>
                  <p className="text-green-300 text-xs mt-2">
                    ✓ SEO will be auto-generated based on your profile information
                  </p>
                </div>
              )}
            </div>
          </div>
        </form>
      </div>
    </div>
  );
};

export default ConsultantProfile;