'use client';

import React, { useState, useEffect, useRef } from 'react';
import { 
  BookOpen, CheckCircle, ChevronRight, Download, FileText, FolderCheck, 
  GraduationCap, MoreVertical, Plane, Search, Send, UploadCloud, User, 
  X, Filter, Eye, Edit, BarChart3, Calendar, Globe, FileCheck, AlertCircle,
  RefreshCw, Loader2, Info
} from 'lucide-react';
import { FaUser, FaPassport, FaDiscourse, FaBuilding, FaRegClock } from "react-icons/fa";
import Image from 'next/image';
import { motion, AnimatePresence } from 'framer-motion';

// ✅ Utility helper – shared across the file
const isStageActive = (value: unknown): boolean => {
  if (typeof value === 'boolean') return value;
  if (typeof value === 'string') {
    return value === 'on' || value === 'true' || value === '1';
  }
  return false;
};


interface StudentApplication {
  id: number;
  name: string;
  passport_number: string;
  course_doc: string;
  intrested_country_doc: string;
  passport_doc: string;
  photo_doc: string;
  educational_degree_doc: string;
  educational_certificate_doc: string;
  recomendation_letter_doc: string;
  study_plan: string;
  ielts_english_proficiency_letter: string;
  status: 'pending' | 'approved' | 'rejected';
  created_at: string;
  // Application stages from API
  intial_documents_assessment: string;
  course_finalaztion: string;
  application_submitted: string;
  got_admission: string;
  visa_applied: string;
  case_closed: string;
}

interface StudentReport {
  id: number;
  name: string;
  passport_number: string;
  course_doc: string;
  intrested_country_doc: string;
  status: 'pending' | 'approved' | 'rejected';
  // Application stages
  intial_documents_assessment: string;
  course_finalaztion: string;
  application_submitted: string;
  got_admission: string;
  visa_applied: string;
  case_closed: string;
  current_stage: string;
  created_at: string;
  updated_at: string;
}

interface ValidationError {
  field: string;
  message: string;
}

interface UploadProgress {
  [field: string]: {
    progress: number;
    fileName: string;
  };
}

interface FormErrors {
  [field: string]: string;
}

// Custom Input Component with real-time validation
const EditInput = ({ 
  icon, 
  type, 
  placeholder, 
  value, 
  onChange, 
  onBlur,
  name, 
  required = false, 
  error = '',
  validate = () => '',
  showError = false
}: any) => {
  const [localError, setLocalError] = useState('');

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newValue = e.target.value;
    onChange(name, newValue);
    
    if (localError || error) {
      setLocalError('');
    }
  };

  const handleBlur = (e: React.FocusEvent<HTMLInputElement>) => {
    if (validate) {
      const validationError = validate(value);
      if (validationError && showError) {
        setLocalError(validationError);
      }
    }
    if (onBlur) onBlur(name);
  };




  const displayError = showError ? (error || localError) : '';

  return (
    <div className="space-y-1">
      <div className="relative group">
        <div className={`absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none transition-colors ${
          displayError ? 'text-rose-500' : 'text-gray-500 group-focus-within:text-[#0B6D76]'
        }`}>
          {icon}
        </div>
        <input
          type={type}
          name={name}
          value={value}
          onChange={handleChange}
          onBlur={handleBlur}
          className={`w-full pl-10 pr-3 py-3 border rounded-lg focus:ring-3 transition-all duration-200 bg-white ${
            displayError 
              ? 'border-rose-300 focus:ring-rose-500/20 focus:border-rose-500' 
              : 'border-gray-300 focus:ring-[#0B6D76]/20 focus:border-[#0B6D76] hover:border-gray-400'
          }`}
          placeholder={placeholder}
          required={required}
        />
      </div>
      {displayError && (
        <div className="flex items-start gap-1">
          <AlertCircle size={14} className="text-rose-500 mt-0.5 flex-shrink-0" />
          <p className="text-rose-600 text-xs">{displayError}</p>
        </div>
      )}
    </div>
  );
};

// Edit Upload Field Component
const EditUploadField = ({ 
  label, 
  field, 
  currentFile, 
  onFileChange, 
  onRemove,
  progress,
  error = '',
  required = false,
  accept = '*',
  showError = false
}: any) => {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [localError, setLocalError] = useState('');

  const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setLocalError('');
      await onFileChange(field, file);
    }
  };

  const handleClick = () => {
    fileInputRef.current?.click();
  };

  const handleRemove = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setLocalError('');
    onRemove(field);
  };

  const getFileExtension = (fileName: string) => {
    const ext = fileName.split('.').pop()?.toLowerCase();
    return ext || '';
  };

  const isImageFile = (fileName: string) => {
    const ext = getFileExtension(fileName);
    return ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp'].includes(ext);
  };

  const isDocumentFile = (fileName: string) => {
    const ext = getFileExtension(fileName);
    return ['pdf', 'doc', 'docx', 'txt', 'rtf', 'csv'].includes(ext);
  };

  const renderPreview = () => {
    if (!currentFile) return null;
    
    const fileName = currentFile.split('/').pop() || '';
    const previewUrl = `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${currentFile}`;
    
    if (isImageFile(fileName)) {
      return (
        <div className="relative w-full h-40 rounded-lg overflow-hidden border border-gray-300 bg-gray-100">
          <Image
            src={previewUrl}
            alt={label}
            fill
            className="object-contain"
            unoptimized
            onError={(e) => {
              const target = e.target as HTMLImageElement;
              target.style.display = 'none';
              target.parentElement!.innerHTML = `
                <div class="flex items-center justify-center w-full h-full">
                  <div class="text-center">
                    <div class="mx-auto mb-2 text-gray-400">
                      <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/><path d="M16 13H8"/><path d="M16 17H8"/><path d="M10 9H8"/></svg>
                    </div>
                    <p class="text-sm font-medium text-gray-700 truncate px-2">${fileName}</p>
                    <p class="text-xs text-gray-500">Image File</p>
                  </div>
                </div>
              `;
            }}
          />
        </div>
      );
    } else {
      return (
        <div className="flex items-center justify-center w-full h-40 bg-gray-100 rounded-lg border border-gray-300">
          <div className="text-center">
            <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="text-gray-400 mx-auto mb-2">
              <path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/>
              <polyline points="14 2 14 8 20 8"/>
              <path d="M16 13H8"/>
              <path d="M16 17H8"/>
              <path d="M10 9H8"/>
            </svg>
            <p className="text-sm font-medium text-gray-700 truncate px-2">{fileName}</p>
            <p className="text-xs text-gray-500">
              {isDocumentFile(fileName) ? 'Document File' : 'File'}
            </p>
          </div>
        </div>
      );
    }
  };

  const displayError = showError ? (error || localError) : '';

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between">
        <label className="text-sm font-medium text-gray-700 flex items-center">
          {label} {required && <span className="text-red-500 ml-1">*</span>}
        </label>
      </div>
      
      <div className="space-y-2">
        {currentFile && !progress && renderPreview()}
        
        {progress ? (
          <div className="bg-gradient-to-r from-blue-50 to-cyan-50 rounded-xl border border-blue-200 p-4">
            <div className="flex items-center justify-between mb-2">
              <span className="text-sm font-medium text-blue-700 flex items-center gap-1">
                <Loader2 size={14} className="animate-spin" />
                Uploading...
              </span>
              <span className="text-sm font-bold text-blue-700">{progress.progress}%</span>
            </div>
            <div className="w-full bg-blue-100 rounded-full h-2">
              <div 
                className="h-full bg-gradient-to-r from-blue-500 to-cyan-600 rounded-full transition-all duration-300"
                style={{ width: `${progress.progress}%` }}
              />
            </div>
            <p className="text-xs text-blue-600 mt-2 truncate">{progress.fileName}</p>
          </div>
        ) : (
          <div className={`flex items-center bg-gradient-to-r from-gray-50 to-white rounded-xl border overflow-hidden transition-all duration-200 group ${
            displayError ? 'border-rose-300' : 'border-gray-300 hover:border-[#0B6D76]'
          }`}>
            <div className={`flex-1 px-4 py-3.5 truncate text-sm ${
              displayError ? 'text-rose-700' : 'text-gray-700'
            }`}>
              {currentFile ? currentFile.split('/').pop() : 'No file chosen'}
            </div>
            <button
              type="button"
              onClick={handleClick}
              className={`flex bg-gradient-to-r from-[#0B6D76] to-[#0071E8] text-white px-5 py-3.5 font-medium text-sm cursor-pointer transition-all duration-200 items-center space-x-2 hover:opacity-90 ${
                displayError ? 'opacity-90' : ''
              }`}
              title={currentFile ? 'Change file' : 'Upload file'}
            >
              <UploadCloud size={18} />
              <span>{currentFile ? 'Change' : 'Upload'}</span>
            </button>
            <input 
              type="file" 
              ref={fileInputRef}
              className="hidden" 
              onChange={handleFileSelect}
              accept={accept}
            />
          </div>
        )}
        
        {displayError && (
          <div className="flex items-start gap-1">
            <AlertCircle size={14} className="text-rose-500 mt-0.5 flex-shrink-0" />
            <p className="text-rose-600 text-xs">{displayError}</p>
          </div>
        )}
        
        {!currentFile && !displayError && (
          <div className="flex items-center gap-1 text-xs text-gray-500">
            <Info size={12} />
            <span>Accepted: Images, PDF, DOC, DOCX, TXT, CSV (Max 10MB)</span>
          </div>
        )}
      </div>
    </div>
  );
};

