// app/student/dashboard/foreign-students/foreign-students-list.jsx
'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Heading from '../../components/atoms/Heading';
import Swal from 'sweetalert2';
import { 
  FaSearch, 
  FaUser, 
  FaClock, 
  FaDollarSign, 
  FaEye,
  FaCalendarPlus,
  FaMapMarkerAlt,
  FaStar,
  FaFilter,
  FaGraduationCap,
  FaChalkboardTeacher,
  FaGlobe,
  FaChevronLeft,
  FaChevronRight
} from 'react-icons/fa';
import Image from 'next/image';

const ForeignStudentsList = () => {
  const router = useRouter();
  
  const [foreignStudents, setForeignStudents] = useState([]);
  const [filteredStudents, setFilteredStudents] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedStudent, setSelectedStudent] = useState(null);
  const [showBookingModal, setShowBookingModal] = useState(false);
  const [availabilityData, setAvailabilityData] = useState(null);
  const [selectedDate, setSelectedDate] = useState('');
  const [selectedTimeSlot, setSelectedTimeSlot] = useState(null);
  const [currentMonth, setCurrentMonth] = useState(new Date());
  const [loadingAvailability, setLoadingAvailability] = useState(false);

  // Load foreign students
  useEffect(() => {
    fetchForeignStudents();
  }, []);

  // Filter students based on search term
  useEffect(() => {
    if (searchTerm.trim() === '') {
      setFilteredStudents(foreignStudents);
    } else {
      const filtered = foreignStudents.filter(student =>
        student.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        (student.country_name && student.country_name.toLowerCase().includes(searchTerm.toLowerCase())) ||
        (student.experience && student.experience.toLowerCase().includes(searchTerm.toLowerCase())) ||
        (student.last_education && student.last_education.toLowerCase().includes(searchTerm.toLowerCase()))
      );
      setFilteredStudents(filtered);
    }
  }, [searchTerm, foreignStudents]);

  const fetchForeignStudents = async () => {
    try {
      setIsLoading(true);
      const response = await fetch('/api/frontend/userdashboard/foreign-students', {
        method: 'GET',
        credentials: 'include'
      });

      if (response.ok) {
        const data = await response.json();
        if (data.success && data.students) {
          setForeignStudents(data.students);
          setFilteredStudents(data.students);
        }
      }
    } catch (error) {
      console.error('Error fetching foreign students:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const fetchStudentAvailability = async (studentId, month = null) => {
    try {
      setLoadingAvailability(true);
      const monthParam = month ? month.toISOString().split('T')[0] : '';
      const response = await fetch(`/api/frontend/userdashboard/foreign-student-availability/${studentId}?month=${monthParam}`, {
        method: 'GET',
        credentials: 'include'
      });

      if (response.ok) {
        const data = await response.json();
        return data;
      }
      return null;
    } catch (error) {
      console.error('Error fetching availability:', error);
      return null;
    } finally {
      setLoadingAvailability(false);
    }
  };

  const handleViewDetails = (student) => {
    setSelectedStudent(student);
  };

  const handleBookAppointment = async (student) => {
    try {
      setSelectedStudent(student);
      const availability = await fetchStudentAvailability(student.id);
      
      if (!availability || !availability.success || !availability.schedule) {
        Swal.fire({
          icon: 'error',
          title: 'Not Available',
          text: 'This foreign student has not set their availability yet.',
          confirmButtonColor: '#0B6D76'
        });
        return;
      }

      setAvailabilityData(availability);
      setCurrentMonth(new Date()); // Reset to current month
      setSelectedDate('');
      setSelectedTimeSlot(null);
      setShowBookingModal(true);
    } catch (error) {
      console.error('Error:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to load availability. Please try again.',
        confirmButtonColor: '#0B6D76'
      });
    }
  };

  const handleMonthChange = (direction) => {
    const newMonth = new Date(currentMonth);
    if (direction === 'next') {
      newMonth.setMonth(newMonth.getMonth() + 1);
    } else {
      newMonth.setMonth(newMonth.getMonth() - 1);
    }
    setCurrentMonth(newMonth);
    loadMonthAvailability(newMonth);
  };

  const loadMonthAvailability = async (month) => {
    if (!selectedStudent) return;
    
    const availability = await fetchStudentAvailability(selectedStudent.id, month);
    if (availability && availability.success) {
      setAvailabilityData(prev => ({
        ...prev,
        schedule: availability.schedule,
        specialDates: availability.specialDates,
        bookedSessions: availability.bookedSessions,
        dateRange: availability.dateRange
      }));
    }
  };

  const getDaysInMonth = () => {
    const year = currentMonth.getFullYear();
    const month = currentMonth.getMonth();
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    const days = [];
    
    // Get day of week for first day (0 = Sunday, 1 = Monday, etc.)
    const startDay = firstDay.getDay();
    
    // Add empty cells for days before first day of month
    for (let i = 0; i < startDay; i++) {
      days.push(null);
    }
    
    // Add all days of the month
    for (let i = 1; i <= lastDay.getDate(); i++) {
      const date = new Date(year, month, i);
      // Fix: Use local date string without timezone conversion
      const dateString = `${year}-${String(month + 1).padStart(2, '0')}-${String(i).padStart(2, '0')}`;
      const dayOfWeek = date.getDay();
      
      // Check if day is in the past (using local date)
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const compareDate = new Date(year, month, i);
      const isPast = compareDate < today;
      
      // Check availability
      let isAvailable = false;
      let availableSlots = [];
      
      if (availabilityData) {
        // Check weekly schedule
        const weeklySchedule = availabilityData.schedule?.find(day => day.day_of_week === dayOfWeek);
        if (weeklySchedule?.is_available && weeklySchedule.time_slots?.length > 0) {
          isAvailable = true;
          availableSlots = weeklySchedule.time_slots;
        }
        
        // Check special dates
        const specialDate = availabilityData.specialDates?.find(d => d.date === dateString);
        if (specialDate) {
          if (specialDate.type === 'available' && specialDate.time_slots?.length > 0) {
            isAvailable = true;
            availableSlots = specialDate.time_slots;
          } else if (specialDate.type === 'unavailable') {
            isAvailable = false;
            availableSlots = [];
          }
        }
        
        // Check booked sessions
        const isBooked = availabilityData.bookedSessions?.some(session => 
          session.date === dateString && 
          session.start === selectedTimeSlot?.start && 
          session.end === selectedTimeSlot?.end
        );
        
        if (isBooked) {
          isAvailable = false;
          availableSlots = availableSlots.filter(slot => 
            !(slot.start === selectedTimeSlot?.start && slot.end === selectedTimeSlot?.end)
          );
        }
      }
      
      days.push({
        date: compareDate,
        dateString,
        dayNumber: i,
        dayName: date.toLocaleDateString('en-US', { weekday: 'short' }),
        isPast,
        isAvailable,
        availableSlots,
        isToday: date.toDateString() === today.toDateString(),
        dayOfWeek: dayOfWeek
      });
    }
    
    return days;
  };

  const getMonthYearString = () => {
    return currentMonth.toLocaleDateString('en-US', {
      month: 'long',
      year: 'numeric'
    });
  };

  const handleDateSelect = (day) => {
    if (!day.isAvailable || day.isPast) return;
    
    setSelectedDate(day.dateString);
    setSelectedTimeSlot(null);
  };

  const handleTimeSlotSelect = (slot) => {
    setSelectedTimeSlot(slot);
  };

  const getTimeSlotsForSelectedDate = () => {
    if (!selectedDate || !availabilityData) return [];
    
    const selectedDateObj = new Date(selectedDate);
    const dayOfWeek = selectedDateObj.getDay();
    const dateString = selectedDate;
    
    let slots = [];
    
    // Get weekly schedule slots
    const weeklySchedule = availabilityData.schedule?.find(day => day.day_of_week === dayOfWeek);
    if (weeklySchedule?.is_available && weeklySchedule.time_slots) {
      slots = [...slots, ...weeklySchedule.time_slots.map(s => ({ ...s, type: 'weekly' }))];
    }
    
    // Get special date slots
    const specialDate = availabilityData.specialDates?.find(d => d.date === dateString);
    if (specialDate?.type === 'available' && specialDate.time_slots) {
      slots = [...slots, ...specialDate.time_slots.map(s => ({ ...s, type: 'special' }))];
    }
    
    // Remove duplicates and filter out booked slots
    const uniqueSlots = [];
    const slotMap = new Map();
    
    slots.forEach(slot => {
      const key = `${slot.start}-${slot.end}`;
      if (!slotMap.has(key)) {
        const isBooked = availabilityData.bookedSessions?.some(session => 
          session.date === dateString && 
          session.start === slot.start && 
          session.end === slot.end
        );
        
        if (!isBooked) {
          slotMap.set(key, true);
          uniqueSlots.push(slot);
        }
      }
    });
    
    // Sort by start time
    return uniqueSlots.sort((a, b) => a.start.localeCompare(b.start));
  };

  const formatDateForDisplay = (dateString) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  };

  const confirmBooking = async () => {
    if (!selectedStudent || !selectedDate || !selectedTimeSlot) {
      Swal.fire({
        icon: 'warning',
        title: 'Incomplete Selection',
        text: 'Please select a date and time slot.',
        confirmButtonColor: '#0B6D76'
      });
      return;
    }

    // Calculate amount at the time of booking
    const amount = calculateCost(selectedStudent.hour_rate, selectedTimeSlot.start, selectedTimeSlot.end);

    // Confirmation dialog
    const result = await Swal.fire({
      title: 'Confirm Booking',
      html: `
        <div class="text-left">
          <div class="flex items-center space-x-3 mb-4">
            <div class="w-10 h-10 rounded-full bg-teal-100 flex items-center justify-center">
              ${selectedStudent.profile_picture ? 
                `<img src="${getProfileImageUrl(selectedStudent.profile_picture)}" class="w-10 h-10 rounded-full object-cover" />` : 
                '<svg class="w-5 h-5 text-teal-600" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd"></path></svg>'
              }
            </div>
            <div>
              <p class="font-semibold">${selectedStudent.name}</p>
              <p class="text-sm text-gray-600">${selectedStudent.country_name || 'International Tutor'}</p>
            </div>
          </div>
          <div class="bg-gray-50 p-3 rounded-lg">
            <p class="font-medium text-gray-800 mb-2">Appointment Details:</p>
            <div class="space-y-1 text-sm">
              <div class="flex justify-between">
                <span class="text-gray-600">Date:</span>
                <span class="font-medium">${formatDateForDisplay(selectedDate)}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">Time:</span>
                <span class="font-medium">${selectedTimeSlot.start} - ${selectedTimeSlot.end}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">Duration:</span>
                <span class="font-medium">
                  ${calculateDuration(selectedTimeSlot.start, selectedTimeSlot.end)}
                </span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">Rate:</span>
                <span class="font-medium text-teal-600">$${selectedStudent.hour_rate || 0} per hour</span>
              </div>
              <div class="border-t border-gray-200 mt-2 pt-2">
                <div class="flex justify-between font-bold">
                  <span>Total Cost:</span>
                  <span>$${amount}</span>
                </div>
              </div>
            </div>
          </div>
          <p class="mt-4 text-red-600 text-sm">Are you sure you want to book this appointment? This action cannot be undone.</p>
        </div>
      `,
      icon: 'question',
      showCancelButton: true,
      confirmButtonText: 'Confirm & Pay',
      cancelButtonText: 'Cancel',
      confirmButtonColor: '#0B6D76',
      cancelButtonColor: '#6b7280',
      showLoaderOnConfirm: true,
      preConfirm: async () => {
        return await submitBooking(amount);
      }
    });

    if (result.isConfirmed) {
      Swal.fire({
        icon: 'success',
        title: 'Booking Confirmed!',
        html: `
          <div class="text-left">
            <p>Your appointment has been booked successfully.</p>
            <p class="mt-2 text-sm text-gray-600">
              We've sent a confirmation to your email. The tutor will contact you with meeting details.
            </p>
          </div>
        `,
        confirmButtonColor: '#0B6D76'
      });

      // Reset modal
      setShowBookingModal(false);
      setSelectedDate('');
      setSelectedTimeSlot(null);
      setSelectedStudent(null);
    }
  };

  const calculateDuration = (start, end) => {
    const [startHour, startMinute] = start.split(':').map(Number);
    const [endHour, endMinute] = end.split(':').map(Number);
    
    const startTotal = startHour * 60 + startMinute;
    const endTotal = endHour * 60 + endMinute;
    
    const durationMinutes = endTotal - startTotal;
    const hours = Math.floor(durationMinutes / 60);
    const minutes = durationMinutes % 60;
    
    if (hours === 0) return `${minutes} minutes`;
    if (minutes === 0) return `${hours} hour${hours > 1 ? 's' : ''}`;
    return `${hours}h ${minutes}m`;
  };

  const calculateCost = (hourRate, start, end) => {
    const [startHour, startMinute] = start.split(':').map(Number);
    const [endHour, endMinute] = end.split(':').map(Number);
    
    const startTotal = startHour * 60 + startMinute;
    const endTotal = endHour * 60 + endMinute;
    
    const durationHours = (endTotal - startTotal) / 60;
    const cost = (hourRate || 0) * durationHours;
    
    return cost.toFixed(2);
  };

  const submitBooking = async (amount) => {
    try {
      const payload = {
        foreignStudentId: selectedStudent.id,
        sessionDate: selectedDate,
        startTime: selectedTimeSlot.start,
        endTime: selectedTimeSlot.end,
        amount: parseFloat(amount) // Send amount to backend
      };

      const response = await fetch('/api/frontend/userdashboard/book-appointment', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload),
        credentials: 'include'
      });

      const data = await response.json();

      if (response.ok && data.success) {
        return data;
      } else {
        // Throw error with backend message
        throw new Error(data.message || 'Failed to book appointment');
      }
    } catch (error) {
      console.error('Error submitting booking:', error);
      
      // Show error in SweetAlert and close confirmation modal
      await Swal.fire({
        icon: 'error',
        title: 'Booking Failed',
        text: error.message || 'Failed to book appointment. Please try again.',
        confirmButtonColor: '#0B6D76'
      });
      
      // Throw error to prevent the loader from staying active
      throw error;
    }
  };

  const getProfileImageUrl = (imagePath) => {
    if (!imagePath) return null;
    if (imagePath.startsWith('http')) return imagePath;
    return `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${imagePath}`;
  };

  const getEducationIcon = (education) => {
    switch (education) {
      case 'phd': return <FaGraduationCap className="text-purple-500" />;
      case 'masters': return <FaGraduationCap className="text-blue-500" />;
      case 'bachelors': return <FaGraduationCap className="text-green-500" />;
      default: return <FaGraduationCap className="text-gray-500" />;
    }
  };

  const getEducationLabel = (education) => {
    if (!education) return 'Not specified';
    return education
      .split('_')
      .map(word => word.charAt(0).toUpperCase() + word.slice(1))
      .join(' ');
  };

  if (isLoading) {
    return (
      <div className="min-h-screen flex justify-center items-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#0B6D76] mx-auto mb-4"></div>
          <p className="text-gray-600">Loading foreign tutors...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-7xl mx-auto px-4">
        {/* Header */}
        <div className="text-center mb-8">
          <Heading level={3}>Meet Our Foreign Students</Heading>
          <p className="text-gray-600 mt-2">
            Connect with foreign students from around the world for personalized learning
          </p>
        </div>

        {/* Search Bar */}
        <div className="bg-white rounded-xl shadow-sm p-4 mb-8">
          <div className="flex flex-col md:flex-row md:items-center gap-4">
            <div className="flex-1">
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <FaSearch className="text-gray-400" />
                </div>
                <input
                  type="text"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  placeholder="Search tutors by name, country, expertise, or education..."
                  className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500 focus:border-transparent text-sm"
                />
              </div>
            </div>
            <div className="flex items-center space-x-2">
              <span className="text-sm text-gray-600 bg-gray-100 px-3 py-1 rounded-full">
                {filteredStudents.length} {filteredStudents.length === 1 ? 'Student' : 'Students'} available
              </span>
            </div>
          </div>
        </div>

        {/* Foreign Students Grid */}
        {filteredStudents.length === 0 ? (
          <div className="text-center py-16 bg-white rounded-xl shadow-sm">
            <div className="w-20 h-20 mx-auto bg-gray-100 rounded-full flex items-center justify-center mb-4">
              <FaUser className="text-gray-400 text-3xl" />
            </div>
            <h3 className="text-lg font-semibold text-gray-800 mb-2">No tutors found</h3>
            <p className="text-gray-600 max-w-md mx-auto">
              Try adjusting your search terms or check back later for new tutors
            </p>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {filteredStudents.map(student => {
              const profileImageUrl = getProfileImageUrl(student.profile_picture);
              
              return (
                <div key={student.id} className="bg-white rounded-xl shadow-sm overflow-hidden border border-gray-200 hover:shadow-md transition-all duration-300 group">
                  {/* Profile Image Section */}
                  <div className="relative h-48 overflow-hidden bg-gradient-to-br from-teal-50 to-blue-50">
                    {profileImageUrl ? (
                      <Image
                        src={profileImageUrl}
                        alt={student.name}
                        fill
                        className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                      />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center">
                        <div className="w-24 h-24 rounded-full bg-gradient-to-br from-teal-100 to-blue-100 flex items-center justify-center">
                          <FaUser className="text-teal-600 text-4xl" />
                        </div>
                      </div>
                    )}
                    <div className="absolute top-4 right-4">
                      <span className="px-3 py-1 bg-white/90 backdrop-blur-sm text-teal-700 text-sm font-medium rounded-full shadow-sm">
                        ${student.hour_rate || 0}/hr
                      </span>
                    </div>
                  </div>

                  {/* Content Section */}
                  <div className="p-5">
                    <div className="mb-4">
                      <h3 className="font-bold text-gray-800 text-lg mb-1">{student.name}</h3>
                      {student.country_name && (
                        <div className="flex items-center text-sm text-gray-600 mb-2">
                          <FaGlobe className="mr-2 text-teal-500" />
                          {student.country_name}
                        </div>
                      )}
                    </div>

                    {/* Education Badge */}
                    {student.last_education && (
                      <div className="flex items-center mb-3">
                        <div className="mr-2">
                          {getEducationIcon(student.last_education)}
                        </div>
                        <span className="text-xs font-medium text-gray-700 bg-gray-100 px-2 py-1 rounded">
                          {getEducationLabel(student.last_education)}
                        </span>
                      </div>
                    )}

                    {/* Experience Preview */}
                    {student.experience && (
                      <div className="mb-4">
                        <div className="flex items-center text-sm text-gray-600 mb-1">
                          <FaChalkboardTeacher className="mr-2 text-teal-500" />
                          <span className="font-medium">Experience</span>
                        </div>
                        <p className="text-sm text-gray-600 line-clamp-2">{student.experience}</p>
                      </div>
                    )}

                    {/* Action Buttons - Improved Layout */}
                    <div className="flex flex-col space-y-2">
                      <button
                        onClick={() => handleViewDetails(student)}
                        className="w-full px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors flex items-center justify-center"
                      >
                        <FaEye className="mr-2" />
                        View Profile
                      </button>
                      <button
                        onClick={() => handleBookAppointment(student)}
                        className="w-full px-4 py-2 text-sm font-medium text-white bg-gradient-to-r from-teal-500 to-teal-600 hover:from-teal-600 hover:to-teal-700 rounded-lg transition-all shadow-sm hover:shadow flex items-center justify-center"
                      >
                        <FaCalendarPlus className="mr-2" />
                        Book Session
                      </button>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}

        {/* Student Details Modal */}
        {selectedStudent && (
          <div className="fixed inset-0 bg-black/70 bg-opacity-50 flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
              <div className="p-6">
                <div className="flex justify-between items-start mb-6">
                  <div>
                    <h3 className="text-xl font-bold text-gray-800">{selectedStudent.name}</h3>
                    <p className="text-gray-600">Foreign Student Profile</p>
                  </div>
                  <button
                    onClick={() => setSelectedStudent(null)}
                    className="text-gray-400 hover:text-gray-600 text-xl transition-colors"
                  >
                    &times;
                  </button>
                </div>

                <div className="space-y-6">
                  {/* Profile Section */}
                  <div className="flex flex-col md:flex-row gap-6 items-start">
                    <div className="flex-shrink-0">
                      {getProfileImageUrl(selectedStudent.profile_picture) ? (
                        <img
                          src={getProfileImageUrl(selectedStudent.profile_picture)}
                          alt={selectedStudent.name}
                          className="w-32 h-32 rounded-xl object-cover border-4 border-white shadow"
                        />
                      ) : (
                        <div className="w-32 h-32 rounded-xl bg-gradient-to-br from-teal-100 to-blue-100 flex items-center justify-center border-4 border-white shadow">
                          <FaUser className="text-teal-600 text-4xl" />
                        </div>
                      )}
                    </div>
                    <div className="flex-1">
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div className="bg-gradient-to-r from-teal-50 to-teal-100 p-4 rounded-lg">
                          <p className="text-sm text-teal-700 font-medium">Hourly Rate</p>
                          <p className="text-3xl font-bold text-teal-800 mt-1">
                            ${selectedStudent.hour_rate || 0}<span className="text-base font-normal text-teal-600">/hour</span>
                          </p>
                        </div>
                        <div className="bg-gray-50 p-4 rounded-lg">
                          <p className="text-sm text-gray-600 font-medium">Country</p>
                          <p className="text-lg font-medium text-gray-800 mt-1 flex items-center">
                            <FaGlobe className="mr-2 text-teal-500" />
                            {selectedStudent.country_name || 'International'}
                          </p>
                        </div>
                        {selectedStudent.last_education && (
                          <div className="bg-gray-50 p-4 rounded-lg">
                            <p className="text-sm text-gray-600 font-medium">Education</p>
                            <p className="text-lg font-medium text-gray-800 mt-1 flex items-center">
                              {getEducationIcon(selectedStudent.last_education)}
                              <span className="ml-2">{getEducationLabel(selectedStudent.last_education)}</span>
                            </p>
                          </div>
                        )}
                        {selectedStudent.gender && (
                          <div className="bg-gray-50 p-4 rounded-lg">
                            <p className="text-sm text-gray-600 font-medium">Gender</p>
                            <p className="text-lg font-medium text-gray-800 mt-1 capitalize">
                              {selectedStudent.gender}
                            </p>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>

                  {/* About Me */}
                  {selectedStudent.about_me && (
                    <div className="bg-gray-50 p-5 rounded-xl">
                      <h4 className="font-semibold text-gray-800 mb-3 flex items-center">
                        <FaUser className="mr-2 text-teal-500" />
                        About Me
                      </h4>
                      <p className="text-gray-600 whitespace-pre-line">{selectedStudent.about_me}</p>
                    </div>
                  )}

                  {/* Experience */}
                  {selectedStudent.experience && (
                    <div className="bg-gray-50 p-5 rounded-xl">
                      <h4 className="font-semibold text-gray-800 mb-3 flex items-center">
                        <FaChalkboardTeacher className="mr-2 text-teal-500" />
                        Experience
                      </h4>
                      <p className="text-gray-600 whitespace-pre-line">{selectedStudent.experience}</p>
                    </div>
                  )}

                </div>

                <div className="mt-8 flex flex-col sm:flex-row justify-end space-y-3 sm:space-y-0 sm:space-x-3">
                  <button
                    onClick={() => setSelectedStudent(null)}
                    className="px-6 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors"
                  >
                    Close
                  </button>
                  <button
                    onClick={() => {
                      setSelectedStudent(null);
                      handleBookAppointment(selectedStudent);
                    }}
                    className="px-6 py-2 text-sm font-medium text-white bg-gradient-to-r from-teal-500 to-teal-600 hover:from-teal-600 hover:to-teal-700 rounded-lg transition-all shadow-sm hover:shadow flex items-center justify-center"
                  >
                    <FaCalendarPlus className="mr-2" />
                    Book a Session
                  </button>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Booking Modal */}
        {showBookingModal && selectedStudent && (
          <div className="fixed inset-0 bg-black/70 bg-opacity-50 flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-2xl max-w-6xl w-full max-h-[90vh] overflow-y-auto">
              <div className="p-6">
                <div className="flex justify-between items-start mb-6">
                  <div>
                    <h3 className="text-xl font-bold text-gray-800">
                      Book Session with {selectedStudent.name}
                    </h3>
                    <p className="text-gray-600">Select your preferred date and time</p>
                  </div>
                  <button
                    onClick={() => {
                      setShowBookingModal(false);
                      setSelectedDate('');
                      setSelectedTimeSlot(null);
                    }}
                    className="text-gray-400 hover:text-gray-600 text-xl transition-colors"
                  >
                    &times;
                  </button>
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                  {/* Tutor Info Sidebar */}
                  <div className="lg:col-span-1">
                    <div className="bg-gradient-to-br from-teal-50 to-blue-50 rounded-xl p-5 border border-teal-100">
                      <div className="flex items-center space-x-3 mb-4">
                        {getProfileImageUrl(selectedStudent.profile_picture) ? (
                          <img
                            src={getProfileImageUrl(selectedStudent.profile_picture)}
                            alt={selectedStudent.name}
                            className="w-14 h-14 rounded-full object-cover border-2 border-white shadow"
                          />
                        ) : (
                          <div className="w-14 h-14 rounded-full bg-teal-100 flex items-center justify-center">
                            <FaUser className="text-teal-600" />
                          </div>
                        )}
                        <div>
                          <h4 className="font-semibold text-gray-800">{selectedStudent.name}</h4>
                          <div className="flex items-center text-sm text-teal-600">
                            <FaDollarSign />
                            <span className="ml-1">{selectedStudent.hour_rate || 0}/hour</span>
                          </div>
                        </div>
                      </div>
                      
                      {selectedStudent.country_name && (
                        <div className="flex items-center text-sm text-gray-600 mb-3">
                          <FaMapMarkerAlt className="mr-2 text-teal-500" />
                          {selectedStudent.country_name}
                        </div>
                      )}
                      
                      {selectedStudent.last_education && (
                        <div className="flex items-center text-sm text-gray-600 mb-3">
                          {getEducationIcon(selectedStudent.last_education)}
                          <span className="ml-2">{getEducationLabel(selectedStudent.last_education)}</span>
                        </div>
                      )}
                      
                      {/* Selected Appointment Summary */}
                      {selectedDate && selectedTimeSlot && (
                        <div className="mt-6 p-4 bg-white rounded-lg border border-teal-200 shadow-sm">
                          <p className="font-medium text-gray-800 mb-3">Selected Appointment</p>
                          <div className="space-y-2 text-sm">
                            <div className="flex justify-between">
                              <span className="text-gray-600">Date:</span>
                              <span className="font-medium">
                                {new Date(selectedDate).toLocaleDateString('en-US', { 
                                  weekday: 'short',
                                  month: 'short', 
                                  day: 'numeric' 
                                })}
                              </span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-gray-600">Time:</span>
                              <span className="font-medium">
                                {selectedTimeSlot.start} - {selectedTimeSlot.end}
                              </span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-gray-600">Duration:</span>
                              <span className="font-medium">
                                {calculateDuration(selectedTimeSlot.start, selectedTimeSlot.end)}
                              </span>
                            </div>
                            <div className="border-t border-gray-200 pt-2 mt-2">
                              <div className="flex justify-between font-semibold">
                                <span>Total Cost:</span>
                                <span className="text-teal-600">
                                  ${calculateCost(selectedStudent.hour_rate, selectedTimeSlot.start, selectedTimeSlot.end)}
                                </span>
                              </div>
                            </div>
                          </div>
                        </div>
                      )}
                    </div>
                  </div>

                  {/* Calendar & Time Selection */}
                  <div className="lg:col-span-2">
                    {/* Month Navigation */}
                    <div className="flex items-center justify-between mb-6">
                      <button
                        onClick={() => handleMonthChange('prev')}
                        className="flex items-center text-gray-600 hover:text-teal-600 px-3 py-2 rounded-lg hover:bg-gray-100 transition-colors"
                      >
                        <FaChevronLeft className="mr-2" />
                        Previous Month
                      </button>
                      <h4 className="text-lg font-semibold text-gray-800">
                        {getMonthYearString()}
                      </h4>
                      <button
                        onClick={() => handleMonthChange('next')}
                        className="flex items-center text-gray-600 hover:text-teal-600 px-3 py-2 rounded-lg hover:bg-gray-100 transition-colors"
                      >
                        Next Month
                        <FaChevronRight className="ml-2" />
                      </button>
                    </div>

                    {/* Calendar Grid */}
                    <div className="mb-8">
                      <div className="grid grid-cols-7 gap-1 mb-2">
                        {['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map(day => (
                          <div key={day} className="text-center text-sm font-medium text-gray-500 py-2">
                            {day}
                          </div>
                        ))}
                      </div>
                      
                      {loadingAvailability ? (
                        <div className="text-center py-12">
                          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-teal-600 mx-auto mb-3"></div>
                          <p className="text-gray-600">Loading availability...</p>
                        </div>
                      ) : (
                        <div className="grid grid-cols-7 gap-1">
                          {getDaysInMonth().map((day, index) => (
                            <div key={index} className="min-h-24">
                              {day ? (
                                <button
                                  onClick={() => handleDateSelect(day)}
                                  disabled={!day.isAvailable || day.isPast}
                                  className={`
                                    w-full h-full p-2 rounded-lg border text-left transition-all
                                    ${day.isToday ? 'border-teal-300 bg-teal-50' : 'border-gray-200'}
                                    ${selectedDate === day.dateString 
                                      ? '!border-teal-500 !bg-teal-50 !ring-2 !ring-teal-200' 
                                      : ''
                                    }
                                    ${day.isAvailable && !day.isPast
                                      ? 'hover:border-teal-300 hover:bg-gray-50 cursor-pointer'
                                      : 'cursor-not-allowed opacity-50'
                                    }
                                    ${day.isPast ? 'bg-gray-100 text-gray-400' : ''}
                                  `}
                                >
                                  <div className="flex justify-between items-start">
                                    <span className={`
                                      text-sm font-medium
                                      ${day.isToday ? 'text-teal-700' : 
                                        selectedDate === day.dateString ? 'text-teal-700' : 
                                        'text-gray-700'
                                      }
                                    `}>
                                      {day.dayNumber}
                                    </span>
                                    {day.isToday && (
                                      <span className="text-xs bg-teal-500 text-white px-1 rounded">
                                        Today
                                      </span>
                                    )}
                                  </div>
                                  
                                  <div className="text-xs text-gray-500 mt-1">
                                    {day.dayName}
                                  </div>
                                  
                                  {day.isAvailable && !day.isPast && (
                                    <div className="mt-2">
                                      <div className="text-xs text-teal-600 font-medium">
                                        Available
                                      </div>
                                      <div className="text-xs text-gray-500 mt-1">
                                        {day.availableSlots.length} slot{day.availableSlots.length !== 1 ? 's' : ''}
                                      </div>
                                    </div>
                                  )}
                                  
                                  {!day.isAvailable && !day.isPast && (
                                    <div className="mt-2 text-xs text-gray-400">
                                      Unavailable
                                    </div>
                                  )}
                                </button>
                              ) : (
                                <div className="w-full h-full p-2 bg-gray-50 rounded-lg"></div>
                              )}
                            </div>
                          ))}
                        </div>
                      )}
                    </div>

                    {/* Time Slots for Selected Date */}
                    {selectedDate && (
                      <div>
                        <h4 className="font-semibold text-gray-800 mb-4">
                          Available Time Slots for {formatDateForDisplay(selectedDate)}
                        </h4>
                        {getTimeSlotsForSelectedDate().length > 0 ? (
                          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
                            {getTimeSlotsForSelectedDate().map((slot, index) => (
                              <button
                                key={index}
                                onClick={() => handleTimeSlotSelect(slot)}
                                className={`
                                  p-4 rounded-xl border text-center transition-all hover:shadow-md
                                  ${selectedTimeSlot?.start === slot.start && selectedTimeSlot?.end === slot.end
                                    ? 'border-teal-500 bg-teal-50 ring-2 ring-teal-200'
                                    : 'border-gray-200 hover:border-teal-300 hover:bg-gray-50'
                                  }
                                `}
                              >
                                <div className="font-medium text-gray-800">
                                  {slot.start} - {slot.end}
                                </div>
                                <div className="text-sm text-gray-500 mt-1">
                                  {calculateDuration(slot.start, slot.end)}
                                </div>
                                <div className="text-xs text-gray-400 mt-2">
                                  {slot.type === 'special' ? 'Special Hours' : 'Regular Hours'}
                                </div>
                              </button>
                            ))}
                          </div>
                        ) : (
                          <div className="text-center py-8 bg-gray-50 rounded-xl">
                            <FaClock className="mx-auto text-gray-300 text-4xl mb-3" />
                            <p className="text-gray-500">No time slots available for this date</p>
                            <p className="text-sm text-gray-400 mt-1">
                              Please select another date with available slots
                            </p>
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                </div>

                {/* Booking Actions */}
                <div className="mt-8 flex flex-col sm:flex-row justify-end space-y-3 sm:space-y-0 sm:space-x-3">
                  <button
                    onClick={() => {
                      setShowBookingModal(false);
                      setSelectedDate('');
                      setSelectedTimeSlot(null);
                    }}
                    className="px-6 py-3 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors"
                  >
                    Cancel
                  </button>
                  <button
                    onClick={confirmBooking}
                    disabled={!selectedDate || !selectedTimeSlot || loadingAvailability}
                    className={`
                      px-6 py-3 text-sm font-medium text-white rounded-lg transition-all shadow-sm
                      ${!selectedDate || !selectedTimeSlot || loadingAvailability
                        ? 'bg-gray-400 cursor-not-allowed'
                        : 'bg-gradient-to-r from-teal-500 to-teal-600 hover:from-teal-600 hover:to-teal-700 hover:shadow'
                      }
                    `}
                  >
                    {loadingAvailability ? (
                      <span className="flex items-center justify-center">
                        <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                        Loading...
                      </span>
                    ) : (
                      <span className="flex items-center justify-center">
                        <FaCalendarPlus className="mr-2" />
                        Confirm Booking
                      </span>
                    )}
                  </button>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default ForeignStudentsList;