// app/foreign-student-register/foreign-student-register.jsx
'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Heading from '../../../components/atoms/Heading';
import Input from '../../../components/atoms/Input';
import Button from '../../../components/atoms/Button';
import TextArea from '../../../components/atoms/TextArea';
import CountrySelect from '../../../components/atoms/CountrySelect';
import { getCountries } from '../../../utils/countryStateCityAPI';
import Swal from 'sweetalert2';
import { 
  FaGlobe, 
  FaUserGraduate, 
  FaDollarSign, 
  FaImage,
  FaEye,
  FaEyeSlash,
  FaCheck,
  FaClock,
  FaCalendar,
  FaGraduationCap,
  FaLaptop,
  FaStar,
  FaUsers,
  FaMapMarkerAlt,
  FaPhone,
  FaEnvelope,
  FaLock,
  FaExclamationCircle
} from 'react-icons/fa';

export default function ForeignStudentRegister() {
  const router = useRouter();
  const [form, setForm] = useState({
    name: '',
    email: '',
    password: '',
    confirm_password: '',
    phone: '',
    country_id: '',
    about_me: '',
    profile_picture: '',
    hour_rate: '',
    gender: '',
    experience: '',
    last_education: '',
    terms_accepted: false,
  });

  const [errors, setErrors] = useState({});
  const [countries, setCountries] = useState([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const [uploadedImage, setUploadedImage] = useState(null);
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  // Image upload function
  const uploadImage = async (file) => {
    try {
      const formData = new FormData();
      formData.append('image', file);
      formData.append('uploadType', 'student-profile');

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

      if (!response.ok) {
        throw new Error('Failed to upload image');
      }

      const data = await response.json();
      return data.s3Key || data.url;
    } catch (error) {
      console.error('Error uploading image:', error);
      throw error;
    }
  };

  const handleFileUpload = async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    // Validate file type
    const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    if (!validTypes.includes(file.type)) {
      Swal.fire({
        icon: 'error',
        title: 'Invalid File Type',
        text: 'Please upload a JPG, PNG, GIF, or WebP image',
        confirmButtonColor: '#0B6D76'
      });
      return;
    }

    // Validate file size (max 5MB)
    if (file.size > 5 * 1024 * 1024) {
      Swal.fire({
        icon: 'error',
        title: 'File Too Large',
        text: 'Please upload an image smaller than 5MB',
        confirmButtonColor: '#0B6D76'
      });
      return;
    }

    try {
      setIsUploading(true);
      const imageUrl = await uploadImage(file);
      
      setUploadedImage({
        file,
        preview: URL.createObjectURL(file),
        url: imageUrl
      });
      
      setForm(prev => ({
        ...prev,
        profile_picture: imageUrl
      }));
      
      if (errors.profile_picture) {
        setErrors(prev => ({ ...prev, profile_picture: null }));
      }
    } catch (error) {
      Swal.fire({
        icon: 'error',
        title: 'Upload Error',
        text: error.message || 'Failed to upload image',
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setIsUploading(false);
    }
  };

  const removeImage = () => {
    if (uploadedImage?.preview) {
      URL.revokeObjectURL(uploadedImage.preview);
    }
    setUploadedImage(null);
    setForm(prev => ({ ...prev, profile_picture: '' }));
    if (errors.profile_picture) {
      setErrors(prev => ({ ...prev, profile_picture: 'Profile picture is required' }));
    }
  };

  // Password visibility toggles
  const togglePasswordVisibility = () => setShowPassword(!showPassword);
  const toggleConfirmPasswordVisibility = () => setShowConfirmPassword(!showConfirmPassword);

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

  // Cleanup object URLs
  useEffect(() => {
    return () => {
      if (uploadedImage?.preview) {
        URL.revokeObjectURL(uploadedImage.preview);
      }
    };
  }, [uploadedImage]);

  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    setForm(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));
    
    // Clear error for this field
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: null }));
    }
    
    // Special handling for password match
    if (name === 'password' || name === 'confirm_password') {
      if (errors.confirm_password && name === 'confirm_password' && value === form.password) {
        setErrors(prev => ({ ...prev, confirm_password: null }));
      }
    }
    
    // Special handling for image upload
    if (name === 'profile_picture') {
      if (errors.profile_picture && value) {
        setErrors(prev => ({ ...prev, profile_picture: null }));
      }
    }
  };

  const handleCountryChange = (value) => {
    const countryId = value?.target?.value || value || '';
    setForm(prev => ({
      ...prev,
      country_id: countryId
    }));
    
    if (errors.country_id) {
      setErrors(prev => ({ ...prev, country_id: null }));
    }
  };

  const validateForm = () => {
    const newErrors = {};
    
    // Required fields validation
    if (!form.name.trim()) newErrors.name = 'Full name is required';
    if (!form.email.trim()) newErrors.email = 'Email is required';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) newErrors.email = 'Invalid email format';
    
    if (!form.password) newErrors.password = 'Password is required';
    if (!form.confirm_password) newErrors.confirm_password = 'Please confirm your password';
    else if (form.password !== form.confirm_password) newErrors.confirm_password = 'Passwords do not match';
    
    if (!form.phone.trim()) newErrors.phone = 'Phone number is required';
    else if (!/^[\+]?[1-9][\d]{0,15}$/.test(form.phone)) newErrors.phone = 'Invalid phone number format';
    
    if (!form.country_id) newErrors.country_id = 'Country is required';
    if (!form.profile_picture) newErrors.profile_picture = 'Profile picture is required';
    if (!form.hour_rate) newErrors.hour_rate = 'Hourly rate is required';
    else if (parseFloat(form.hour_rate) <= 0) newErrors.hour_rate = 'Hourly rate must be greater than 0';
    
    if (!form.gender) newErrors.gender = 'Gender is required';
    if (!form.last_education) newErrors.last_education = 'Education level is required';
    if (!form.about_me.trim()) newErrors.about_me = 'About yourself is required';
    if (!form.experience.trim()) newErrors.experience = 'Experience is required';
    if (!form.terms_accepted) newErrors.terms_accepted = 'You must accept the terms and conditions';
    
    return newErrors;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // Client-side validation
    const validationErrors = validateForm();
    if (Object.keys(validationErrors).length > 0) {
      setErrors(validationErrors);
      
      // Scroll to first error
      const firstErrorField = Object.keys(validationErrors)[0];
      const element = document.querySelector(`[name="${firstErrorField}"]`);
      if (element) {
        element.scrollIntoView({ behavior: 'smooth', block: 'center' });
        element.focus();
      }
      
      Swal.fire({
        icon: 'error',
        title: 'Missing Required Fields',
        html: `
          <div class="text-left">
            <p class="mb-2">Please fill in all required fields:</p>
            <ul class="list-disc pl-4 text-sm">
              ${Object.values(validationErrors).slice(0, 3).map(error => `<li>${error}</li>`).join('')}
              ${Object.keys(validationErrors).length > 3 ? `<li>... and ${Object.keys(validationErrors).length - 3} more</li>` : ''}
            </ul>
          </div>
        `,
        confirmButtonColor: '#0B6D76'
      });
      return;
    }
    
    setErrors({});
    setIsSubmitting(true);

    try {
      const response = await fetch('/api/frontend/register-foreign-student', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...form,
          hour_rate: parseFloat(form.hour_rate),
          country_id: parseInt(form.country_id)
        }),
      });

      const data = await response.json();

      if (response.ok && data.success) {
        Swal.fire({
          icon: 'success',
          title: '🎉 Registration Successful!',
          html: `
            <div class="text-center">
              <p>Your account has been created successfully!</p>
              <p class="mt-2 text-sm text-gray-600">You need to wait for account activation. Once your account is activated, you can login.</p>
            </div>
          `,
          confirmButtonColor: '#0B6D76',
          showConfirmButton: true
        }).then(() => {
          router.push('/foreign-students/login');
        });
      } else {
        // Handle validation errors
        if (data.errors) {
          setErrors(data.errors);
          
          const errorMessages = Object.values(data.errors).join('\n');
          Swal.fire({
            icon: 'error',
            title: 'Validation Error',
            html: `
              <div class="text-left">
                <p>Please fix the following errors:</p>
                <ul class="list-disc pl-4 mt-2 text-sm">
                  ${Object.values(data.errors).map(error => `<li>${error}</li>`).join('')}
                </ul>
              </div>
            `,
            confirmButtonColor: '#0B6D76'
          });
        } else {
          Swal.fire({
            icon: 'error',
            title: 'Registration Failed',
            text: data.message || 'Something went wrong. Please try again.',
            confirmButtonColor: '#0B6D76'
          });
        }
      }
    } catch (err) {
      console.error('Registration error:', err);
      Swal.fire({
        icon: 'error',
        title: 'Network Error',
        text: 'Please check your connection and try again.',
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const countryOptions = countries.map(country => ({
    label: country.name,
    value: String(country.id)
  }));

  const educationOptions = [
    { value: 'high_school', label: 'High School' },
    { value: 'bachelors', label: 'Bachelor\'s Degree' },
    { value: 'masters', label: 'Master\'s Degree' },
    { value: 'phd', label: 'PhD' },
    { value: 'diploma', label: 'Diploma' },
    { value: 'certificate', label: 'Certificate' }
  ];

  // Helper function to render error message
  const renderErrorMessage = (fieldName) => {
    if (errors[fieldName]) {
      return (
        <div className="flex items-center gap-1 text-red-500 text-sm mt-1">
          <FaExclamationCircle className="w-3 h-3" />
          <span>{errors[fieldName]}</span>
        </div>
      );
    }
    return null;
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-gray-50 to-white py-12 px-4">
      <div className="max-w-7xl mx-auto">
        {/* Header Section */}
        <div className="text-center mb-12">
          <h1 className="text-4xl md:text-5xl font-bold text-gray-900 mb-4">
            Work as a <span className="text-teal-600">Freelance Foreign Student Guide</span>
          </h1>
          <p className="text-xl text-gray-600 max-w-3xl mx-auto">
            Turn your international study experience into income by guiding aspiring students
          </p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
          {/* Left Column - Content */}
          <div className="space-y-8">
            {/* Hero Message */}
            <div className="bg-gradient-to-r from-teal-50 to-blue-50 rounded-2xl p-8 border border-teal-100">
              <h2 className="text-2xl font-bold text-gray-900 mb-4">
                Are you currently studying or living abroad?
              </h2>
              <p className="text-gray-700 mb-4">
                Universities Page invites foreign students to join our global platform as freelance student guides 
                and earn money by helping aspiring students plan their study abroad journey.
              </p>
              <p className="text-gray-700">
                Your real-life experience is valuable. Students trust guidance from someone who has already been 
                through the process — admissions, visas, accommodation, and student life.
              </p>
            </div>

            {/* What You'll Do Section */}
            <div className="bg-white rounded-2xl shadow-lg p-8 border border-gray-200">
              <h3 className="text-2xl font-bold text-gray-900 mb-6 flex items-center">
                <FaGraduationCap className="mr-3 text-teal-600" />
                What You'll Do as a Foreign Student Guide
              </h3>
              <div className="space-y-4">
                <div className="flex items-start space-x-3">
                  <div className="w-8 h-8 bg-teal-100 rounded-full flex items-center justify-center flex-shrink-0">
                    <FaCheck className="text-teal-600" />
                  </div>
                  <p className="text-gray-700">
                    <span className="font-semibold">Guide students</span> about universities, programs, and admission processes
                  </p>
                </div>
                <div className="flex items-start space-x-3">
                  <div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0">
                    <FaGlobe className="text-blue-600" />
                  </div>
                  <p className="text-gray-700">
                    <span className="font-semibold">Share real insights</span> about student life, part-time work, and living costs
                  </p>
                </div>
                <div className="flex items-start space-x-3">
                  <div className="w-8 h-8 bg-purple-100 rounded-full flex items-center justify-center flex-shrink-0">
                    <FaPhone className="text-purple-600" />
                  </div>
                  <p className="text-gray-700">
                    <span className="font-semibold">Support students</span> through online calls, chats, or consultations
                  </p>
                </div>
                <div className="flex items-start space-x-3">
                  <div className="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center flex-shrink-0">
                    <FaUsers className="text-green-600" />
                  </div>
                  <p className="text-gray-700">
                    <span className="font-semibold">Act as a trusted mentor</span>, not a sales agent
                  </p>
                </div>
              </div>
            </div>

            {/* Why Join Section */}
            <div className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-2xl p-8 border border-blue-100">
              <h3 className="text-2xl font-bold text-gray-900 mb-6 flex items-center">
                <FaStar className="mr-3 text-blue-600" />
                Why Join Universities Page?
              </h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="flex items-center space-x-3">
                  <FaDollarSign className="text-green-600 flex-shrink-0" />
                  <span className="text-gray-700">Earn per consultation or referral</span>
                </div>
                <div className="flex items-center space-x-3">
                  <FaLaptop className="text-blue-600 flex-shrink-0" />
                  <span className="text-gray-700">Work remotely from anywhere</span>
                </div>
                <div className="flex items-center space-x-3">
                  <FaCalendar className="text-purple-600 flex-shrink-0" />
                  <span className="text-gray-700">Flexible schedule</span>
                </div>
                <div className="flex items-center space-x-3">
                  <FaStar className="text-yellow-600 flex-shrink-0" />
                  <span className="text-gray-700">Build your profile & ratings</span>
                </div>
                <div className="flex items-center space-x-3">
                  <FaGlobe className="text-teal-600 flex-shrink-0" />
                  <span className="text-gray-700">Join Pakistan's largest study abroad portal</span>
                </div>
                <div className="flex items-center space-x-3">
                  <FaClock className="text-red-600 flex-shrink-0" />
                  <span className="text-gray-700">No fixed hours, no office work</span>
                </div>
              </div>
              <div className="mt-6 p-4 bg-white/50 rounded-xl">
                <p className="text-gray-800 font-medium italic">
                  "No office work. No fixed hours. Just genuine guidance — and income."
                </p>
              </div>
            </div>

            {/* Who Can Apply Section */}
            <div className="bg-white rounded-2xl shadow-lg p-8 border border-gray-200">
              <h3 className="text-2xl font-bold text-gray-900 mb-6">Who Can Apply?</h3>
              <div className="space-y-3">
                <div className="flex items-center space-x-3">
                  <div className="w-6 h-6 bg-green-100 rounded-full flex items-center justify-center">
                    <FaCheck className="text-green-600 text-sm" />
                  </div>
                  <span className="text-gray-700">International students currently studying abroad</span>
                </div>
                <div className="flex items-center space-x-3">
                  <div className="w-6 h-6 bg-green-100 rounded-full flex items-center justify-center">
                    <FaCheck className="text-green-600 text-sm" />
                  </div>
                  <span className="text-gray-700">Graduates living outside Pakistan</span>
                </div>
                <div className="flex items-center space-x-3">
                  <div className="w-6 h-6 bg-green-100 rounded-full flex items-center justify-center">
                    <FaCheck className="text-green-600 text-sm" />
                  </div>
                  <span className="text-gray-700">Students with experience in admissions, visas, or student life abroad</span>
                </div>
                <div className="flex items-center space-x-3">
                  <div className="w-6 h-6 bg-green-100 rounded-full flex items-center justify-center">
                    <FaCheck className="text-green-600 text-sm" />
                  </div>
                  <span className="text-gray-700">Anyone passionate about helping others study overseas</span>
                </div>
              </div>
            </div>

            {/* How to Register Steps */}
            <div className="bg-gradient-to-r from-teal-50 to-teal-100 rounded-2xl p-8 border border-teal-200">
              <h3 className="text-2xl font-bold text-gray-900 mb-6">How to Register</h3>
              <div className="space-y-4">
                <div className="flex items-start space-x-4">
                  <div className="w-8 h-8 bg-teal-600 text-white rounded-full flex items-center justify-center flex-shrink-0">
                    1
                  </div>
                  <div>
                    <p className="font-semibold text-gray-900">Fill out the registration form</p>
                    <p className="text-sm text-gray-600">Provide your basic details and experience</p>
                  </div>
                </div>
                <div className="flex items-start space-x-4">
                  <div className="w-8 h-8 bg-teal-600 text-white rounded-full flex items-center justify-center flex-shrink-0">
                    2
                  </div>
                  <div>
                    <p className="font-semibold text-gray-900">Upload your profile photo</p>
                    <p className="text-sm text-gray-600">Add a clear, professional profile picture</p>
                  </div>
                </div>
                <div className="flex items-start space-x-4">
                  <div className="w-8 h-8 bg-teal-600 text-white rounded-full flex items-center justify-center flex-shrink-0">
                    3
                  </div>
                  <div>
                    <p className="font-semibold text-gray-900">Select your country & education level</p>
                    <p className="text-sm text-gray-600">Specify your location and academic background</p>
                  </div>
                </div>
                <div className="flex items-start space-x-4">
                  <div className="w-8 h-8 bg-teal-600 text-white rounded-full flex items-center justify-center flex-shrink-0">
                    4
                  </div>
                  <div>
                    <p className="font-semibold text-gray-900">Agree to Terms & Privacy Policy</p>
                    <p className="text-sm text-gray-600">Review and accept our terms</p>
                  </div>
                </div>
                <div className="flex items-start space-x-4">
                  <div className="w-8 h-8 bg-teal-600 text-white rounded-full flex items-center justify-center flex-shrink-0">
                    5
                  </div>
                  <div>
                    <p className="font-semibold text-gray-900">Click Create Account</p>
                    <p className="text-sm text-gray-600">Submit your application</p>
                  </div>
                </div>
              </div>
              <div className="mt-6 p-4 bg-white rounded-xl">
                <p className="text-gray-700">
                  <span className="font-semibold">Note:</span> All fields are required. Our team will review your profile and activate your account.
                </p>
              </div>
            </div>

            {/* Final CTA */}
            <div className="bg-gradient-to-r from-teal-600 to-blue-600 rounded-2xl p-8 text-center">
              <h3 className="text-2xl font-bold text-white mb-4">
                Start Earning by Helping Others Study Abroad
              </h3>
              <p className="text-white/90 mb-6">
                Join Universities Page and become part of a trusted global student network.
                Your journey can change someone else's future — and reward you for it.
              </p>
              <p className="text-xl font-bold text-white">
                👉 Register now and start earning today!
              </p>
            </div>
          </div>

          {/* Right Column - Registration Form */}
          <div className="space-y-8">
            <div className="bg-white rounded-2xl shadow-xl p-8 border border-gray-200 sticky top-8">
              <Heading level={3} className="text-center text-teal-700 mb-2">
                Registration Form
              </Heading>
              <p className="text-gray-600 text-center mb-8">
                Complete this form to become a Foreign Student Guide. <span className="text-red-500 font-semibold">*All fields are required</span>
              </p>
              
              <form onSubmit={handleSubmit} className="space-y-6">
                {/* Profile Picture Upload - Required */}
                <div className="space-y-2">
                  <label className="block text-sm font-medium text-gray-700">
                    Profile Picture <span className="text-red-500">*</span>
                  </label>
                  <div className="flex items-center space-x-4">
                    <div className="relative">
                      <div className="w-24 h-24 rounded-full border-2 border-dashed border-gray-300 flex items-center justify-center overflow-hidden bg-gray-50 hover:border-teal-500 transition-colors">
                        {uploadedImage ? (
                          <img
                            src={uploadedImage.preview}
                            alt="Profile preview"
                            className="w-full h-full object-cover"
                          />
                        ) : (
                          <FaImage className="text-gray-400 text-2xl" />
                        )}
                      </div>
                      {uploadedImage && (
                        <button
                          type="button"
                          onClick={removeImage}
                          className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm hover:bg-red-600"
                        >
                          ×
                        </button>
                      )}
                    </div>
                    <div>
                      <label className="cursor-pointer">
                        <div className="px-4 py-2 bg-teal-600 text-white rounded-full hover:bg-teal-700 transition-colors inline-flex items-center space-x-2">
                          <FaImage />
                          <span>{isUploading ? 'Uploading...' : uploadedImage ? 'Change' : 'Upload'}</span>
                        </div>
                        <input
                          type="file"
                          accept="image/*"
                          onChange={handleFileUpload}
                          className="hidden"
                          disabled={isUploading}
                        />
                      </label>
                      <p className="text-sm text-gray-500 mt-2">
                        JPG, PNG, GIF or WebP. Max 5MB.
                      </p>
                    </div>
                  </div>
                  {renderErrorMessage('profile_picture')}
                </div>

                {/* Name & Email */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      Full Name <span className="text-red-500">*</span>
                    </label>
                    <div className="relative">
                      <FaUsers className="absolute left-3 top-3 text-gray-400" />
                      <Input
                        type="text"
                        name="name"
                        value={form.name}
                        onChange={handleChange}
                        placeholder="Enter your full name"
                        className="pl-10"
                        required
                        error={!!errors.name}
                      />
                    </div>
                    {renderErrorMessage('name')}
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      Email Address <span className="text-red-500">*</span>
                    </label>
                    <div className="relative">
                      <FaEnvelope className="absolute left-3 top-3 text-gray-400" />
                      <Input
                        type="email"
                        name="email"
                        value={form.email}
                        onChange={handleChange}
                        placeholder="Enter your email"
                        className="pl-10"
                        required
                        error={!!errors.email}
                      />
                    </div>
                    {renderErrorMessage('email')}
                  </div>
                </div>

                {/* Password Fields */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      Password <span className="text-red-500">*</span>
                    </label>
                    <div className="relative">
                      <FaLock className="absolute left-3 top-3 text-gray-400" />
                      <Input
                        type={showPassword ? 'text' : 'password'}
                        name="password"
                        value={form.password}
                        onChange={handleChange}
                        placeholder="Create password"
                        className="pl-10 pr-10"
                        required
                        error={!!errors.password}
                      />
                      <button
                        type="button"
                        onClick={togglePasswordVisibility}
                        className="absolute right-3 top-3 text-gray-500 hover:text-gray-700"
                      >
                        {showPassword ? <FaEyeSlash /> : <FaEye />}
                      </button>
                    </div>
                    {renderErrorMessage('password')}
                  </div>
                  
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      Confirm Password <span className="text-red-500">*</span>
                    </label>
                    <div className="relative">
                      <FaLock className="absolute left-3 top-3 text-gray-400" />
                      <Input
                        type={showConfirmPassword ? 'text' : 'password'}
                        name="confirm_password"
                        value={form.confirm_password}
                        onChange={handleChange}
                        placeholder="Confirm password"
                        className="pl-10 pr-10"
                        required
                        error={!!errors.confirm_password}
                      />
                      <button
                        type="button"
                        onClick={toggleConfirmPasswordVisibility}
                        className="absolute right-3 top-3 text-gray-500 hover:text-gray-700"
                      >
                        {showConfirmPassword ? <FaEyeSlash /> : <FaEye />}
                      </button>
                    </div>
                    {renderErrorMessage('confirm_password')}
                  </div>
                </div>

                {/* Phone & Country */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      Phone Number <span className="text-red-500">*</span>
                    </label>
                    <div className="relative">
                      <FaPhone className="absolute left-3 top-3 text-gray-400" />
                      <Input
                        type="tel"
                        name="phone"
                        value={form.phone}
                        onChange={handleChange}
                        placeholder="+1234567890"
                        className="pl-10"
                        required
                        error={!!errors.phone}
                      />
                    </div>
                    {renderErrorMessage('phone')}
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      Country <span className="text-red-500">*</span>
                    </label>
                    <CountrySelect
                      name="country"
                      icon={<FaGlobe />}
                      placeholder="Select your country"
                      value={form.country_id}
                      onChange={handleCountryChange}
                      options={countryOptions}
                      required
                      error={!!errors.country_id}
                    />
                    {renderErrorMessage('country_id')}
                  </div>
                </div>

                {/* Hour Rate & Education */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      Hourly Rate ($) <span className="text-red-500">*</span>
                    </label>
                    <div className="relative">
                      <FaDollarSign className="absolute left-3 top-3 text-gray-400" />
                      <Input
                        type="number"
                        name="hour_rate"
                        value={form.hour_rate}
                        onChange={handleChange}
                        placeholder="0.00"
                        step="0.01"
                        min="0.01"
                        className="pl-10"
                        required
                        error={!!errors.hour_rate}
                      />
                    </div>
                    {renderErrorMessage('hour_rate')}
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      Education Level <span className="text-red-500">*</span>
                    </label>
                    <div className="relative">
                      <FaUserGraduate className="absolute left-3 top-3 text-gray-400" />
                      <select
                        name="last_education"
                        value={form.last_education}
                        onChange={handleChange}
                        className={`w-full px-4 py-3 border rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent pl-10 ${
                          errors.last_education ? 'border-red-500' : 'border-gray-300 bg-gray-50'
                        }`}
                        required
                      >
                        <option value="">Select education level</option>
                        {educationOptions.map(option => (
                          <option key={option.value} value={option.value}>
                            {option.label}
                          </option>
                        ))}
                      </select>
                    </div>
                    {renderErrorMessage('last_education')}
                  </div>
                </div>

                {/* Gender */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Gender <span className="text-red-500">*</span>
                  </label>
                  <div className="flex items-center space-x-6">
                    {['male', 'female', 'other'].map((g) => (
                      <label key={g} className="flex items-center space-x-2">
                        <input
                          type="radio"
                          name="gender"
                          value={g}
                          checked={form.gender === g}
                          onChange={handleChange}
                          className="accent-teal-600"
                          required
                        />
                        <span className="capitalize">{g}</span>
                      </label>
                    ))}
                  </div>
                  {renderErrorMessage('gender')}
                </div>

                {/* About Me */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    About Yourself <span className="text-red-500">*</span>
                  </label>
                  <TextArea
                    name="about_me"
                    value={form.about_me}
                    onChange={handleChange}
                    placeholder="Tell us about your background, interests, and why you want to be a student guide..."
                    rows={3}
                    required
                    error={!!errors.about_me}
                  />
                  {renderErrorMessage('about_me')}
                </div>

                {/* Experience */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Experience <span className="text-red-500">*</span>
                  </label>
                  <TextArea
                    name="experience"
                    value={form.experience}
                    onChange={handleChange}
                    placeholder="Share your study abroad experience, any previous mentoring or teaching experience..."
                    rows={3}
                    required
                    error={!!errors.experience}
                  />
                  {renderErrorMessage('experience')}
                </div>

                {/* Terms and Conditions */}
                <div className={`rounded-xl p-4 ${
                  errors.terms_accepted ? 'bg-red-50 border border-red-200' : 'bg-blue-50'
                }`}>
                  <label className="flex items-start space-x-3">
                    <input
                      type="checkbox"
                      name="terms_accepted"
                      checked={form.terms_accepted}
                      onChange={handleChange}
                      className="accent-teal-600 mt-1 flex-shrink-0"
                      required
                    />
                    <span className="text-sm text-gray-700">
                      I agree to the{' '}
                      <a href="/terms" target="_blank" className="text-teal-600 underline hover:text-teal-700 font-medium">
                        Terms and Conditions
                      </a>
                      {' '}and{' '}
                      <a href="/privacy" target="_blank" className="text-teal-600 underline hover:text-teal-700 font-medium">
                        Privacy Policy
                      </a>
                      . I understand that my profile will be reviewed before activation.
                    </span>
                  </label>
                  {renderErrorMessage('terms_accepted')}
                </div>

                {/* Submit Button */}
                <div>
                  <Button 
                    type="submit" 
                    disabled={isSubmitting || isUploading}
                    className="w-full py-4 text-lg font-semibold"
                  >
                    {isSubmitting ? (
                      <div className="flex items-center justify-center">
                        <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin mr-3"></div>
                        Creating Your Account...
                      </div>
                    ) : (
                      '🚀 Create Account & Start Earning'
                    )}
                  </Button>
                  <p className="text-center text-sm text-gray-500 mt-4">
                    Already have an account?{' '}
                    <button
                      type="button"
                      onClick={() => router.push('/foreign-students/login')}
                      className="text-teal-600 font-medium hover:text-teal-700 underline"
                    >
                      Login here
                    </button>
                  </p>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}