// Document Modal Component
const DocumentModal = ({ 
  isOpen, 
  onClose, 
  application 
}: { 
  isOpen: boolean; 
  onClose: () => void; 
  application: StudentApplication | null;
}) => {
  if (!isOpen || !application) return null;

  const documents = [
    { label: 'Passport', field: application.passport_doc, type: 'image' },
    { label: 'Photo', field: application.photo_doc, type: 'image' },
    { label: 'Educational Degree', field: application.educational_degree_doc, type: 'document' },
    { label: 'Educational Certificate', field: application.educational_certificate_doc, type: 'document' },
    { label: 'Recommendation Letter', field: application.recomendation_letter_doc, type: 'document' },
    { label: 'Study Plan', field: application.study_plan, type: 'document' },
    { label: 'IELTS/English Proficiency', field: application.ielts_english_proficiency_letter, type: 'document' },
  ].filter(doc => doc.field && doc.field !== "None" && doc.field !== "null");

  const handleDownload = async (field: string, label: string) => {
    try {
      const fileName = field.split('/').pop() || `${label}_document`;
      const previewUrl = `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${field}`;
      
      console.log('Downloading from:', previewUrl);
      console.log('File name:', fileName);
      
      // Create a temporary anchor element
      const a = document.createElement('a');
      a.href = previewUrl;
      a.download = fileName;
      a.target = '_blank';
      
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      
    } catch (error) {
      console.error('Download failed:', error);
      alert('Failed to download file. Please try opening the file directly.');
      
      const previewUrl = `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${field}`;
      window.open(previewUrl, '_blank');
    }
  };

  const handleOpenInNewTab = (field: string) => {
    const previewUrl = `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${field}`;
    window.open(previewUrl, '_blank');
  };

  return (
    <AnimatePresence>
      {isOpen && (
        <div className="fixed inset-0 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4 z-50">
          <motion.div 
            className="bg-white rounded-2xl max-w-6xl w-full max-h-[90vh] overflow-y-auto shadow-2xl"
            initial={{ opacity: 0, scale: 0.9, y: 20 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.9, y: 20 }}
            transition={{ type: "spring", damping: 25 }}
          >
            <div className="p-8">
              <div className="flex justify-between items-center mb-8">
                <div>
                  <h3 className="text-2xl font-bold text-gray-900">
                    Documents for <span className="bg-gradient-to-r from-[#0B6D76] to-[#0071E8] bg-clip-text text-transparent">{application.name}</span>
                  </h3>
                  <p className="text-gray-600 mt-1">View all submitted documents</p>
                </div>
                <motion.button
                  onClick={onClose}
                  className="text-gray-400 hover:text-gray-600 text-2xl p-2 hover:bg-gray-100 rounded-full transition-all duration-200"
                  whileHover={{ rotate: 90 }}
                  whileTap={{ scale: 0.9 }}
                >
                  <X size={24} />
                </motion.button>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {documents.map((doc, index) => {
                  const previewUrl = `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${doc.field}`;
                  const fileName = doc.field.split('/').pop() || 'Unknown file';
                  
                  return (
                    <motion.div
                      key={index}
                      initial={{ opacity: 0, y: 20 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: index * 0.1 }}
                      className="bg-gradient-to-br from-gray-50 to-white rounded-2xl border border-gray-200 overflow-hidden hover:shadow-lg transition-all duration-300"
                    >
                      <div className="p-5">
                        <div className="flex items-center justify-between mb-4">
                          <h4 className="font-semibold text-gray-900 truncate">{doc.label}</h4>
                          <div className="w-10 h-10 bg-gradient-to-r from-[#0B6D76] to-[#0071E8] rounded-lg flex items-center justify-center flex-shrink-0">
                            {doc.type === 'image' ? (
                              <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="text-white">
                                <rect width="18" height="18" x="3" y="3" rx="2" ry="2"/>
                                <circle cx="9" cy="9" r="2"/>
                                <path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/>
                              </svg>
                            ) : (
                              <FileText size={20} className="text-white" />
                            )}
                          </div>
                        </div>
                        
                        <div className="aspect-square relative rounded-lg overflow-hidden border border-gray-300 bg-gray-100">
                          {doc.type === 'image' ? (
                            <Image 
                              src={previewUrl}
                              alt={doc.label}
                              fill
                              className="object-contain hover:scale-105 transition-transform duration-300"
                              unoptimized
                              onError={(e) => {
                                const target = e.target as HTMLImageElement;
                                target.style.display = 'none';
                                target.parentElement!.innerHTML = `
                                  <div class="flex items-center justify-center w-full h-full">
                                    <div class="text-center">
                                      <div class="mx-auto mb-2 text-gray-400">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/><path d="M16 13H8"/><path d="M16 17H8"/><path d="M10 9H8"/></svg>
                                      </div>
                                      <p class="text-sm font-medium text-gray-700 truncate px-2">${fileName}</p>
                                    </div>
                                  </div>
                                `;
                              }}
                            />
                          ) : (
                            <div className="flex items-center justify-center w-full h-full">
                              <div className="text-center">
                                <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="text-gray-400 mx-auto mb-2">
                                  <path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/>
                                  <polyline points="14 2 14 8 20 8"/>
                                  <path d="M16 13H8"/>
                                  <path d="M16 17H8"/>
                                  <path d="M10 9H8"/>
                                </svg>
                                <p className="text-sm font-medium text-gray-700 truncate px-2">{fileName}</p>
                                <p className="text-xs text-gray-500">Document File</p>
                              </div>
                            </div>
                          )}
                        </div>
                        
                        <div className="mt-4 flex justify-center space-x-3">
                        
                          <button 
                            onClick={() => handleOpenInNewTab(doc.field)}
                            className="flex items-center space-x-2 text-sm font-medium text-gray-700 hover:text-gray-900 transition-colors px-4 py-2 rounded-lg hover:bg-gray-100 border border-gray-300"
                          >
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                              <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>
                              <polyline points="15 3 21 3 21 9"/>
                              <line x1="10" y1="14" x2="21" y2="3"/>
                            </svg>
                            <span>Open</span>
                          </button>
                        </div>
                      </div>
                    </motion.div>
                  );
                })}
              </div>
              
              {documents.length === 0 && (
                <div className="text-center py-12">
                  <div className="w-24 h-24 mx-auto mb-6 bg-gradient-to-r from-gray-100 to-gray-200 rounded-full flex items-center justify-center">
                    <FileText className="text-gray-400" size={48} />
                  </div>
                  <h4 className="text-xl font-bold text-gray-900 mb-2">No Documents Available</h4>
                  <p className="text-gray-600">This student has not uploaded any documents yet.</p>
                </div>
              )}
            </div>
          </motion.div>
        </div>
      )}
    </AnimatePresence>
  );
};

