'use client';

import { useState, useRef, useEffect } from 'react';
import { 
  UploadCloud, User, FileText, 
  GraduationCap, Globe, Mail, 
  Phone, Calendar, Flag, 
  BookOpen, Building, Award,
  CheckCircle, X, Loader2,
  Paperclip, Image as ImageIcon,
  File, FileCheck, Clock,
  AlertCircle
} from 'lucide-react';
import Input from '../atoms/Input';
import Heading from '../atoms/Heading';
import Image from 'next/image';
import Swal from 'sweetalert2';
import withReactContent from 'sweetalert2-react-content';

const MySwal = withReactContent(Swal);

interface ValidationError {
  field: string;
  message: string;
}

const NewStudentForm = () => {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    passportNumber: '',
    dateOfBirth: '',
    course: '',
    country: '',
    nationality: '',
    university: '',
  });

  const [files, setFiles] = useState({
    passport: null as string | null,
    photo: null as string | null,
    degree: null as string | null,
    certificate: null as string | null,
    recommendation: null as string | null,
    studyPlan: null as string | null,
    ielts: null as string | null,
  });

  const [previews, setPreviews] = useState<Record<string, string>>({});
  const [uploading, setUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState<Record<string, number>>({});
  const [uploadedFiles, setUploadedFiles] = useState<Record<string, boolean>>({});
  const [submissionStatus, setSubmissionStatus] = useState<{
    type: 'success' | 'error';
    message: string;
  } | null>(null);
  
  const [validationErrors, setValidationErrors] = useState<ValidationError[]>([]);
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});

  const fileRequirements = {
    passport: { required: true, type: 'image/*,.pdf,.doc,.docx', size: '5MB', label: 'Passport Copy' },
    photo: { required: true, type: 'image/*', size: '5MB', label: 'Passport Photo' },
    degree: { required: true, type: '*', size: '10MB', label: 'Educational Degree' },
    certificate: { required: true, type: '*', size: '10MB', label: 'Educational Certificate' },
    recommendation: { required: true, type: '*', size: '10MB', label: 'Recommendation Letter' },
    studyPlan: { required: true, type: '*', size: '10MB', label: 'Study Plan' },
    ielts: { required: true, type: '*', size: '10MB', label: 'English Proficiency' },
  };

  // Show success SweetAlert
  const showSuccessAlert = (message: string) => {
    MySwal.fire({
      title: <span className="text-2xl font-bold text-green-600">Success!</span>,
      html: (
        <div className="text-center">
          <div className="flex justify-center mb-4">
            <div className="p-3 bg-gradient-to-r from-green-100 to-emerald-100 rounded-full">
              <CheckCircle size={48} className="text-green-600" />
            </div>
          </div>
          <p className="text-lg text-gray-700 mb-2">{message}</p>
          <p className="text-sm text-gray-500">The student has been registered successfully.</p>
        </div>
      ),
      icon: 'success',
      showConfirmButton: true,
      confirmButtonText: 'Continue',
      confirmButtonColor: '#0B6D76',
      timer: 3000,
      timerProgressBar: true,
      background: '#f9fafb',
      customClass: {
        popup: 'rounded-2xl shadow-2xl border border-gray-200',
        confirmButton: 'px-6 py-2.5 rounded-xl font-medium'
      }
    });
  };

  // Show error SweetAlert
  const showErrorAlert = (message: string, errors?: ValidationError[]) => {
    MySwal.fire({
      title: <span className="text-2xl font-bold text-rose-600">Oops!</span>,
      html: (
        <div className="text-left">
          <div className="flex justify-center mb-4">
            <div className="p-3 bg-gradient-to-r from-rose-100 to-pink-100 rounded-full">
              <AlertCircle size={48} className="text-rose-600" />
            </div>
          </div>
          <p className="text-lg text-gray-700 mb-4">{message}</p>
          {errors && errors.length > 0 && (
            <div className="bg-gradient-to-r from-amber-50 to-orange-50 p-4 rounded-xl border border-amber-200 mb-4">
              <h4 className="font-semibold text-amber-800 mb-2">Validation Errors:</h4>
              <ul className="text-sm text-amber-700 space-y-1">
                {errors.slice(0, 3).map((error, index) => (
                  <li key={index} className="flex items-start gap-2">
                    <div className="w-1.5 h-1.5 bg-amber-500 rounded-full mt-1.5 flex-shrink-0" />
                    <span><strong className="capitalize">{error.field.replace(/([A-Z])/g, ' $1').trim()}:</strong> {error.message}</span>
                  </li>
                ))}
                {errors.length > 3 && (
                  <li className="text-amber-600 text-sm">
                    ...and {errors.length - 3} more error{errors.length - 3 > 1 ? 's' : ''}
                  </li>
                )}
              </ul>
            </div>
          )}
        </div>
      ),
      icon: 'error',
      showConfirmButton: true,
      confirmButtonText: 'Try Again',
      confirmButtonColor: '#dc2626',
      background: '#f9fafb',
      customClass: {
        popup: 'rounded-2xl shadow-2xl border border-gray-200',
        confirmButton: 'px-6 py-2.5 rounded-xl font-medium'
      }
    });
  };

  // Show file upload error SweetAlert
  const showFileErrorAlert = (missingFiles: string[]) => {
    MySwal.fire({
      title: <span className="text-2xl font-bold text-amber-600">Missing Documents</span>,
      html: (
        <div className="text-left">
          <div className="flex justify-center mb-4">
            <div className="p-3 bg-gradient-to-r from-amber-100 to-orange-100 rounded-full">
              <FileText size={48} className="text-amber-600" />
            </div>
          </div>
          <p className="text-lg text-gray-700 mb-4">Please upload all required documents:</p>
          <ul className="space-y-2">
            {missingFiles.map((field, index) => (
              <li key={index} className="flex items-center gap-3 p-3 bg-gradient-to-r from-gray-50 to-gray-100 rounded-lg">
                <div className="p-2 bg-white rounded-lg border border-gray-200">
                  {field === 'passport' || field === 'photo' ? (
                    <ImageIcon size={20} className="text-gray-600" />
                  ) : field === 'degree' || field === 'certificate' ? (
                    <Award size={20} className="text-gray-600" />
                  ) : field === 'recommendation' ? (
                    <FileText size={20} className="text-gray-600" />
                  ) : field === 'studyPlan' ? (
                    <BookOpen size={20} className="text-gray-600" />
                  ) : field === 'ielts' ? (
                    <FileCheck size={20} className="text-gray-600" />
                  ) : (
                    <Paperclip size={20} className="text-gray-600" />
                  )}
                </div>
                <span className="font-medium text-gray-800">
                  {fileRequirements[field as keyof typeof fileRequirements]?.label || field}
                </span>
              </li>
            ))}
          </ul>
        </div>
      ),
      icon: 'warning',
      showConfirmButton: true,
      confirmButtonText: 'Upload Files',
      confirmButtonColor: '#0B6D76',
      background: '#f9fafb',
      customClass: {
        popup: 'rounded-2xl shadow-2xl border border-gray-200',
        confirmButton: 'px-6 py-2.5 rounded-xl font-medium'
      }
    });
  };

  // Show confirmation dialog before submission
  const showConfirmationDialog = () => {
    return MySwal.fire({
      title: <span className="text-2xl font-bold text-gray-800">Confirm Registration</span>,
      html: (
        <div className="text-center">
          <div className="flex justify-center mb-4">
            <div className="p-3 bg-gradient-to-r from-blue-100 to-cyan-100 rounded-full">
              <GraduationCap size={48} className="text-blue-600" />
            </div>
          </div>
          <p className="text-lg text-gray-700 mb-2">Are you sure you want to register this student?</p>
          <p className="text-sm text-gray-500">
            Please review all information before submitting. This action cannot be undone.
          </p>
          
          <div className="mt-6 p-4 bg-gradient-to-r from-gray-50 to-gray-100 rounded-xl text-left">
            <div className="grid grid-cols-2 gap-3 text-sm">
              <div>
                <span className="text-gray-500">Student:</span>
                <p className="font-medium text-gray-800">{formData.name || 'Not specified'}</p>
              </div>
              <div>
                <span className="text-gray-500">Course:</span>
                <p className="font-medium text-gray-800">{formData.course || 'Not specified'}</p>
              </div>
              <div>
                <span className="text-gray-500">Email:</span>
                <p className="font-medium text-gray-800">{formData.email || 'Not specified'}</p>
              </div>
              <div>
                <span className="text-gray-500">Documents:</span>
                <p className="font-medium text-gray-800">
                  {Object.values(uploadedFiles).filter(Boolean).length} of {
                    Object.values(fileRequirements).filter(req => req.required).length
                  } uploaded
                </p>
              </div>
            </div>
          </div>
        </div>
      ),
      icon: 'question',
      showCancelButton: true,
      confirmButtonText: 'Yes, Register Student',
      cancelButtonText: 'Review Again',
      confirmButtonColor: '#0B6D76',
      cancelButtonColor: '#6b7280',
      background: '#f9fafb',
      customClass: {
        popup: 'rounded-2xl shadow-2xl border border-gray-200',
        confirmButton: 'px-6 py-2.5 rounded-xl font-medium mr-2',
        cancelButton: 'px-6 py-2.5 rounded-xl font-medium'
      },
      reverseButtons: true
    });
  };

  // Clear errors when user starts typing
  useEffect(() => {
    const handleInputChange = (field: string) => {
      setFieldErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    };
  }, []);

  const handleInputChange = (field: string, value: string) => {
    setFieldErrors(prev => {
      const newErrors = { ...prev };
      delete newErrors[field];
      return newErrors;
    });

    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  const handleFileChange = async (field: string, file: File) => {
    const requirement = fileRequirements[field as keyof typeof fileRequirements];
    
    setFieldErrors(prev => {
      const newErrors = { ...prev };
      delete newErrors[`files.${field}`];
      return newErrors;
    });

    const maxSize = parseInt(requirement.size) * 1024 * 1024;
    if (file.size > maxSize) {
      setFieldErrors(prev => ({
        ...prev,
        [`files.${field}`]: `File too large. Maximum size is ${requirement.size}`
      }));
      return;
    }

    if (requirement.type !== '*') {
      const acceptedTypes = requirement.type.split(',').map(type => type.trim());
      const fileExtension = file.name.split('.').pop()?.toLowerCase();
      const mimeType = file.type;
      
      let isValidType = false;
      
      if (acceptedTypes.some(type => {
        if (type.includes('/*')) {
          const baseType = type.split('/')[0];
          return mimeType.startsWith(baseType + '/');
        }
        return type === mimeType;
      })) {
        isValidType = true;
      }
      
      if (!isValidType && fileExtension) {
        const validExtensions = acceptedTypes
          .filter(type => !type.includes('/'))
          .map(type => type.replace('.', '').toLowerCase());
        
        if (validExtensions.includes(fileExtension)) {
          isValidType = true;
        }
      }

      if (!isValidType) {
        setFieldErrors(prev => ({
          ...prev,
          [`files.${field}`]: `Invalid file type. Accepted: ${requirement.type.replace('*', 'All files')}`
        }));
        return;
      }
    }

    if (file.type.startsWith('image/')) {
      const reader = new FileReader();
      reader.onload = (e) => {
        setPreviews(prev => ({
          ...prev,
          [field]: e.target?.result as string
        }));
      };
      reader.readAsDataURL(file);
    } else {
      setPreviews(prev => ({
        ...prev,
        [field]: 'document'
      }));
    }

    try {
      setUploadProgress(prev => ({ ...prev, [field]: 0 }));
      
      const uploadResult = await uploadFile(file, 'c-student', (progress: number) => {
        setUploadProgress(prev => ({ ...prev, [field]: progress }));
      });
      
      if (uploadResult.success) {
        setFiles(prev => ({ ...prev, [field]: uploadResult.s3Key }));
        setUploadedFiles(prev => ({ ...prev, [field]: true }));
        
        setTimeout(() => {
          setUploadProgress(prev => {
            const newProgress = { ...prev };
            delete newProgress[field];
            return newProgress;
          });
        }, 1000);
      } else {
        throw new Error(uploadResult.message);
      }
    } catch (error) {
      console.error(`Error uploading ${field}:`, error);
      setFieldErrors(prev => ({
        ...prev,
        [`files.${field}`]: `Failed to upload ${requirement.label}. Please try again.`
      }));
      setUploadedFiles(prev => ({ ...prev, [field]: false }));
    }
  };

  const uploadFile = async (file: File, uploadType: string, onProgress: (progress: number) => void) => {
    const formData = new FormData();
    formData.append('image', file);
    formData.append('uploadType', uploadType);

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

    return await response.json();
  };

  const removeFile = (field: string) => {
    setFiles(prev => ({ ...prev, [field]: null }));
    setUploadedFiles(prev => ({ ...prev, [field]: false }));
    setPreviews(prev => {
      const newPreviews = { ...prev };
      delete newPreviews[field];
      return newPreviews;
    });
    
    setFieldErrors(prev => {
      const newErrors = { ...prev };
      delete newErrors[`files.${field}`];
      return newErrors;
    });
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmissionStatus(null);
    setValidationErrors([]);
    setFieldErrors({});

    // Show confirmation dialog first
    const confirmation = await showConfirmationDialog();
    if (!confirmation.isConfirmed) {
      return;
    }

    setUploading(true);

    try {
      // Check if all required files are uploaded
      const requiredFiles = Object.entries(fileRequirements)
        .filter(([, req]) => req.required)
        .map(([field]) => field);
      
      const missingFiles = requiredFiles.filter(field => !files[field as keyof typeof files]);
      
      if (missingFiles.length > 0) {
        const newErrors: Record<string, string> = {};
        missingFiles.forEach(field => {
          newErrors[`files.${field}`] = `${fileRequirements[field as keyof typeof fileRequirements].label} is required`;
        });
        setFieldErrors(newErrors);
        
        // Show SweetAlert for missing files
        showFileErrorAlert(missingFiles);
        
        setUploading(false);
        return;
      }

      // Prepare submission data
      const submissionData = {
        ...formData,
        files: {
          passport: files.passport || '',
          photo: files.photo || '',
          educationalDegree: files.degree || '',
          educationalCertificate: files.certificate || '',
          recommendationLetter: files.recommendation || '',
          studyPlan: files.studyPlan || '',
          ieltsOrEnglishProficiency: files.ielts || '',
        }
      };

      // Submit to the API
      const response = await fetch('/api/frontend/consultant/consultantdashboard/student/add', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(submissionData),
      });

      const result = await response.json();

      if (result.success) {
        // Show success SweetAlert
        showSuccessAlert(result.message || 'Student added successfully!');
        
        // Reset form after 3 seconds
        setTimeout(() => {
          resetForm();
        }, 3000);
      } else {
        // Handle validation errors from backend
        if (result.errors && Array.isArray(result.errors)) {
          const newFieldErrors: Record<string, string> = {};
          result.errors.forEach((error: ValidationError) => {
            newFieldErrors[error.field] = error.message;
          });
          setFieldErrors(prev => ({ ...prev, ...newFieldErrors }));
          setValidationErrors(result.errors);
          
          // Show error SweetAlert with validation errors
          showErrorAlert(result.message || 'Please fix the errors below', result.errors);
        } else {
          // Show generic error SweetAlert
          showErrorAlert(result.message || 'Failed to add student');
        }
      }
    } catch (error) {
      console.error('Error submitting form:', error);
      // Show error SweetAlert for network/unknown errors
      showErrorAlert('Error submitting form. Please try again.');
    } finally {
      setUploading(false);
    }
  };

  const resetForm = () => {
    setFormData({
      name: '',
      email: '',
      phone: '',
      passportNumber: '',
      dateOfBirth: '',
      course: '',
      country: '',
      nationality: '',
      university: '',
    });
    setFiles({
      passport: null,
      photo: null,
      degree: null,
      certificate: null,
      recommendation: null,
      studyPlan: null,
      ielts: null,
    });
    setPreviews({});
    setUploadedFiles({});
    setValidationErrors([]);
    setFieldErrors({});
    setSubmissionStatus(null);
  };

  const getFileIcon = (field: string) => {
    if (field === 'passport' || field === 'photo') return ImageIcon;
    if (field === 'degree' || field === 'certificate') return Award;
    if (field === 'recommendation') return FileText;
    if (field === 'studyPlan') return BookOpen;
    if (field === 'ielts') return FileCheck;
    return Paperclip;
  };

  const getFileDisplayName = (field: string) => {
    if (!files[field as keyof typeof files]) return '';
    const url = files[field as keyof typeof files] as string;
    const parts = url.split('/');
    return parts[parts.length - 1];
  };

  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 */}
        <div className="text-center mb-10">
          <div className="flex items-center justify-center gap-4 mb-6">
            <div className="p-3 bg-gradient-to-r from-[#0B6D76] to-teal-600 rounded-xl shadow-lg">
              <GraduationCap size={32} className="text-white" />
            </div>
            <div>
              <Heading level={5} className="text-3xl md:text-4xl font-bold text-gray-900">
                Add New Student
              </Heading>
              <p className="text-gray-600 mt-2">
                Complete all required information to register a new student
              </p>
            </div>
          </div>
          
          <div className="inline-flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-blue-100 to-cyan-100 rounded-full">
            <Clock size={16} className="text-blue-600" />
            <span className="text-blue-700 font-medium">
              📝 All documents are required
            </span>
          </div>
        </div>

        {/* Submission Status (Optional - You can remove this if you want only SweetAlert) */}
        {submissionStatus && (
          <div className={`mb-6 rounded-2xl p-5 ${
            submissionStatus.type === 'success' 
              ? 'bg-gradient-to-r from-green-100 to-emerald-100 border border-green-200' 
              : 'bg-gradient-to-r from-rose-100 to-pink-100 border border-rose-200'
          }`}>
            <div className="flex items-center gap-3">
              {submissionStatus.type === 'success' ? (
                <CheckCircle size={24} className="text-green-600" />
              ) : (
                <AlertCircle size={24} className="text-rose-600" />
              )}
              <div>
                <h4 className={`font-bold ${
                  submissionStatus.type === 'success' ? 'text-green-800' : 'text-rose-800'
                }`}>
                  {submissionStatus.type === 'success' ? 'Success!' : 'Please check the form'}
                </h4>
                <p className={submissionStatus.type === 'success' ? 'text-green-700' : 'text-rose-700'}>
                  {submissionStatus.message}
                </p>
              </div>
            </div>
          </div>
        )}

        {/* Validation Errors Summary */}
        {validationErrors.length > 0 && (
          <div className="mb-6 rounded-2xl p-5 bg-gradient-to-r from-amber-100 to-orange-100 border border-amber-200">
            <div className="flex items-center gap-3 mb-3">
              <AlertCircle size={24} className="text-amber-600" />
              <h4 className="font-bold text-amber-800">Validation Errors</h4>
            </div>
            <ul className="text-sm text-amber-700 space-y-1">
              {validationErrors.map((error, index) => (
                <li key={index} className="flex items-start gap-2">
                  <div className="w-1.5 h-1.5 bg-amber-500 rounded-full mt-1.5" />
                  <span>
                    <strong>{error.field}:</strong> {error.message}
                  </span>
                </li>
              ))}
            </ul>
          </div>
        )}

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Left Column - Form */}
          <div className="lg:col-span-2">
            <div className="bg-white rounded-2xl shadow-xl p-6 md:p-8 border border-gray-200">
              <div className="mb-8">
                <div className="flex items-center gap-3 mb-2">
                  <div className="p-2 bg-gradient-to-r from-blue-100 to-cyan-100 rounded-lg">
                    <User size={24} className="text-blue-600" />
                  </div>
                  <div>
                    <h2 className="text-2xl font-bold text-gray-900">Student Information</h2>
                    <p className="text-gray-600">Enter the student personal details</p>
                  </div>
                </div>
              </div>

              <form onSubmit={handleSubmit} className="space-y-6">
                {/* Personal Information */}
                <div className="space-y-4">
                  <h3 className="font-bold text-gray-800 text-lg flex items-center gap-2">
                    <User size={18} />
                    Personal Details
                  </h3>
                  
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-1">
                      <Input 
                        icon={<User size={18} />} 
                        name="name"
                        type="text" 
                        placeholder="Full Name"
                        value={formData.name}
                        onChange={(e) => handleInputChange('name', e.target.value)}
                        required
                        error={fieldErrors.name}
                      />
                      {fieldErrors.name && (
                        <p className="text-rose-600 text-sm flex items-center gap-1">
                          <AlertCircle size={14} />
                          {fieldErrors.name}
                        </p>
                      )}
                    </div>
                    
                    <div className="space-y-1">
                      <Input 
                        icon={<Mail size={18} />} 
                        name="email"
                        type="email" 
                        placeholder="Email Address"
                        value={formData.email}
                        onChange={(e) => handleInputChange('email', e.target.value)}
                        required
                        error={fieldErrors.email}
                      />
                      {fieldErrors.email && (
                        <p className="text-rose-600 text-sm flex items-center gap-1">
                          <AlertCircle size={14} />
                          {fieldErrors.email}
                        </p>
                      )}
                    </div>
                    
                    <div className="space-y-1">
                      <Input 
                        icon={<Phone size={18} />} 
                        name="phone"
                        type="tel" 
                        placeholder="Phone Number"
                        value={formData.phone}
                        onChange={(e) => handleInputChange('phone', e.target.value)}
                        required
                        error={fieldErrors.phone}
                      />
                      {fieldErrors.phone && (
                        <p className="text-rose-600 text-sm flex items-center gap-1">
                          <AlertCircle size={14} />
                          {fieldErrors.phone}
                        </p>
                      )}
                    </div>
                    
                    <div className="space-y-1">
                      <Input 
                        icon={<FileText size={18} />} 
                        name="passportNumber"
                        type="text" 
                        placeholder="Passport Number"
                        value={formData.passportNumber}
                        onChange={(e) => handleInputChange('passportNumber', e.target.value)}
                        required
                        error={fieldErrors.passportNumber}
                      />
                      {fieldErrors.passportNumber && (
                        <p className="text-rose-600 text-sm flex items-center gap-1">
                          <AlertCircle size={14} />
                          {fieldErrors.passportNumber}
                        </p>
                      )}
                    </div>
                    
                    <div className="space-y-1">
                      <Input 
                        icon={<Calendar size={18} />} 
                        name="dateOfBirth"
                        type="date" 
                        placeholder="Date of Birth"
                        value={formData.dateOfBirth}
                        onChange={(e) => handleInputChange('dateOfBirth', e.target.value)}
                        required
                        error={fieldErrors.dateOfBirth}
                      />
                      {fieldErrors.dateOfBirth && (
                        <p className="text-rose-600 text-sm flex items-center gap-1">
                          <AlertCircle size={14} />
                          {fieldErrors.dateOfBirth}
                        </p>
                      )}
                    </div>
                    
                    <div className="space-y-1">
                      <Input 
                        icon={<Flag size={18} />} 
                        name="nationality"
                        type="text" 
                        placeholder="Nationality"
                        value={formData.nationality}
                        onChange={(e) => handleInputChange('nationality', e.target.value)}
                        required
                        error={fieldErrors.nationality}
                      />
                      {fieldErrors.nationality && (
                        <p className="text-rose-600 text-sm flex items-center gap-1">
                          <AlertCircle size={14} />
                          {fieldErrors.nationality}
                        </p>
                      )}
                    </div>
                  </div>
                </div>

                {/* Education Information */}
                <div className="space-y-4">
                  <h3 className="font-bold text-gray-800 text-lg flex items-center gap-2">
                    <GraduationCap size={18} />
                    Education Details
                  </h3>
                  
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-1">
                      <Input 
                        icon={<BookOpen size={18} />} 
                        name="course"
                        type="text" 
                        placeholder="Desired Course"
                        value={formData.course}
                        onChange={(e) => handleInputChange('course', e.target.value)}
                        required
                        error={fieldErrors.course}
                      />
                      {fieldErrors.course && (
                        <p className="text-rose-600 text-sm flex items-center gap-1">
                          <AlertCircle size={14} />
                          {fieldErrors.course}
                        </p>
                      )}
                    </div>
                    
                    <div className="space-y-1">
                      <Input 
                        icon={<Globe size={18} />} 
                        name="country"
                        type="text" 
                        placeholder="Target Country"
                        value={formData.country}
                        onChange={(e) => handleInputChange('country', e.target.value)}
                        required
                        error={fieldErrors.country}
                      />
                      {fieldErrors.country && (
                        <p className="text-rose-600 text-sm flex items-center gap-1">
                          <AlertCircle size={14} />
                          {fieldErrors.country}
                        </p>
                      )}
                    </div>
                    
                    <div className="space-y-1">
                      <Input 
                        icon={<Building size={18} />} 
                        name="university"
                        type="text" 
                        placeholder="Preferred University"
                        value={formData.university}
                        onChange={(e) => handleInputChange('university', e.target.value)}
                        error={fieldErrors.university}
                      />
                      {fieldErrors.university && (
                        <p className="text-rose-600 text-sm flex items-center gap-1">
                          <AlertCircle size={14} />
                          {fieldErrors.university}
                        </p>
                      )}
                    </div>
                  </div>
                </div>

                {/* Submit Button */}
                <button
                  type="submit"
                  disabled={uploading}
                  className="w-full bg-gradient-to-r from-[#0B6D76] to-teal-600 text-white font-bold py-3.5 rounded-xl hover:shadow-xl transition-all hover:scale-[1.02] disabled:opacity-70 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                >
                  {uploading ? (
                    <>
                      <Loader2 size={20} className="animate-spin" />
                      Processing...
                    </>
                  ) : (
                    <>
                      <CheckCircle size={20} />
                      Register Student
                    </>
                  )}
                </button>
              </form>
            </div>
          </div>

          {/* Right Column - Document Upload */}
          <div className="lg:col-span-1">
            <div className="bg-white rounded-2xl shadow-xl p-6 border border-gray-200 sticky top-6">
              <div className="mb-6">
                <div className="flex items-center gap-3 mb-2">
                  <div className="p-2 bg-gradient-to-r from-purple-100 to-pink-100 rounded-lg">
                    <FileText size={24} className="text-purple-600" />
                  </div>
                  <div>
                    <h2 className="text-2xl font-bold text-gray-900">Documents</h2>
                    <p className="text-gray-600">Upload all required files</p>
                  </div>
                </div>
              </div>

              {/* Upload Progress Summary */}
              <div className="mb-6">
                <div className="flex items-center justify-between mb-2">
                  <span className="text-sm font-medium text-gray-700">Upload Progress</span>
                  <span className="text-sm font-bold text-gray-900">
                    {Object.values(uploadedFiles).filter(Boolean).length} of {
                      Object.values(fileRequirements).filter(req => req.required).length
                    } required
                  </span>
                </div>
                <div className="w-full bg-gray-200 rounded-full h-2">
                  <div 
                    className="h-full bg-gradient-to-r from-green-500 to-emerald-600 transition-all duration-500"
                    style={{ 
                      width: `${(Object.values(uploadedFiles).filter(Boolean).length / Object.values(fileRequirements).filter(req => req.required).length) * 100}%` 
                    }}
                  />
                </div>
              </div>

              {/* File Upload Fields */}
              <div className="space-y-4">
                {Object.entries(fileRequirements).map(([field, requirement]) => {
                  const FileIcon = getFileIcon(field);
                  const isUploaded = uploadedFiles[field];
                  const isUploading = uploadProgress[field] !== undefined;
                  const progress = uploadProgress[field];
                  const fileError = fieldErrors[`files.${field}`];
                  
                  return (
                    <div 
                      key={field}
                      className={`p-4 rounded-xl border transition-all ${
                        fileError
                          ? 'bg-gradient-to-r from-rose-50 to-pink-50 border-rose-200'
                          : isUploaded 
                          ? 'bg-gradient-to-r from-green-50 to-emerald-50 border-green-200' 
                          : isUploading
                          ? 'bg-gradient-to-r from-blue-50 to-cyan-50 border-blue-200'
                          : 'bg-gray-50 border-gray-200'
                      }`}
                    >
                      <div className="flex items-center justify-between mb-2">
                        <div className="flex items-center gap-3">
                          <div className={`p-2 rounded-lg ${
                            fileError
                              ? 'bg-rose-100 text-rose-600'
                              : isUploaded 
                              ? 'bg-green-100 text-green-600' 
                              : isUploading
                              ? 'bg-blue-100 text-blue-600'
                              : 'bg-gray-100 text-gray-600'
                          }`}>
                            <FileIcon size={18} />
                          </div>
                          <div>
                            <h4 className="font-medium text-gray-900">{requirement.label}</h4>
                            <p className="text-xs text-gray-500">
                              Required • Max {requirement.size}
                            </p>
                          </div>
                        </div>
                        
                        {isUploaded && !fileError && (
                          <CheckCircle size={18} className="text-green-500" />
                        )}
                      </div>
                      
                      {fileError && (
                        <div className="mb-2">
                          <p className="text-rose-600 text-sm flex items-center gap-1">
                            <AlertCircle size={14} />
                            {fileError}
                          </p>
                        </div>
                      )}
                      
                      {isUploading ? (
                        <div className="mt-2">
                          <div className="flex items-center justify-between text-sm mb-1">
                            <span className="text-blue-600">Uploading...</span>
                            <span className="font-medium">{progress}%</span>
                          </div>
                          <div className="w-full bg-gray-200 rounded-full h-1.5">
                            <div 
                              className="h-full bg-gradient-to-r from-blue-500 to-cyan-600 transition-all duration-300"
                              style={{ width: `${progress}%` }}
                            />
                          </div>
                        </div>
                      ) : files[field as keyof typeof files] ? (
                        <div className="mt-2">
                          {previews[field] && previews[field] !== 'document' ? (
                            <div className="mb-2">
                              <div className="relative w-16 h-16 rounded-lg overflow-hidden border border-gray-300">
                                <Image
                                  src={previews[field]}
                                  alt={requirement.label}
                                  fill
                                  className="object-cover"
                                />
                              </div>
                            </div>
                          ) : previews[field] === 'document' ? (
                            <div className="mb-2">
                              <div className="w-16 h-16 rounded-lg border border-gray-300 flex items-center justify-center bg-gray-100">
                                <FileText size={24} className="text-gray-500" />
                              </div>
                            </div>
                          ) : null}
                          
                          <div className="flex items-center justify-between">
                            <div className="flex-1 min-w-0">
                              <span className="text-sm text-gray-600 truncate block">
                                {getFileDisplayName(field)}
                              </span>
                              <span className="text-xs text-gray-500">
                                {requirement.label}
                              </span>
                            </div>
                            <button
                              type="button"
                              onClick={() => removeFile(field)}
                              className="p-1 text-gray-400 hover:text-rose-600 hover:bg-rose-50 rounded-lg transition-colors ml-2"
                            >
                              <X size={16} />
                            </button>
                          </div>
                        </div>
                      ) : (
                        <UploadField 
                          field={field}
                          requirement={requirement}
                          onFileChange={handleFileChange}
                          isUploaded={isUploaded}
                          error={fileError}
                        />
                      )}
                    </div>
                  );
                })}
              </div>

              {/* Upload Instructions */}
              <div className="mt-6 pt-6 border-t border-gray-200">
                <h4 className="font-medium text-gray-900 mb-2">Upload Instructions</h4>
                <ul className="text-sm text-gray-600 space-y-1">
                  <li className="flex items-center gap-2">
                    <div className="w-1.5 h-1.5 bg-green-500 rounded-full" />
                    All documents are required
                  </li>
                  <li className="flex items-center gap-2">
                    <div className="w-1.5 h-1.5 bg-blue-500 rounded-full" />
                    Accepted: Images, PDF, DOC, DOCX
                  </li>
                  <li className="flex items-center gap-2">
                    <div className="w-1.5 h-1.5 bg-purple-500 rounded-full" />
                    Max file size: 10MB each
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// Upload Field Component
interface UploadFieldProps {
  field: string;
  requirement: {
    type: string;
    size: string;
    label: string;
    required: boolean;
  };
  onFileChange: (field: string, file: File) => Promise<void>;
  isUploaded: boolean;
  error?: string;
}

