"use client";

import { useState, useEffect, useCallback } from "react";
import { Eye, CheckSquare, Square, Download, X } from "lucide-react";
import Pagination from "../../components/Pagination";
import Swal from 'sweetalert2';
import { useParams } from "next/navigation";
import Layout from "../../components/Layout";
import Image from "next/image";

const ConsultantStudentsList = () => {

  const { id } = useParams(); // Get consultant ID from URL params

  const [students, setStudents] = useState([]);
  const [loading, setLoading] = useState(true);
  
  // Filter states
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  
  // Applied filters state
  const [appliedSearchTerm, setAppliedSearchTerm] = useState("");
  const [appliedStatusFilter, setAppliedStatusFilter] = useState("");
  const [appliedStartDate, setAppliedStartDate] = useState("");
  const [appliedEndDate, setAppliedEndDate] = useState("");

  const [selectedStudent, setSelectedStudent] = useState(null);
  const [showDocumentsModal, setShowDocumentsModal] = useState(false);
  const [showStatusModal, setShowStatusModal] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(15);
  const [totalItems, setTotalItems] = useState(0);
  const [totalPages, setTotalPages] = useState(1);

  // Status update state
  const [statusUpdates, setStatusUpdates] = useState({});

  // Reset to first page when applied filters change
  useEffect(() => {
    setCurrentPage(1);
  }, [appliedSearchTerm, appliedStatusFilter, appliedStartDate, appliedEndDate]);

  const fetchStudents = useCallback(async () => {
  setLoading(true);
  try {
    const params = new URLSearchParams({
      page: currentPage.toString(),
      limit: itemsPerPage.toString(),
      consultant_id: id.toString(), // Add consultant ID to params
    });

    if (appliedSearchTerm) {
      params.append("search", appliedSearchTerm);
    }
    if (appliedStatusFilter) {
      params.append("status", appliedStatusFilter);
    }
    if (appliedStartDate) {
      params.append("start_date", appliedStartDate);
    }
    if (appliedEndDate) {
      params.append("end_date", appliedEndDate);
    }

    const response = await fetch(`/api/internal/consultant-students?${params.toString()}`);
    
    if (!response.ok) {
      throw new Error('Failed to fetch students');
    }
    
    const data = await response.json();
    
    if (data.success) {
      setStudents(data.students || []);
      setTotalItems(data.meta?.totalItems || 0);
      setTotalPages(data.meta?.totalPages || 1);
    } else {
      setStudents([]);
      setTotalItems(0);
      setTotalPages(1);
    }
  } catch (error) {
    console.error("Fetch error:", error);
    Swal.fire({
      icon: "error",
      title: "Error",
      text: "Failed to fetch students",
    });
    setStudents([]);
    setTotalItems(0);
    setTotalPages(1);
  } finally {
    setLoading(false);
  }
}, [currentPage, appliedSearchTerm, appliedStatusFilter, appliedStartDate, appliedEndDate, itemsPerPage, id]); // Add consultantId to dependencies

  useEffect(() => {
    fetchStudents();
  }, [fetchStudents]);

  const handleSearch = () => {
    setAppliedSearchTerm(searchTerm);
    setAppliedStatusFilter(statusFilter);
    setAppliedStartDate(startDate);
    setAppliedEndDate(endDate);
  };

  const clearFilters = () => {
    setSearchTerm("");
    setStatusFilter("");
    setStartDate("");
    setEndDate("");
    setAppliedSearchTerm("");
    setAppliedStatusFilter("");
    setAppliedStartDate("");
    setAppliedEndDate("");
  };

  const hasActiveFilters = appliedSearchTerm || appliedStatusFilter || appliedStartDate || appliedEndDate;

  const formatDate = (dateString) => {
    if (!dateString) return 'N/A';
    try {
      const date = new Date(dateString);
      return date.toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
      });
    } catch (e) {
      return 'N/A';
    }
  };

  const openDocumentsModal = (student) => {
    setSelectedStudent(student);
    setShowDocumentsModal(true);
  };

  const openStatusModal = (student) => {
    setSelectedStudent(student);
    // Initialize status updates with current student status
    setStatusUpdates({
      initial_documents_assessment: student.intial_documents_assessment === "on",
      course_finalization: student.course_finalaztion === "on",
      application_submitted: student.application_submitted === "on",
      got_admission: student.got_admission === "on",
      visa_applied: student.visa_applied === "on",
      case_closed: student.case_closed === "on",
    });
    setShowStatusModal(true);
  };

  const handleStatusChange = (stage, checked) => {
    setStatusUpdates(prev => ({
      ...prev,
      [stage]: checked
    }));
  };

  const updateStudentStatus = async () => {
    try {

      const updateData = {
        studentId: selectedStudent.id, // Add student ID to the request body
        ...statusUpdates // Spread the status updates
      };

      const response = await fetch(`/api/internal/consultant-students`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(updateData),
      });
      
      if (!response.ok) throw new Error("Failed to update status");
      
      const result = await response.json();
      
      if (result.success) {
        Swal.fire({
          icon: 'success',
          title: 'Success!',
          text: 'Student status updated successfully.',
          confirmButtonColor: '#0B6D76',
        });
        setShowStatusModal(false);
        fetchStudents(); // Refresh the list
      }
    } catch (error) {
      console.error("Status update error:", error);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: 'Failed to update student status.',
        confirmButtonColor: '#0B6D76',
      });
    }
  };

  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + students.length;

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 to-cyan-100 flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-[#0B6D76]"></div>
      </div>
    );
  }

  return (
    <>
    <Layout>
    <div className="space-y-6 p-6 bg-gradient-to-br from-blue-50 to-cyan-100 min-h-screen">
      {/* Header */}
      <div className="flex flex-col md:flex-row justify-between items-center mb-8 gap-4">
        <div className="text-center md:text-left">
          <h1 className="text-3xl font-bold text-gray-900">Consultant Students</h1>
          <p className="text-gray-600 mt-2">Manage all student applications</p>
        </div>
        <button
          onClick={() => setIsFilterOpen(!isFilterOpen)}
          className={`px-4 py-2 rounded-lg transition-colors flex items-center gap-2 ${
            isFilterOpen 
              ? 'bg-[#0B6D76] text-white' 
              : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
          }`}
        >
          🔍 Filters
          {hasActiveFilters && (
            <span className="ml-1 px-2 py-1 bg-white text-[#0B6D76] text-xs rounded-full">
              {[appliedSearchTerm, appliedStatusFilter, appliedStartDate, appliedEndDate].filter(Boolean).length}
            </span>
          )}
        </button>
      </div>

      {/* Filter Section */}
      {isFilterOpen && (
        <div className="bg-white rounded-2xl shadow-xl p-6 mb-6">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Search Students</label>
              <input
                type="text"
                placeholder="Search by name, passport, course..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && handleSearch()}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              />
            </div>
            
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Start Date</label>
              <input
                type="date"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">End Date</label>
              <input
                type="date"
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              />
            </div>
          </div>
          
          <div className="flex justify-between items-center mt-4 pt-4 border-t border-gray-200">
            <div className="flex gap-2">
              <button
                onClick={handleSearch}
                className="px-4 py-2 bg-[#0B6D76] text-white rounded-lg hover:bg-[#085a61] transition-colors flex items-center gap-2"
              >
                🔍 Search
              </button>
              {hasActiveFilters && (
                <button
                  onClick={clearFilters}
                  className="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors"
                >
                  Clear Filters
                </button>
              )}
            </div>
            
            {/* Active Filters Display */}
            {hasActiveFilters && (
              <div className="text-sm text-gray-600 flex flex-wrap gap-2">
                Active filters: 
                {appliedSearchTerm && <span className="px-2 py-1 bg-blue-100 text-blue-800 rounded">Search: &quot;{appliedSearchTerm}&quot;</span>}
                {appliedStatusFilter && <span className="px-2 py-1 bg-green-100 text-green-800 rounded">Status: {appliedStatusFilter}</span>}
                {appliedStartDate && <span className="px-2 py-1 bg-purple-100 text-purple-800 rounded">Start: {formatDate(appliedStartDate)}</span>}
                {appliedEndDate && <span className="px-2 py-1 bg-orange-100 text-orange-800 rounded">End: {formatDate(appliedEndDate)}</span>}
              </div>
            )}
          </div>
        </div>
      )}

      {/* Table */}
      <div className="bg-white rounded-2xl shadow-xl p-6 overflow-x-auto">
        <table className="w-full min-w-[1000px]">
          <thead className="sticky top-0 bg-gradient-to-r from-blue-50 to-cyan-50 z-10">
            <tr>
              <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900 rounded-l-xl">#</th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900">Name</th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900">Passport</th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900">Course</th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900">Country</th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900">Created At</th>
              <th className="px-6 py-4 text-center text-sm font-semibold text-gray-900 rounded-r-xl">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-200">
            {students.map((student, index) => (
              <tr key={student.id} className="hover:bg-gray-50 transition-colors">
                <td className="px-6 py-4 text-gray-600">{startIndex + index + 1}</td>
                <td className="px-6 py-4 font-medium text-gray-900">{student.name}</td>
                <td className="px-6 py-4 text-gray-600">{student.passport_number}</td>
                <td className="px-6 py-4 text-gray-600">{student.course_doc}</td>
                <td className="px-6 py-4 text-gray-600">{student.intrested_country_doc}</td>
                <td className="px-6 py-4 text-sm text-gray-500">
                  {formatDate(student.created_at)}
                </td>
                <td className="px-6 py-4 text-center">
                  <div className="flex justify-center gap-2">
                    <button
                      onClick={() => openDocumentsModal(student)}
                      className="p-2 text-blue-600 hover:bg-blue-100 rounded-lg transition-colors"
                      title="View Documents"
                    >
                      <Eye className="w-4 h-4" />
                    </button>
                    <button
                      onClick={() => openStatusModal(student)}
                      className="p-2 text-green-600 hover:bg-green-100 rounded-lg transition-colors"
                      title="Update Status"
                    >
                      <CheckSquare className="w-4 h-4" />
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>

        {students.length === 0 && (
          <div className="text-center py-12">
            <div className="text-gray-500 text-lg">
              {hasActiveFilters ? 'No students found matching your filters.' : 'No students available.'}
            </div>
            <p className="text-gray-400 mt-2">
              {hasActiveFilters ? 'Try adjusting your search criteria or clear filters' : 'No student records have been created yet'}
            </p>
            {hasActiveFilters && (
              <button
                onClick={clearFilters}
                className="mt-4 px-4 py-2 bg-[#0B6D76] text-white rounded-lg hover:bg-[#085a61] transition-colors"
              >
                Clear all filters
              </button>
            )}
          </div>
        )}

        {/* Pagination */}
        {totalPages > 1 && (
          <Pagination
            currentPage={currentPage}
            totalPages={totalPages}
            onPageChange={setCurrentPage}
            totalItems={totalItems}
            startIndex={startIndex + 1}
            endIndex={endIndex}
          />
        )}
      </div>

      {/* Documents Modal */}
      {showDocumentsModal && selectedStudent && (
        <DocumentsModal
          student={selectedStudent}
          onClose={() => setShowDocumentsModal(false)}
        />
      )}

      {/* Status Update Modal */}
      {showStatusModal && selectedStudent && (
        <StatusUpdateModal
          student={selectedStudent}
          statusUpdates={statusUpdates}
          onStatusChange={handleStatusChange}
          onUpdate={updateStudentStatus}
          onClose={() => setShowStatusModal(false)}
        />
      )}
    </div>
    </Layout>
    </>
  );
};

// Documents Modal Component (Reuse your existing one)
const DocumentsModal = ({ student, onClose }) => {
  const getDocumentUrl = (filePath) => {
    if (!filePath) return null;
    return `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${filePath}`;
  };

  const handleDownload = async (filePath, documentName) => {
    try {
      const url = getDocumentUrl(filePath);
      const response = await fetch(url);
      const blob = await response.blob();
      const downloadUrl = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = downloadUrl;
      a.download = `${documentName}_${student.name}.${filePath.split('.').pop()}`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(downloadUrl);
    } catch (error) {
      console.error('Download error:', error);
      alert('Failed to download document');
    }
  };

  const documents = [
    {
      label: 'Passport',
      field: 'passport_doc',
      file: student.passport_doc,
      required: true
    },
    {
      label: 'Photo',
      field: 'photo_doc',
      file: student.photo_doc,
      required: true
    },
    {
      label: 'Educational Degree',
      field: 'educational_degree_doc',
      file: student.educational_degree_doc,
      required: true
    },
    {
      label: 'Educational Certificate',
      field: 'educational_certificate_doc',
      file: student.educational_certificate_doc,
      required: true
    },
    {
      label: 'Recommendation Letter',
      field: 'recomendation_letter_doc',
      file: student.recomendation_letter_doc,
      required: false
    },
    {
      label: 'Study Plan',
      field: 'study_plan',
      file: student.study_plan,
      required: false
    },
    {
      label: 'IELTS/English Proficiency',
      field: 'ielts_english_proficiency_letter',
      file: student.ielts_english_proficiency_letter,
      required: false
    }
  ];

  return (
    <div className="fixed inset-0 bg-black/70 bg-opacity-50 flex items-center justify-center p-4 z-50">
      <div className="bg-white rounded-lg max-w-6xl w-full max-h-[95vh] overflow-y-auto">
        <div className="p-6">
          {/* Header */}
          <div className="flex justify-between items-center mb-6">
            <div>
              <h3 className="text-2xl font-bold text-gray-900">
                Documents - {student.name}
              </h3>
              <p className="text-gray-600 mt-1">
                Passport: {student.passport_number} | Course: {student.course_doc}
              </p>
            </div>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600 text-2xl p-2 hover:bg-gray-100 rounded-full transition-colors"
            >
              <X size={24} />
            </button>
          </div>

          {/* Required Documents */}
          <div className="mb-8">
            <h4 className="text-lg font-semibold text-gray-900 mb-4 pb-2 border-b">
              Required Documents
            </h4>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {documents
                .filter(doc => doc.required)
                .map((document) => (
                  <DocumentCard
                    key={document.field}
                    document={document}
                    student={student}
                    onDownload={handleDownload}
                  />
                ))}
            </div>
          </div>

          {/* Additional Documents */}
          {documents.filter(doc => !doc.required && doc.file).length > 0 && (
            <div className="mb-8">
              <h4 className="text-lg font-semibold text-gray-900 mb-4 pb-2 border-b">
                Additional Documents
              </h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {documents
                  .filter(doc => !doc.required && doc.file)
                  .map((document) => (
                    <DocumentCard
                      key={document.field}
                      document={document}
                      student={student}
                      onDownload={handleDownload}
                    />
                  ))}
              </div>
            </div>
          )}

          {/* Close Button */}
          <div className="mt-6 flex justify-end">
            <button
              onClick={onClose}
              className="px-6 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors font-medium"
            >
              Close
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};
const DocumentCard = ({ document, student, onDownload }) => {

  const documentUrl = `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${document.file}`;
  const fileExtension = document.file?.split('.').pop()?.toLowerCase();
  const isImage = ['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(fileExtension);
  const isPDF = fileExtension === 'pdf';

  return (
    <div className="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
      <div className="flex justify-between items-start mb-3">
        <h5 className="font-medium text-gray-900">
          {document.label}
          {!document.required && (
            <span className="ml-2 text-xs text-gray-500">(Optional)</span>
          )}
        </h5>
        <button
          onClick={() => onDownload(document.file, document.label)}
          className="p-1 text-blue-600 hover:bg-blue-100 rounded transition-colors"
          title="Download Document"
        >
          <Download size={16} />
        </button>
      </div>

      <div className="space-y-3">
        {isImage ? (
          <div className="relative w-full h-48 rounded border border-gray-300 overflow-hidden">
            <Image
              src={documentUrl}
              alt={document.label}
              fill
              className="object-cover"
              onError={(e) => {
                const target = e.target as HTMLImageElement;
                target.style.display = 'none';
                // Show error message
                const errorDiv = document.createElement('div');
                errorDiv.className = 'absolute inset-0 flex items-center justify-center bg-gray-100';
                errorDiv.innerHTML = '<span class="text-gray-500 text-sm">Image not available</span>';
                target.parentNode?.appendChild(errorDiv);
              }}
            />
          </div>
        ) : isPDF ? (
          <div className="w-full h-48 bg-red-50 border border-red-200 rounded flex flex-col items-center justify-center">
            <div className="text-red-500 text-center">
              <div className="text-2xl font-bold">PDF</div>
              <div className="text-sm mt-2">Document File</div>
            </div>
          </div>
        ) : (
          <div className="w-full h-48 bg-gray-100 border border-gray-300 rounded flex items-center justify-center">
            <div className="text-gray-500 text-center">
              <div className="text-lg font-medium uppercase">{fileExtension}</div>
              <div className="text-sm mt-2">Document File</div>
            </div>
          </div>
        )}

        <div className="text-xs text-gray-500 truncate" title={document.file}>
          File: {document.file?.split('/').pop() || 'No file'}
        </div>
      </div>
    </div>
  );
};

// Status Update Modal Component
import { FileText, BookOpen, Send, GraduationCap, Plane, FolderCheck, CheckCircle,} from 'lucide-react';

const StatusUpdateModal = ({ student, statusUpdates, onStatusChange, onUpdate, onClose }) => {

  // Create proper stage array from student data
  const stageData = [
    { 
      key: 'initial_documents_assessment',
      label: 'Initial Documents Assessment',
      icon: <FileText size={20} />,
      value: statusUpdates.initial_documents_assessment
    },
    { 
      key: 'course_finalization',
      label: 'Course Finalization', 
      icon: <BookOpen size={20} />,
      value: statusUpdates.course_finalization
    },
    { 
      key: 'application_submitted',
      label: 'Application Submitted',
      icon: <Send size={20} />,
      value: statusUpdates.application_submitted
    },
    { 
      key: 'got_admission',
      label: 'Got Admission',
      icon: <GraduationCap size={20} />,
      value: statusUpdates.got_admission
    },
    { 
      key: 'visa_applied',
      label: 'Visa Applied',
      icon: <Plane size={20} />,
      value: statusUpdates.visa_applied
    },
    { 
      key: 'case_closed',
      label: 'Case Closed',
      icon: <FolderCheck size={20} />,
      value: statusUpdates.case_closed
    }
  ];

  // Count completed stages for progress bar
  const completedStages = stageData.filter(stage => stage.value === true).length;

  const progressPercentage = (completedStages / stageData.length) * 100;

  return (
    <div className="fixed inset-0 bg-black/70 bg-opacity-50 flex items-center justify-center p-4 z-50">
      <div className="bg-white rounded-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        <div className="p-6">
          {/* Header */}
          <div className="flex justify-between items-center mb-6">
            <div>
              <h2 className="text-2xl font-bold text-gray-900">Update Application Status</h2>
              <p className="text-gray-600">Update progress for {student.name}</p>
            </div>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600 text-2xl p-2 hover:bg-gray-100 rounded-full transition-colors"
            >
              <X size={24} />
            </button>
          </div>

          {/* Student Information */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6 p-4 bg-blue-50 rounded-lg">
            <div>
              <label className="text-sm font-medium text-gray-600">Name:</label>
              <p className="text-lg font-semibold text-gray-900">{student.name || 'N/A'}</p>
            </div>
            <div>
              <label className="text-sm font-medium text-gray-600">Passport Number:</label>
              <p className="text-lg font-semibold text-gray-900">{student.passport_number || 'N/A'}</p>
            </div>
            <div>
              <label className="text-sm font-medium text-gray-600">Course:</label>
              <p className="text-lg font-semibold text-gray-900">{student.course_doc || 'N/A'}</p>
            </div>
            <div>
              <label className="text-sm font-medium text-gray-600">Country:</label>
              <p className="text-lg font-semibold text-gray-900">{student.intrested_country_doc || 'N/A'}</p>
            </div>
          </div>

          {/* Progress Visualization */}
          <div className="mb-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">
              Current Progress
            </h3>
            <p className="text-sm text-gray-600 mb-4">
              <span className="text-green-600 font-medium">Green steps</span> indicate completed stages.
              Click on stages below to update status.
            </p>
            
            {/* Progress Bar */}
            <div className="w-full py-6">
              <div className="relative">
                {/* Progress Line */}
                <div className="absolute top-5 left-0 right-0 h-1 bg-gray-200 rounded-full">
                  <div 
                    className="h-1 bg-green-500 rounded-full transition-all duration-500"
                    style={{ 
                      width: `${progressPercentage}%` 
                    }}
                  />
                </div>
                
                {/* Stages */}
                <div className="relative flex justify-between">
                  {stageData.map((stage, index) => {
                    const isActive = stage.value === true;
                    
                    return (
                      <div key={stage.key} className="flex flex-col items-center">
                        <button
                          onClick={() => onStatusChange(stage.key, !stage.value)}
                          className={`
                            relative flex items-center justify-center w-10 h-10 rounded-full border-2 z-10
                            cursor-pointer transition-all duration-300
                            ${isActive 
                              ? 'bg-green-500 border-green-600 text-white shadow-lg hover:bg-green-600' 
                              : 'bg-white border-gray-300 text-gray-400 hover:bg-gray-100'
                            }
                          `}
                        >
                          {isActive ? <CheckCircle size={20} /> : stage.icon}
                        </button>
                        <span className={`
                          mt-2 text-xs font-medium text-center max-w-24
                          ${isActive ? 'text-green-600' : 'text-gray-500'}
                        `}>
                          {stage.label}
                        </span>
                        <span className="text-xs text-gray-400 mt-1">
                          {index + 1}
                        </span>
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>
          </div>

          {/* Stage Status Controls */}
          <div className="p-4 bg-gray-50 rounded-lg mb-6">
            <h4 className="font-semibold text-gray-900 mb-4">Stage Controls</h4>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
              {stageData.map((stage) => (
                <div key={stage.key} className="flex items-center justify-between p-3 bg-white rounded-lg border border-gray-200">
                  <label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                    {stage.icon}
                    {stage.label}
                  </label>
                  <button
                    onClick={() => onStatusChange(stage.key, !stage.value)}
                    className={`p-2 rounded-lg border-2 transition-all duration-200 ${
                      stage.value 
                        ? 'bg-green-500 border-green-600 text-white hover:bg-green-600' 
                        : 'bg-white border-gray-300 text-gray-400 hover:bg-gray-50 hover:border-gray-400'
                    }`}
                  >
                    {stage.value ? <CheckSquare size={18} /> : <Square size={18} />}
                  </button>
                </div>
              ))}
            </div>
          </div>

          {/* Progress Summary */}
          <div className="p-4 bg-green-50 rounded-lg mb-6">
            <div className="flex justify-between items-center">
              <div>
                <h4 className="font-semibold text-gray-900">Progress Summary</h4>
                <p className="text-sm text-gray-600">
                  {completedStages} of {stageData.length} stages completed
                </p>
              </div>
              <div className="text-right">
                <span className="text-2xl font-bold text-green-600">
                  {Math.round(progressPercentage)}%
                </span>
                <p className="text-xs text-gray-500">Complete</p>
              </div>
            </div>
            <div className="w-full bg-gray-200 rounded-full h-2 mt-2">
              <div 
                className="bg-green-500 h-2 rounded-full transition-all duration-500"
                style={{ width: `${progressPercentage}%` }}
              />
            </div>
          </div>

          {/* Action Buttons */}
          <div className="flex justify-end space-x-3 pt-4 border-t">
            <button
              onClick={onClose}
              className="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors font-medium"
            >
              Cancel
            </button>
            <button
              onClick={onUpdate}
              className="px-6 py-2 bg-[#0B6D76] text-white rounded-lg hover:bg-[#085a61] transition-colors font-medium"
            >
              Update Status
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ConsultantStudentsList;