// Report Modal Component
const ReportModal = ({ 
  isOpen, 
  onClose, 
  report 
}: { 
  isOpen: boolean; 
  onClose: () => void; 
  report: StudentReport | null;
}) => {
  if (!isOpen || !report) return null;

  const ProgressBar = ({ report }: { report: any }) => {
    const stageData = [
      { 
        key: 'intial_documents_assessment',
        label: 'Initial Assessment',
        icon: <FileText size={18} />,
        value: report.intial_documents_assessment || "off",
        description: 'Document review'
      },
      { 
        key: 'course_finalaztion',
        label: 'Course Finalized', 
        icon: <BookOpen size={18} />,
        value: report.course_finalaztion || "off",
        description: 'Program selected'
      },
      { 
        key: 'application_submitted',
        label: 'Submitted',
        icon: <Send size={18} />,
        value: report.application_submitted || "off",
        description: 'Application sent'
      },
      { 
        key: 'got_admission',
        label: 'Admission',
        icon: <GraduationCap size={18} />,
        value: report.got_admission || "off",
        description: 'Offer received'
      },
      { 
        key: 'visa_applied',
        label: 'Visa Applied',
        icon: <Plane size={18} />,
        value: report.visa_applied || "off",
        description: 'Visa processing'
      },
      { 
        key: 'case_closed',
        label: 'Case Closed',
        icon: <FolderCheck size={18} />,
        value: report.case_closed || "off",
        description: 'Completed'
      }
    ];

    const completedStages = stageData.filter(stage =>
  isStageActive(stage.value)
).length;

    
    const progressPercentage = (completedStages / stageData.length) * 100;

    return (
      <div className="w-full py-8">
        <div className="mb-6">
          <div className="flex justify-between items-center mb-2">
            <span className="text-sm font-medium text-gray-700">Application Progress</span>
            <span className="text-sm font-bold text-[#0B6D76]">{completedStages}/{stageData.length} Completed</span>
          </div>
          <div className="h-2 bg-gray-200 rounded-full overflow-hidden">
            <motion.div 
              className="h-full bg-gradient-to-r from-[#0B6D76] to-[#0071E8] rounded-full"
              initial={{ width: 0 }}
              animate={{ width: `${progressPercentage}%` }}
              transition={{ duration: 1, ease: "easeOut" }}
            />
          </div>
        </div>
        
        <div className="relative">
          <div className="absolute top-5 left-0 right-0 h-0.5 bg-gray-200">
            <div 
              className="h-0.5 bg-gradient-to-r from-[#0B6D76] to-[#0071E8] transition-all duration-1000"
              style={{ width: `${progressPercentage}%` }}
            />
          </div>
          
          <div className="relative flex justify-between gap-2">
            {stageData.map((stage, index) => {
              const value = stage.value;
              const isActive = isStageActive(stage.value);
              
              return (
                <motion.div 
                  key={stage.key} 
                  className="flex flex-col items-center"
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: index * 0.1 }}
                >
                  <motion.div 
                    className={`
                      relative flex items-center justify-center w-12 h-12 rounded-full border-2 z-10 mb-3
                      ${isActive 
                        ? 'bg-gradient-to-br from-[#0B6D76] to-[#0071E8] border-white shadow-lg shadow-[#0B6D76]/30' 
                        : 'bg-white border-gray-300 text-gray-400'
                      }
                      transition-all duration-300
                    `}
                    whileHover={{ scale: 1.1 }}
                    whileTap={{ scale: 0.95 }}
                  >
                    {isActive ? (
                      <motion.div
                        initial={{ scale: 0 }}
                        animate={{ scale: 1 }}
                        transition={{ type: "spring", stiffness: 200 }}
                      >
                        <CheckCircle size={20} className="text-white" />
                      </motion.div>
                    ) : (
                      <div className="text-gray-400">
                        {stage.icon}
                      </div>
                    )}
                  </motion.div>
                  <span className={`
                    text-xs font-semibold text-center mb-1
                    ${isActive ? 'text-[#0B6D76]' : 'text-gray-500'}
                  `}>
                    {stage.label}
                  </span>
                  <span className="text-xs text-gray-400 text-center leading-tight">
                    {stage.description}
                  </span>
                </motion.div>
              );
            })}
          </div>
        </div>
      </div>
    );
  };

  return (
    <AnimatePresence>
      {isOpen && (
        <div className="fixed inset-0 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4 z-50">
          <motion.div 
            className="bg-white rounded-2xl max-w-3xl w-full max-h-[90vh] overflow-hidden shadow-2xl"
            initial={{ opacity: 0, scale: 0.9, y: 20 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.9, y: 20 }}
            transition={{ type: "spring", damping: 25 }}
          >
            <div className="p-8">
              <div className="flex justify-between items-center mb-8">
                <div>
                  <h2 className="text-3xl font-bold text-gray-900 bg-gradient-to-r from-[#0B6D76] to-[#0071E8] bg-clip-text text-transparent">
                    Student Report
                  </h2>
                  <p className="text-gray-600 mt-1">Detailed application progress tracking</p>
                </div>
                <motion.button
                  onClick={onClose}
                  className="text-gray-400 hover:text-gray-600 text-2xl p-2 hover:bg-gray-100 rounded-full transition-all duration-200"
                  whileHover={{ rotate: 90 }}
                  whileTap={{ scale: 0.9 }}
                >
                  <X size={24} />
                </motion.button>
              </div>

              <div className="bg-gradient-to-r from-[#0B6D76]/10 to-[#0071E8]/10 rounded-2xl p-6 mb-8 border border-[#0B6D76]/20">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="space-y-4">
                    <div className="flex items-center space-x-3">
                      <div className="w-12 h-12 bg-gradient-to-br from-[#0B6D76] to-[#0071E8] rounded-xl flex items-center justify-center">
                        <User className="text-white" size={24} />
                      </div>
                      <div>
                        <label className="text-sm font-medium text-gray-600 block">Student Name</label>
                        <p className="text-xl font-bold text-gray-900">{report.name || 'N/A'}</p>
                      </div>
                    </div>
                    <div className="flex items-center space-x-3">
                      <div className="w-12 h-12 bg-gradient-to-br from-[#0071E8] to-[#0B6D76] rounded-xl flex items-center justify-center">
                        <Globe className="text-white" size={24} />
                      </div>
                      <div>
                        <label className="text-sm font-medium text-gray-600 block">Interested Country</label>
                        <p className="text-xl font-bold text-gray-900">{report.intrested_country_doc || 'N/A'}</p>
                      </div>
                    </div>
                  </div>
                  <div className="space-y-4">
                    <div className="flex items-center space-x-3">
                      <div className="w-12 h-12 bg-gradient-to-br from-[#0B6D76] to-[#0071E8] rounded-xl flex items-center justify-center">
                        <FaPassport className="text-white" size={20} />
                      </div>
                      <div>
                        <label className="text-sm font-medium text-gray-600 block">Passport Number</label>
                        <p className="text-xl font-bold text-gray-900">{report.passport_number || 'N/A'}</p>
                      </div>
                    </div>
                    <div className="flex items-center space-x-3">
                      <div className="w-12 h-12 bg-gradient-to-br from-[#0071E8] to-[#0B6D76] rounded-xl flex items-center justify-center">
                        <BookOpen className="text-white" size={24} />
                      </div>
                      <div>
                        <label className="text-sm font-medium text-gray-600 block">Course</label>
                        <p className="text-xl font-bold text-gray-900">{report.course_doc || 'N/A'}</p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <div className="mb-8">
                <div className="flex items-center justify-between mb-6">
                  <h3 className="text-xl font-bold text-gray-900">
                    Application Journey
                  </h3>
                  <div className="flex items-center space-x-2">
                    <Calendar className="text-[#0B6D76]" size={20} />
                    <span className="text-sm font-medium text-gray-700">
                      Started: {new Date(report.created_at).toLocaleDateString()}
                    </span>
                  </div>
                </div>
                
                <div className="bg-white rounded-2xl border border-gray-200 p-6 shadow-sm">
                  <ProgressBar report={report} />
                </div>
              </div>

              <div className="grid grid-cols-3 gap-4">
                <div className="bg-gradient-to-br from-[#0B6D76]/5 to-[#0B6D76]/20 p-4 rounded-xl border border-[#0B6D76]/10">
                  <div className="text-2xl font-bold text-[#0B6D76]">
                    {report.status === 'approved' ? '✓ Approved' : report.status === 'rejected' ? '✗ Rejected' : '⏳ Pending'}
                  </div>
                  <div className="text-sm text-gray-600 mt-1">Current Status</div>
                </div>
                <div className="bg-gradient-to-br from-[#0071E8]/5 to-[#0071E8]/20 p-4 rounded-xl border border-[#0071E8]/10">
                  <div className="text-2xl font-bold text-[#0071E8]">
                    {new Date(report.updated_at).toLocaleDateString()}
                  </div>
                  <div className="text-sm text-gray-600 mt-1">Last Updated</div>
                </div>
                <div className="bg-gradient-to-br from-[#0B6D76]/5 to-[#0071E8]/20 p-4 rounded-xl border border-[#0B6D76]/10">
                  <div className="text-2xl font-bold text-[#0B6D76]">
                    {(() => {
                      const stages = [
                        { key: 'intial_documents_assessment', label: 'Initial Assessment', value: report.intial_documents_assessment },
                        { key: 'course_finalaztion', label: 'Course Finalization', value: report.course_finalaztion },
                        { key: 'application_submitted', label: 'Application Submitted', value: report.application_submitted },
                        { key: 'got_admission', label: 'Got Admission', value: report.got_admission },
                        { key: 'visa_applied', label: 'Visa Applied', value: report.visa_applied },
                        { key: 'case_closed', label: 'Case Closed', value: report.case_closed }
                      ];
                      
                      for (let i = stages.length - 1; i >= 0; i--) {
  if (isStageActive(stages[i].value)) {
    return stages[i].label;
  }
}

                      
                      return 'Not Started';
                    })()}
                  </div>
                  <div className="text-sm text-gray-600 mt-1">Current Stage</div>
                </div>
              </div>
            </div>
          </motion.div>
        </div>
      )}
    </AnimatePresence>
  );
};