const UploadField = ({ field, requirement, onFileChange, isUploaded, error }: UploadFieldProps) => {
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      onFileChange(field, file);
    }
  };

  const handleClick = () => {
    fileInputRef.current?.click();
  };

  const getAcceptedTypesText = () => {
    if (requirement.type === '*') return 'All files';
    return requirement.type
      .split(',')
      .map(type => {
        if (type === 'image/*') return 'Images';
        if (type === '.pdf') return 'PDF';
        if (type === '.doc' || type === '.docx') return 'Word Documents';
        return type;
      })
      .join(', ');
  };

  return (
    <div>
      <input 
        type="file" 
        ref={fileInputRef}
        className="hidden" 
        onChange={handleFileSelect}
        accept={requirement.type}
        required={requirement.required}
      />
      
      <button
        type="button"
        onClick={handleClick}
        disabled={isUploaded}
        className={`w-full mt-2 px-4 py-2 rounded-xl hover:shadow-md transition-all flex items-center justify-center gap-2 border ${
          error
            ? 'border-rose-300 bg-gradient-to-r from-rose-50 to-pink-50 text-rose-700 hover:from-rose-100 hover:to-pink-100'
            : isUploaded
            ? 'border-green-300 bg-gradient-to-r from-green-50 to-emerald-50 text-green-700 cursor-not-allowed'
            : 'border-gray-300 bg-gradient-to-r from-gray-100 to-gray-200 text-gray-700 hover:shadow-md'
        }`}
      >
        <UploadCloud size={18} />
        <span>Choose File</span>
      </button>
      
      {!isUploaded && !error && (
        <p className="text-xs text-gray-500 mt-1">
          Accepted: {getAcceptedTypesText()}
        </p>
      )}
    </div>
  );
};

export default NewStudentForm;