const StudentApplication = () => {
  const [applications, setApplications] = useState<StudentApplication[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedStatus, setSelectedStatus] = useState<string>('all');
  const [selectedApplication, setSelectedApplication] = useState<StudentApplication | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [isReportModalOpen, setIsReportModalOpen] = useState(false);
  const [studentReport, setStudentReport] = useState<StudentReport | null>(null);
  const [editFormData, setEditFormData] = useState({
    name: '',
    passportNumber: '',
    course: '',
    country: '',
  });
  const [editFiles, setEditFiles] = useState({
    passport: '',
    photo: '',
    degree: '',
    certificate: '',
    recommendation: '',
    studyPlan: '',
    ielts: '',
  });
  const [uploading, setUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState<UploadProgress>({});
  const [formErrors, setFormErrors] = useState<FormErrors>({});
  const [fileErrors, setFileErrors] = useState<FormErrors>({});
  const [submitError, setSubmitError] = useState<string>('');
  const [touchedFields, setTouchedFields] = useState<Set<string>>(new Set());
  const [isSubmitting, setIsSubmitting] = useState(false);

  const validateName = (value: string): string => {
    if (!value.trim()) return 'Name is required';
    if (value.length < 2) return 'Name must be at least 2 characters';
    if (value.length > 100) return 'Name must be less than 100 characters';
    return '';
  };

  const validatePassportNumber = (value: string): string => {
    if (!value.trim()) return 'Passport number is required';
    if (value.length < 5) return 'Passport number must be at least 5 characters';
    if (value.length > 20) return 'Passport number must be less than 20 characters';
    return '';
  };

  const validateCourse = (value: string): string => {
    if (!value.trim()) return 'Course is required';
    if (value.length < 2) return 'Course must be at least 2 characters';
    if (value.length > 100) return 'Course must be less than 100 characters';
    return '';
  };

  const validateCountry = (value: string): string => {
    if (!value.trim()) return 'Country is required';
    if (value.length < 2) return 'Country must be at least 2 characters';
    if (value.length > 50) return 'Country must be less than 50 characters';
    return '';
  };

  const validateFile = (file: File, field: string): string => {
    const maxSize = 10 * 1024 * 1024;
    
    if (file.size > maxSize) {
      return `File too large (${(file.size / (1024 * 1024)).toFixed(1)}MB). Max size: 10MB`;
    }
    
    const fileName = file.name.toLowerCase();
    const extension = fileName.split('.').pop() || '';
    
    if (field === 'passport' || field === 'photo') {
      const allowedImageTypes = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
      if (!allowedImageTypes.includes(extension)) {
        return `Only image files (${allowedImageTypes.join(', ')}) are allowed`;
      }
    } else {
      const allowedTypes = ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx', 'txt', 'csv'];
      if (!allowedTypes.includes(extension)) {
        return `Only ${allowedTypes.join(', ')} files are allowed`;
      }
    }
    
    return '';
  };

  useEffect(() => {
    fetchApplications();
  }, []);

  const fetchApplications = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/frontend/consultant/consultantdashboard/student/', {
        method: "POST"
      });
      const result = await response.json();
      
      if (result.success) {
        setApplications(result.data);
      } else {
        console.error('Failed to fetch applications:', result.message);
      }
    } catch (error) {
      console.error('Error fetching applications:', error);
    } finally {
      setLoading(false);
    }
  };

  const openReportModal = async (application: StudentApplication) => {
    setSelectedApplication(application);
    
    try {
      const response = await fetch(`/api/frontend/consultant/consultantdashboard/student/report/${application.id}`, {
        method: "POST"
      });
      const result = await response.json();
      
      console.log('Report API Response:', result);
      
      if (result.success) {
        setStudentReport({
          ...result.data,
          intial_documents_assessment: result.data.intial_documents_assessment,
          course_finalaztion: result.data.course_finalaztion,
          application_submitted: result.data.application_submitted,
          got_admission: result.data.got_admission,
          visa_applied: result.data.visa_applied,
          case_closed: result.data.case_closed,
          current_stage: result.data.current_stage || 'Not Started',
        });
        setIsReportModalOpen(true);
      } else {
        console.log('Using application data for report');
        setStudentReport({
          ...application,
          intial_documents_assessment: application.intial_documents_assessment,
          course_finalaztion: application.course_finalaztion,
          application_submitted: application.application_submitted,
          got_admission: application.got_admission,
          visa_applied: application.visa_applied,
          case_closed: application.case_closed,
          current_stage: 'Not Available',
          status: application.status,
          updated_at: application.created_at,
        });
        setIsReportModalOpen(true);
      }
    } catch (error) {
      console.error('Error fetching report:', error);
      setStudentReport({
        ...application,
        intial_documents_assessment: application.intial_documents_assessment,
        course_finalaztion: application.course_finalaztion,
        application_submitted: application.application_submitted,
        got_admission: application.got_admission,
        visa_applied: application.visa_applied,
        case_closed: application.case_closed,
        current_stage: 'Not Available',
        status: application.status,
        updated_at: application.created_at,
      });
      setIsReportModalOpen(true);
    }
  };

  const openDocumentsModal = (application: StudentApplication) => {
    setSelectedApplication(application);
    setIsModalOpen(true);
  };

  const openEditModal = (application: StudentApplication) => {
    setSelectedApplication(application);
    setFormErrors({});
    setFileErrors({});
    setSubmitError('');
    setTouchedFields(new Set());
    
    setEditFormData({
      name: application.name,
      passportNumber: application.passport_number,
      course: application.course_doc,
      country: application.intrested_country_doc,
    });

    setEditFiles({
      passport: application.passport_doc,
      photo: application.photo_doc,
      degree: application.educational_degree_doc,
      certificate: application.educational_certificate_doc,
      recommendation: application.recomendation_letter_doc || '',
      studyPlan: application.study_plan || '',
      ielts: application.ielts_english_proficiency_letter || '',
    });

    setIsEditModalOpen(true);
  };

  const closeModal = () => {
    setIsModalOpen(false);
    setIsEditModalOpen(false);
    setSelectedApplication(null);
    setEditFormData({
      name: '',
      passportNumber: '',
      course: '',
      country: '',
    });
    setEditFiles({
      passport: '',
      photo: '',
      degree: '',
      certificate: '',
      recommendation: '',
      studyPlan: '',
      ielts: '',
    });
    setFormErrors({});
    setFileErrors({});
    setSubmitError('');
    setUploadProgress({});
    setTouchedFields(new Set());
  };

  const handleEditInputChange = (field: string, value: string) => {
    setEditFormData(prev => ({
      ...prev,
      [field]: value
    }));

    if (touchedFields.has(field)) {
      let error = '';
      switch (field) {
        case 'name':
          error = validateName(value);
          break;
        case 'passportNumber':
          error = validatePassportNumber(value);
          break;
        case 'course':
          error = validateCourse(value);
          break;
        case 'country':
          error = validateCountry(value);
          break;
      }
      
      setFormErrors(prev => ({
        ...prev,
        [field]: error
      }));
    }
  };

  const handleFieldBlur = (field: string) => {
    setTouchedFields(prev => new Set(prev).add(field));
    
    const value = editFormData[field as keyof typeof editFormData];
    let error = '';
    
    switch (field) {
      case 'name':
        error = validateName(value);
        break;
      case 'passportNumber':
        error = validatePassportNumber(value);
        break;
      case 'course':
        error = validateCourse(value);
        break;
      case 'country':
        error = validateCountry(value);
        break;
    }
    
    setFormErrors(prev => ({
      ...prev,
      [field]: error
    }));
  };

  const handleEditFileChange = async (field: string, file: File) => {
    setFileErrors(prev => {
      const newErrors = { ...prev };
      delete newErrors[field];
      return newErrors;
    });

    const validationError = validateFile(file, field);
    if (validationError) {
      setFileErrors(prev => ({
        ...prev,
        [field]: validationError
      }));
      return;
    }

    setUploadProgress(prev => ({
      ...prev,
      [field]: {
        progress: 0,
        fileName: file.name
      }
    }));

    try {
      const uploadResult = await uploadFile(file, 'c-student', (progress: number) => {
        setUploadProgress(prev => ({
          ...prev,
          [field]: {
            ...prev[field],
            progress
          }
        }));
      });
      
      if (uploadResult.success) {
        setEditFiles(prev => ({
          ...prev,
          [field]: uploadResult.s3Key
        }));
        
        setTimeout(() => {
          setUploadProgress(prev => {
            const newProgress = { ...prev };
            delete newProgress[field];
            return newProgress;
          });
        }, 500);
      } else {
        throw new Error(uploadResult.message || 'Upload failed');
      }
    } catch (error) {
      console.error(`Error uploading ${field}:`, error);
      setFileErrors(prev => ({
        ...prev,
        [field]: error instanceof Error ? error.message : 'Upload failed. Please try again.'
      }));
      
      setUploadProgress(prev => {
        const newProgress = { ...prev };
        delete newProgress[field];
        return newProgress;
      });
    }
  };

  const handleRemoveFile = (field: string) => {
    setEditFiles(prev => ({
      ...prev,
      [field]: ''
    }));
    
    if (['passport', 'photo', 'degree', 'certificate'].includes(field)) {
      setFileErrors(prev => ({
        ...prev,
        [field]: `${field.charAt(0).toUpperCase() + field.slice(1)} is required`
      }));
    } else {
      setFileErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    }
  };

  const uploadFile = async (file: File, uploadType: string, onProgress?: (progress: number) => void) => {
    const formData = new FormData();
    formData.append('image', file);
    formData.append('uploadType', uploadType);

    if (onProgress) {
      onProgress(0);
      setTimeout(() => onProgress(30), 100);
      setTimeout(() => onProgress(60), 200);
      setTimeout(() => onProgress(90), 300);
    }

    const response = await fetch('/api/frontend/upload', {
      method: 'POST',
      body: formData,
    });

    const result = await response.json();
    
    if (onProgress) {
      onProgress(100);
    }

    if (!response.ok || !result.success) {
      throw new Error(result.message || 'Upload failed');
    }

    return result;
  };

  const validateForm = (): boolean => {
    const newFormErrors: FormErrors = {};
    const newFileErrors: FormErrors = {};

    const nameError = validateName(editFormData.name);
    if (nameError) newFormErrors.name = nameError;

    const passportError = validatePassportNumber(editFormData.passportNumber);
    if (passportError) newFormErrors.passportNumber = passportError;

    const courseError = validateCourse(editFormData.course);
    if (courseError) newFormErrors.course = courseError;

    const countryError = validateCountry(editFormData.country);
    if (countryError) newFormErrors.country = countryError;

    if (!editFiles.passport) newFileErrors.passport = 'Passport copy is required';
    if (!editFiles.photo) newFileErrors.photo = 'Passport photo is required';
    if (!editFiles.degree) newFileErrors.degree = 'Educational degree is required';
    if (!editFiles.certificate) newFileErrors.certificate = 'Educational certificate is required';

    setFormErrors(newFormErrors);
    setFileErrors(prev => ({ ...prev, ...newFileErrors }));

    return Object.keys(newFormErrors).length === 0 && Object.keys(newFileErrors).length === 0;
  };

  const handleEditSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitError('');
    setIsSubmitting(true);

    const allFields = ['name', 'passportNumber', 'course', 'country'];
    setTouchedFields(prev => new Set([...prev, ...allFields]));

    if (!validateForm()) {
      setIsSubmitting(false);
      return;
    }

    try {
      const updateData = {
        ...editFormData,
        files: {
          passport: editFiles.passport,
          photo: editFiles.photo,
          educationalDegree: editFiles.degree,
          educationalCertificate: editFiles.certificate,
          recommendationLetter: editFiles.recommendation || '',
          studyPlan: editFiles.studyPlan || '',
          ieltsOrEnglishProficiency: editFiles.ielts || '',
        }
      };

      const response = await fetch(`/api/frontend/consultant/consultantdashboard/student/edit/${selectedApplication?.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(updateData),
      });

      const result = await response.json();

      if (result.success) {
        alert('Student application updated successfully!');
        fetchApplications();
        closeModal();
      } else {
        if (result.errors && Array.isArray(result.errors)) {
          const newFormErrors: FormErrors = {};
          const newFileErrors: FormErrors = {};
          
          result.errors.forEach((error: ValidationError) => {
            if (error.field.startsWith('files.')) {
              const field = error.field.split('.')[1];
              newFileErrors[field] = error.message;
            } else {
              newFormErrors[error.field] = error.message;
            }
          });
          
          setFormErrors(newFormErrors);
          setFileErrors(prev => ({ ...prev, ...newFileErrors }));
          setSubmitError(result.message || 'Please fix the errors below');
        } else {
          setSubmitError(result.message || 'Failed to update application');
        }
      }
    } catch (error) {
      console.error('Error updating application:', error);
      setSubmitError('Error updating application. Please try again.');
    } finally {
      setIsSubmitting(false);
    }
  };

  const filteredApplications = applications.filter(app => {
    const matchesSearch = app.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         app.passport_number.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         app.course_doc.toLowerCase().includes(searchTerm.toLowerCase());
    
    const matchesStatus = selectedStatus === 'all' || app.status === selectedStatus;
    
    return matchesSearch && matchesStatus;
  });

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'approved': return 'bg-green-100 text-green-800 border-green-200';
      case 'rejected': return 'bg-red-100 text-red-800 border-red-200';
      default: return 'bg-yellow-100 text-yellow-800 border-yellow-200';
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 p-4 md:p-6">
      <div className="max-w-7xl mx-auto">
        <div className="mb-8">
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div>
              <h1 className="text-2xl md:text-2xl font-bold text-gray-900">
                Student <span className="bg-gradient-to-r from-[#0B6D76] to-[#0071E8] bg-clip-text text-transparent">Applications</span>
              </h1>
              <p className="text-gray-600 mt-2">Manage and track all student applications</p>
            </div>
            <div className="flex items-center space-x-2 text-sm text-gray-600 bg-white px-4 py-2 rounded-full shadow-sm">
              <FileCheck className="text-[#0B6D76]" size={18} />
              <span>Total: <span className="font-bold text-[#0B6D76]">{applications.length}</span> Applications</span>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-2xl shadow-lg p-6 mb-6">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="relative">
              <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
              <input
                type="text"
                placeholder="Search by name, passport, or course..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full pl-12 pr-4 py-3 border border-gray-300 rounded-xl focus:ring-3 focus:ring-[#0B6D76]/20 focus:border-[#0B6D76] transition-all duration-200"
              />
            </div>
            
            <div className="flex items-center space-x-4">
              <Filter className="text-gray-500" size={20} />
              <div className="flex space-x-2">
                {['all', 'pending', 'approved', 'rejected'].map((status) => (
                  <button
                    key={status}
                    onClick={() => setSelectedStatus(status)}
                    className={`px-4 py-2 rounded-lg font-medium transition-all duration-200 ${
                      selectedStatus === status
                        ? 'bg-gradient-to-r from-[#0B6D76] to-[#0071E8] text-white'
                        : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                    }`}
                  >
                    {status.charAt(0).toUpperCase() + status.slice(1)}
                  </button>
                ))}
              </div>
            </div>
            
            <div className="flex items-center justify-end">
              <button
                onClick={fetchApplications}
                className="flex items-center space-x-2 px-4 py-3 bg-gradient-to-r from-[#0B6D76] to-[#0071E8] text-white rounded-xl hover:opacity-90 transition-opacity font-medium"
              >
                <RefreshCw size={18} />
                <span>Refresh</span>
              </button>
            </div>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
          {filteredApplications.map((app) => (
            <motion.div
              key={app.id}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.3 }}
              whileHover={{ y: -5 }}
              className="bg-white rounded-2xl shadow-lg overflow-hidden border border-gray-200 hover:shadow-2xl transition-all duration-300"
            >
              <div className="p-6">
                <div className="flex justify-between items-start mb-4">
                  <div>
                    <span className="text-xs font-semibold text-gray-500">ID: #{app.id}</span>
                    <h3 className="text-xl font-bold text-gray-900 mt-1">{app.name}</h3>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4 mb-6">
                  <div className="space-y-1">
                    <div className="flex items-center text-gray-600">
                      <FaPassport className="mr-2 text-[#0B6D76]" size={14} />
                      <span className="text-sm">Passport</span>
                    </div>
                    <p className="font-semibold text-gray-900">{app.passport_number}</p>
                  </div>
                  
                  <div className="space-y-1">
                    <div className="flex items-center text-gray-600">
                      <BookOpen className="mr-2 text-[#0071E8]" size={14} />
                      <span className="text-sm">Course</span>
                    </div>
                    <p className="font-semibold text-gray-900 truncate">{app.course_doc}</p>
                  </div>
                  
                  <div className="space-y-1">
                    <div className="flex items-center text-gray-600">
                      <Globe className="mr-2 text-[#0B6D76]" size={14} />
                      <span className="text-sm">Country</span>
                    </div>
                    <p className="font-semibold text-gray-900">{app.intrested_country_doc}</p>
                  </div>
                  
                  <div className="space-y-1">
                    <div className="flex items-center text-gray-600">
                      <Calendar className="mr-2 text-[#0071E8]" size={14} />
                      <span className="text-sm">Applied</span>
                    </div>
                    <p className="font-semibold text-gray-900">
                      {new Date(app.created_at).toLocaleDateString()}
                    </p>
                  </div>
                </div>

                <div className="grid grid-cols-3 gap-2">
                  <motion.button
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    onClick={() => openDocumentsModal(app)}
                    className="flex flex-col items-center justify-center py-3 bg-gradient-to-r from-gray-50 to-white rounded-xl border border-gray-300 hover:border-[#0B6D76] hover:bg-[#0B6D76]/5 transition-all duration-200 group"
                  >
                    <Eye size={20} className="text-gray-600 group-hover:text-[#0B6D76] mb-1" />
                    <span className="text-xs font-medium text-gray-700 group-hover:text-[#0B6D76]">View</span>
                  </motion.button>
                  
                  <motion.button
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    onClick={() => openEditModal(app)}
                    className="flex flex-col items-center justify-center py-3 bg-gradient-to-r from-gray-50 to-white rounded-xl border border-gray-300 hover:border-[#0071E8] hover:bg-[#0071E8]/5 transition-all duration-200 group"
                  >
                    <Edit size={20} className="text-gray-600 group-hover:text-[#0071E8] mb-1" />
                    <span className="text-xs font-medium text-gray-700 group-hover:text-[#0071E8]">Edit</span>
                  </motion.button>
                  
                  <motion.button
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    onClick={() => openReportModal(app)}
                    className="flex flex-col items-center justify-center py-3 bg-gradient-to-r from-[#0B6D76]/10 to-[#0071E8]/10 rounded-xl border border-[#0B6D76]/20 hover:border-[#0B6D76] transition-all duration-200 group"
                  >
                    <BarChart3 size={20} className="text-[#0B6D76] mb-1" />
                    <span className="text-xs font-medium text-[#0B6D76]">Report</span>
                  </motion.button>
                </div>
              </div>
            </motion.div>
          ))}
        </div>

        {filteredApplications.length === 0 && !loading && (
          <motion.div 
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            className="text-center py-16 bg-white rounded-2xl shadow-lg"
          >
            <div className="w-24 h-24 mx-auto mb-6 bg-gradient-to-r from-[#0B6D76]/10 to-[#0071E8]/10 rounded-full flex items-center justify-center">
              <FileText className="text-[#0B6D76]" size={48} />
            </div>
            <h3 className="text-2xl font-bold text-gray-900 mb-2">No Applications Found</h3>
            <p className="text-gray-600 mb-6">Try adjusting your search or filters</p>
            <button
              onClick={() => { setSearchTerm(''); setSelectedStatus('all'); }}
              className="px-6 py-3 bg-gradient-to-r from-[#0B6D76] to-[#0071E8] text-white rounded-xl font-medium hover:opacity-90 transition-opacity"
            >
              Clear Filters
            </button>
          </motion.div>
        )}

        {loading && (
          <div className="text-center py-16">
            <div className="animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-[#0B6D76] mx-auto"></div>
            <p className="mt-4 text-gray-600 font-medium">Loading applications...</p>
          </div>
        )}

        <DocumentModal 
          isOpen={isModalOpen}
          onClose={() => setIsModalOpen(false)}
          application={selectedApplication}
        />

        <ReportModal 
          isOpen={isReportModalOpen}
          onClose={() => setIsReportModalOpen(false)}
          report={studentReport}
        />

        <AnimatePresence>
          {isEditModalOpen && selectedApplication && (
            <div className="fixed inset-0 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4 z-50">
              <motion.div 
                className="bg-white rounded-2xl max-w-4xl w-full max-h-[90vh] overflow-y-auto shadow-2xl"
                initial={{ opacity: 0, scale: 0.9, y: 20 }}
                animate={{ opacity: 1, scale: 1, y: 0 }}
                exit={{ opacity: 0, scale: 0.9, y: 20 }}
                transition={{ type: "spring", damping: 25 }}
              >
                <div className="p-8">
                  <div className="flex justify-between items-center mb-8">
                    <div>
                      <h3 className="text-2xl font-bold text-gray-900">
                        Edit <span className="bg-gradient-to-r from-[#0B6D76] to-[#0071E8] bg-clip-text text-transparent">
                          Student Application
                        </span>
                      </h3>
                      <p className="text-gray-600 mt-1">ID: #{selectedApplication.id} • {selectedApplication.name}</p>
                    </div>
                    <motion.button
                      onClick={closeModal}
                      className="text-gray-400 hover:text-gray-600 text-2xl p-2 hover:bg-gray-100 rounded-full transition-all duration-200"
                      whileHover={{ rotate: 90 }}
                      whileTap={{ scale: 0.9 }}
                      disabled={isSubmitting}
                    >
                      <X size={24} />
                    </motion.button>
                  </div>

                  {submitError && (
                    <div className="mb-6 p-4 bg-gradient-to-r from-rose-50 to-pink-50 border border-rose-200 rounded-xl">
                      <div className="flex items-center gap-3">
                        <AlertCircle size={20} className="text-rose-600" />
                        <div>
                          <h4 className="font-bold text-rose-800">Error</h4>
                          <p className="text-rose-700">{submitError}</p>
                        </div>
                      </div>
                    </div>
                  )}

                  <form onSubmit={handleEditSubmit} className="space-y-8">
                    <div className="bg-gradient-to-r from-[#0B6D76]/5 to-[#0071E8]/5 p-6 rounded-2xl">
                      <h4 className="text-lg font-bold text-gray-900 mb-4">Basic Information</h4>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <EditInput
                          icon={<FaUser size={18} />}
                          type="text"
                          placeholder="Enter Student Name"
                          value={editFormData.name}
                          onChange={handleEditInputChange}
                          onBlur={handleFieldBlur}
                          name="name"
                          required
                          error={formErrors.name}
                          validate={validateName}
                          showError={touchedFields.has('name')}
                        />
                        <EditInput
                          icon={<FaPassport size={18} />}
                          type="text"
                          placeholder="Passport Number"
                          value={editFormData.passportNumber}
                          onChange={handleEditInputChange}
                          onBlur={handleFieldBlur}
                          name="passportNumber"
                          required
                          error={formErrors.passportNumber}
                          validate={validatePassportNumber}
                          showError={touchedFields.has('passportNumber')}
                        />
                        <EditInput
                          icon={<FaDiscourse size={18} />}
                          type="text"
                          placeholder="Course"
                          value={editFormData.course}
                          onChange={handleEditInputChange}
                          onBlur={handleFieldBlur}
                          name="course"
                          required
                          error={formErrors.course}
                          validate={validateCourse}
                          showError={touchedFields.has('course')}
                        />
                        <EditInput
                          icon={<FaBuilding size={18} />}
                          type="text"
                          placeholder="Interested Country"
                          value={editFormData.country}
                          onChange={handleEditInputChange}
                          onBlur={handleFieldBlur}
                          name="country"
                          required
                          error={formErrors.country}
                          validate={validateCountry}
                          showError={touchedFields.has('country')}
                        />
                      </div>
                    </div>

                    <div className="bg-gradient-to-r from-[#0B6D76]/5 to-[#0071E8]/5 p-6 rounded-2xl">
                      <h4 className="text-lg font-bold text-gray-900 mb-4">
                        Required Documents <span className="text-red-500">*</span>
                      </h4>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <EditUploadField
                          label="Passport Copy"
                          field="passport"
                          currentFile={editFiles.passport}
                          onFileChange={handleEditFileChange}
                          onRemove={handleRemoveFile}
                          progress={uploadProgress.passport}
                          error={fileErrors.passport}
                          required
                          accept="image/*"
                          showError={true}
                        />
                        <EditUploadField
                          label="Passport Photo"
                          field="photo"
                          currentFile={editFiles.photo}
                          onFileChange={handleEditFileChange}
                          onRemove={handleRemoveFile}
                          progress={uploadProgress.photo}
                          error={fileErrors.photo}
                          required
                          accept="image/*"
                          showError={true}
                        />
                        <EditUploadField
                          label="Educational Degree"
                          field="degree"
                          currentFile={editFiles.degree}
                          onFileChange={handleEditFileChange}
                          onRemove={handleRemoveFile}
                          progress={uploadProgress.degree}
                          error={fileErrors.degree}
                          required
                          accept="image/*,.pdf,.doc,.docx,.txt,.csv"
                          showError={true}
                        />
                        <EditUploadField
                          label="Educational Certificate"
                          field="certificate"
                          currentFile={editFiles.certificate}
                          onFileChange={handleEditFileChange}
                          onRemove={handleRemoveFile}
                          progress={uploadProgress.certificate}
                          error={fileErrors.certificate}
                          required
                          accept="image/*,.pdf,.doc,.docx,.txt,.csv"
                          showError={true}
                        />
                      </div>
                    </div>

                    <div className="bg-gradient-to-r from-[#0B6D76]/5 to-[#0071E8]/5 p-6 rounded-2xl">
                      <h4 className="text-lg font-bold text-gray-900 mb-4">Additional Documents</h4>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <EditUploadField
                          label="Recommendation Letter"
                          field="recommendation"
                          currentFile={editFiles.recommendation}
                          onFileChange={handleEditFileChange}
                          onRemove={handleRemoveFile}
                          progress={uploadProgress.recommendation}
                          error={fileErrors.recommendation}
                          accept="image/*,.pdf,.doc,.docx,.txt,.csv"
                          showError={true}
                        />
                        <EditUploadField
                          label="Study Plan"
                          field="studyPlan"
                          currentFile={editFiles.studyPlan}
                          onFileChange={handleEditFileChange}
                          onRemove={handleRemoveFile}
                          progress={uploadProgress.studyPlan}
                          error={fileErrors.studyPlan}
                          accept="image/*,.pdf,.doc,.docx,.txt,.csv"
                          showError={true}
                        />
                        <EditUploadField
                          label="IELTS/English Proficiency"
                          field="ielts"
                          currentFile={editFiles.ielts}
                          onFileChange={handleEditFileChange}
                          onRemove={handleRemoveFile}
                          progress={uploadProgress.ielts}
                          error={fileErrors.ielts}
                          accept="image/*,.pdf,.doc,.docx,.txt,.csv"
                          showError={true}
                        />
                      </div>
                    </div>

                    <div className="flex justify-end space-x-4 pt-8 border-t">
                      <motion.button
                        type="button"
                        onClick={closeModal}
                        className="px-8 py-3 border border-gray-300 text-gray-700 rounded-xl hover:bg-gray-50 transition-colors font-medium"
                        whileHover={{ scale: 1.02 }}
                        whileTap={{ scale: 0.98 }}
                        disabled={isSubmitting}
                      >
                        Cancel
                      </motion.button>
                      <motion.button
                        type="submit"
                        disabled={isSubmitting}
                        className={`px-8 py-3 bg-gradient-to-r from-[#0B6D76] to-[#0071E8] text-white rounded-xl font-medium transition-all duration-200 flex items-center gap-2 ${
                          isSubmitting ? 'opacity-70 cursor-not-allowed' : 'hover:opacity-90'
                        }`}
                        whileHover={!isSubmitting ? { scale: 1.02 } : {}}
                        whileTap={!isSubmitting ? { scale: 0.98 } : {}}
                      >
                        {isSubmitting ? (
                          <>
                            <Loader2 size={18} className="animate-spin" />
                            Updating...
                          </>
                        ) : (
                          'Update Application'
                        )}
                      </motion.button>
                    </div>
                  </form>
                </div>
              </motion.div>
            </div>
          )}
        </AnimatePresence>
      </div>
    </div>
  );
};

export default StudentApplication;