'use client';

import React, { useState, useEffect } from 'react';
import Swal from 'sweetalert2';
import { 
  FaCalendarPlus,
  FaMapMarkerAlt,
  FaClock,
  FaChevronLeft,
  FaChevronRight,
  FaTimes,
  FaUser,
  FaDollarSign,
  FaLock,
  FaEnvelope,
  FaPhone,
  FaGlobe,
  FaGraduationCap,
  FaEye,
  FaEyeSlash,
  FaCheckCircle,
  FaCalendarCheck,
  FaCalendarTimes
} from 'react-icons/fa';
import { useUserStore } from '../../../store/useUserStore'; // Adjust path as needed

const BookingModal = ({ 
  student, 
  isOpen, 
  onClose,
  onBookingSuccess 
}) => {
  const { user, isLoggedIn, setUser } = useUserStore();
  
  // States for authentication
  const [isLoginForm, setIsLoginForm] = useState(true);
  const [isRegisterForm, setIsRegisterForm] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  
  // States for booking
  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);
  const [loadingAuth, setLoadingAuth] = useState(false);
  const [bookingLoading, setBookingLoading] = useState(false);
  
  // New state for booked slots
  const [bookedSlotsMap, setBookedSlotsMap] = useState({});
  
  // Registration form data
  const [formData, setFormData] = useState({
    // Login form
    email: '',
    password: '',
    
    // Registration form
    first_name: '',
    last_name: '',
    phone: '',
    phone_code: '92',
    nationality: '',
    state: '',
    city: '',
    program_type: '',
    gender: '',
    agree: false,
  });
  
  const [countries, setCountries] = useState([]);
  const [states, setStates] = useState([]);
  const [cities, setCities] = useState([]);

  // Helper function to format date to YYYY-MM-DD in LOCAL timezone
  const formatDateToLocalString = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  // Helper function to parse date string to local date
  const parseDateStringToLocal = (dateString) => {
    // If it's already in YYYY-MM-DD format, parse it directly
    if (/^\d{4}-\d{2}-\d{2}$/.test(dateString)) {
      const [year, month, day] = dateString.split('-').map(Number);
      return new Date(year, month - 1, day);
    }
    
    // If it's an ISO string, parse it and adjust to local timezone
    if (dateString.includes('T')) {
      const date = new Date(dateString);
      // Create a new date in local timezone
      return new Date(date.getFullYear(), date.getMonth(), date.getDate());
    }
    
    // Default fallback
    return new Date(dateString);
  };

  // Load countries on component mount
  useEffect(() => {
    if (isOpen) {
      loadCountries();
    }
  }, [isOpen]);

  // Fetch availability when user is logged in
  useEffect(() => {
    if (isOpen && student && isLoggedIn) {
      loadInitialAvailability();
    }
  }, [isOpen, student, isLoggedIn]);

  const loadCountries = async () => {
    try {
      const response = await fetch('/api/frontend/countries-with-phone');
      const data = await response.json();
      if (data.success) {
        setCountries(data.data);
        const pakistan = data.data.find(country => country.phonecode === '92');
        if (pakistan) {
          setFormData(prev => ({
            ...prev,
            phone_code: '92',
          }));
        }
      }
    } catch (error) {
      console.error('Error loading countries:', error);
    }
  };

  const loadStates = async (countryId) => {
    try {
      const response = await fetch(`/api/frontend/states?countryId=${countryId}`, { method: "POST" });
      const data = await response.json();
      if (data.success) {
        setStates(data.states);
      }
    } catch (error) {
      console.error('Error loading states:', error);
    }
  };

  const loadCities = async (stateId) => {
    try {
      const response = await fetch(`/api/frontend/cities?stateId=${stateId}`, { method: "POST" });
      const data = await response.json();
      if (data.success) {
        setCities(data.cities);
      }
    } catch (error) {
      console.error('Error loading cities:', error);
    }
  };

  const handleInputChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));

    if (name === 'nationality' && value) {
      loadStates(value);
      setFormData(prev => ({ 
        ...prev, 
        state: '', 
        city: '',
        phone_code: countries.find(country => country.id === value)?.phonecode || '92'
      }));
      setStates([]);
      setCities([]);
    }

    if (name === 'state' && value) {
      loadCities(value);
      setFormData(prev => ({ ...prev, city: '' }));
      setCities([]);
    }
  };

  const handleLogin = async (e) => {
    e.preventDefault();
    setLoadingAuth(true);

    try {
      const response = await fetch('/api/frontend/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: formData.email,
          password: formData.password
        }),
      });

      const data = await response.json();

      if (response.ok) {
        setUser(data.data);
        
        Swal.fire({
          title: 'Login Successful!',
          icon: 'success',
          confirmButtonColor: '#0B6D76',
          timer: 1500,
          showConfirmButton: false
        });
      } else {
        Swal.fire({
          title: 'Login Failed',
          text: data.message || 'Invalid credentials',
          icon: 'error',
          confirmButtonColor: '#0B6D76'
        });
      }
    } catch (error) {
      Swal.fire({
        title: 'Error',
        text: 'Something went wrong. Please try again.',
        icon: 'error',
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setLoadingAuth(false);
    }
  };

  const handleRegister = async (e) => {
    e.preventDefault();
    setLoadingAuth(true);

    try {
      const response = await fetch('/api/frontend/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          first_name: formData.first_name,
          last_name: formData.last_name,
          phone: `+${formData.phone_code}${formData.phone}`,
          email: formData.email,
          password: formData.password,
          confirm_password: formData.password,
          nationality: formData.nationality,
          state: formData.state,
          city: formData.city,
          program_type: formData.program_type,
          gender: formData.gender,
          agree: formData.agree
        }),
      });

      const data = await response.json();

      if (response.ok) {
        // Auto login after registration
        const loginResponse = await fetch('/api/frontend/login', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            email: formData.email,
            password: formData.password
          }),
        });

        const loginData = await loginResponse.json();

        if (loginResponse.ok) {
          setUser(loginData.data);
          
          Swal.fire({
            title: 'Registration Successful!',
            text: 'Your account has been created and you are now logged in.',
            icon: 'success',
            confirmButtonColor: '#0B6D76'
          });
        }
      } else {
        const errorMessages = data.message || {};
        
        if (typeof errorMessages === 'object') {
          const errorMessagesString = Object.values(errorMessages).join('\n');
          Swal.fire({
            icon: 'error',
            title: 'Registration Failed',
            text: errorMessagesString,
            confirmButtonColor: '#0B6D76'
          });
        } else {
          throw new Error(errorMessages);
        }
      }
    } catch (error) {
      Swal.fire({
        title: 'Error',
        text: error.message || 'Something went wrong. Please try again.',
        icon: 'error',
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setLoadingAuth(false);
    }
  };

  const loadInitialAvailability = async () => {
    try {
      setLoadingAvailability(true);
      const availability = await fetchStudentAvailability(student.id);
      setAvailabilityData(availability);
      
      // Build booked slots map with proper timezone handling
      if (availability && availability.bookedSessions) {
        buildBookedSlotsMap(availability.bookedSessions);
      }
      
      setCurrentMonth(new Date());
      setSelectedDate('');
      setSelectedTimeSlot(null);
    } catch (error) {
      console.error('Error loading availability:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to load availability. Please try again.',
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setLoadingAvailability(false);
    }
  };

  const fetchStudentAvailability = async (studentId, month = null) => {
    try {
      const monthParam = month ? formatDateToLocalString(month) : '';
      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;
    }
  };

  // Function to build a map of booked slots for quick lookup
  const buildBookedSlotsMap = (bookedSessions) => {
    const map = {};
    
    console.log('Building booked slots map from:', bookedSessions);
    
    bookedSessions.forEach(session => {
      // Parse date to local timezone
      const localDate = parseDateStringToLocal(session.date);
      const dateKey = formatDateToLocalString(localDate);
      
      const timeKey = `${session.start}-${session.end}`;
      
      console.log(`Processing: ${session.date} -> ${dateKey}, time: ${timeKey}`);
      
      if (!map[dateKey]) {
        map[dateKey] = new Set();
      }
      
      map[dateKey].add(timeKey);
    });
    
    console.log('Built booked slots map:', map);
    setBookedSlotsMap(map);
  };

  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 (!student) return;
    
    const availability = await fetchStudentAvailability(student.id, month);
    if (availability && availability.success) {
      setAvailabilityData(prev => ({
        ...prev,
        schedule: availability.schedule,
        specialDates: availability.specialDates,
        bookedSessions: availability.bookedSessions,
        dateRange: availability.dateRange
      }));
      
      // Update booked slots map
      if (availability.bookedSessions) {
        buildBookedSlotsMap(availability.bookedSessions);
      }
    }
  };

  // Check if a time slot is booked
  const isTimeSlotBooked = (dateString, slot) => {
    // Parse to local date to ensure correct comparison
    const localDate = parseDateStringToLocal(dateString);
    const formattedDate = formatDateToLocalString(localDate);
    
    if (!bookedSlotsMap[formattedDate]) {
      return false;
    }
    
    const timeKey = `${slot.start}-${slot.end}`;
    return bookedSlotsMap[formattedDate].has(timeKey);
  };

  const getDaysInMonth = () => {
    if (!availabilityData) {
      return [];
    }

    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 = [];
    
    const startDay = firstDay.getDay();
    
    // Add empty days for start of month
    for (let i = 0; i < startDay; i++) {
      days.push(null);
    }
    
    // Add days of the month
    for (let i = 1; i <= lastDay.getDate(); i++) {
      const date = new Date(year, month, i);
      const dateString = formatDateToLocalString(date);
      const dayOfWeek = date.getDay();
      
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const compareDate = new Date(year, month, i);
      const isPast = compareDate < today;
      
      let isAvailable = false;
      let availableSlots = [];
      let bookedCount = 0;
      
      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) {
          // Get weekly slots and filter out booked ones
          const weeklySlots = weeklySchedule.time_slots.filter(slot => 
            !isTimeSlotBooked(dateString, slot)
          );
          if (weeklySlots.length > 0) {
            isAvailable = true;
            availableSlots = [...availableSlots, ...weeklySlots];
          }
        }
        
        // Check special dates - parse to local for comparison
        const specialDate = availabilityData.specialDates?.find(d => {
          const specialDateLocal = parseDateStringToLocal(d.date);
          const specialDateStr = formatDateToLocalString(specialDateLocal);
          return specialDateStr === dateString;
        });
        
        if (specialDate?.type === 'available' && specialDate.time_slots) {
          // Get special slots and filter out booked ones
          const specialSlots = specialDate.time_slots.filter(slot => 
            !isTimeSlotBooked(dateString, slot)
          );
          if (specialSlots.length > 0) {
            isAvailable = true;
            availableSlots = [...availableSlots, ...specialSlots];
          }
        } else if (specialDate?.type === 'unavailable') {
          isAvailable = false;
          availableSlots = [];
        }
        
        // Count booked slots for this date
        if (bookedSlotsMap[dateString]) {
          bookedCount = bookedSlotsMap[dateString].size;
        }
      }
      
      days.push({
        date: compareDate,
        dateString,
        dayNumber: i,
        dayName: date.toLocaleDateString('en-US', { weekday: 'short' }),
        isPast,
        isAvailable,
        availableSlots,
        bookedCount,
        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 = parseDateStringToLocal(selectedDate);
    const dayOfWeek = selectedDateObj.getDay();
    const dateString = formatDateToLocalString(selectedDateObj);
    
    let slots = [];
    
    // Get weekly schedule slots
    const weeklySchedule = availabilityData.schedule?.find(day => day.day_of_week === dayOfWeek);
    if (weeklySchedule?.is_available && weeklySchedule.time_slots) {
      // Filter out booked slots
      const weeklySlots = weeklySchedule.time_slots
        .filter(slot => !isTimeSlotBooked(dateString, slot))
        .map(s => ({ ...s, type: 'weekly' }));
      slots = [...slots, ...weeklySlots];
    }
    
    // Get special date slots
    const specialDate = availabilityData.specialDates?.find(d => {
      const specialDateLocal = parseDateStringToLocal(d.date);
      const specialDateStr = formatDateToLocalString(specialDateLocal);
      return specialDateStr === dateString;
    });
    
    if (specialDate?.type === 'available' && specialDate.time_slots) {
      // Filter out booked slots
      const specialSlots = specialDate.time_slots
        .filter(slot => !isTimeSlotBooked(dateString, slot))
        .map(s => ({ ...s, type: 'special' }));
      slots = [...slots, ...specialSlots];
    }
    
    // Remove duplicates
    const uniqueSlots = [];
    const slotMap = new Map();
    
    slots.forEach(slot => {
      const key = `${slot.start}-${slot.end}`;
      if (!slotMap.has(key)) {
        slotMap.set(key, true);
        uniqueSlots.push(slot);
      }
    });
    
    return uniqueSlots.sort((a, b) => a.start.localeCompare(b.start));
  };

  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 formatDateForDisplay = (dateString) => {
    const date = parseDateStringToLocal(dateString);
    return date.toLocaleDateString('en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  };

  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 '🎓';
      case 'masters': return '🎓';
      case 'bachelors': return '🎓';
      default: return '🎓';
    }
  };

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

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

    // Double-check if the slot is still available
    const localSelectedDate = formatDateToLocalString(parseDateStringToLocal(selectedDate));
    if (isTimeSlotBooked(localSelectedDate, selectedTimeSlot)) {
      Swal.fire({
        icon: 'error',
        title: 'Slot Already Booked',
        text: 'This time slot has been booked by another user. Please select a different time.',
        confirmButtonColor: '#0B6D76'
      });
      
      // Refresh availability
      await loadMonthAvailability(currentMonth);
      setSelectedTimeSlot(null);
      return;
    }

    const amount = calculateCost(student.hour_rate, selectedTimeSlot.start, selectedTimeSlot.end);

    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">
              ${student.profile_picture ? 
                `<img src="${getProfileImageUrl(student.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">${student.name}</p>
              <p class="text-sm text-gray-600">${student.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">$${student.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 Booking',
      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'
      });

      // Update booked slots map locally
      const newBookedSlotsMap = { ...bookedSlotsMap };
      const formattedDate = formatDateToLocalString(parseDateStringToLocal(selectedDate));
      
      if (!newBookedSlotsMap[formattedDate]) {
        newBookedSlotsMap[formattedDate] = new Set();
      }
      
      newBookedSlotsMap[formattedDate].add(`${selectedTimeSlot.start}-${selectedTimeSlot.end}`);
      setBookedSlotsMap(newBookedSlotsMap);

      // Reset modal
      onClose();
      setSelectedDate('');
      setSelectedTimeSlot(null);
      
      // Notify parent component
      if (onBookingSuccess) {
        onBookingSuccess();
      }
    }
  };

  const submitBooking = async (amount) => {
    setBookingLoading(true);
    try {
      // Ensure we're sending the correct date (local date)
      const localDate = parseDateStringToLocal(selectedDate);
      const sessionDate = formatDateToLocalString(localDate);
      
      const payload = {
        foreignStudentId: student.id,
        sessionDate: sessionDate, // Send local date, not ISO string
        startTime: selectedTimeSlot.start,
        endTime: selectedTimeSlot.end,
        amount: parseFloat(amount)
      };

      console.log('Booking payload:', payload);

      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 new Error(data.message || 'Failed to book appointment');
      }
    } catch (error) {
      console.error('Error submitting booking:', error);
      
      await Swal.fire({
        icon: 'error',
        title: 'Booking Failed',
        text: error.message || 'Failed to book appointment. Please try again.',
        confirmButtonColor: '#0B6D76'
      });
      
      throw error;
    } finally {
      setBookingLoading(false);
    }
  };

  // Reset form when modal opens
  const resetForms = () => {
    setIsLoginForm(true);
    setIsRegisterForm(false);
    setFormData({
      email: '',
      password: '',
      first_name: '',
      last_name: '',
      phone: '',
      phone_code: '92',
      nationality: '',
      state: '',
      city: '',
      program_type: '',
      gender: '',
      agree: false,
    });
  };

  if (!isOpen || !student) return null;

  return (
    <div className="fixed inset-0 bg-black/70 bg-opacity-50 flex items-center justify-center z-50 p-4">
      {/* Different modal widths for authentication vs booking */}
      <div className={`bg-white rounded-2xl w-full max-h-[90vh] overflow-y-auto ${
        !isLoggedIn ? 'max-w-md' : 'max-w-6xl'
      }`}>
        <div className="p-6">
          <div className="flex justify-between items-start mb-6">
            <div>
              <h3 className="text-xl font-bold text-gray-800">
                {!isLoggedIn ? (isLoginForm ? 'Login to Book' : 'Create Account') : 'Book Session with'} {student.name}
              </h3>
              <p className="text-gray-600">
                {!isLoggedIn ? 
                  'Please login or create an account to book a session' : 
                  'Select your preferred date and time'
                }
              </p>
            </div>
            <button
              onClick={() => {
                onClose();
                resetForms();
              }}
              className="text-gray-400 hover:text-gray-600 text-xl transition-colors"
            >
              <FaTimes />
            </button>
          </div>

          {/* Authentication Forms (Show only if not logged in) */}
          {!isLoggedIn && (
            <div className="space-y-6">
              {/* Login Form */}
              {isLoginForm && (
                <form onSubmit={handleLogin} className="space-y-6">
                  <div className="space-y-4">
                    <div className="relative">
                      <FaEnvelope className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" />
                      <input
                        type="email"
                        name="email"
                        value={formData.email}
                        onChange={handleInputChange}
                        placeholder="Enter your email"
                        className="w-full pl-12 pr-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-gray-50/50 transition-all duration-200"
                        required
                      />
                    </div>
                    
                    <div className="relative">
                      <FaLock className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" />
                      <input
                        type={showPassword ? "text" : "password"}
                        name="password"
                        value={formData.password}
                        onChange={handleInputChange}
                        placeholder="Enter your password"
                        className="w-full pl-12 pr-12 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-gray-50/50 transition-all duration-200"
                        required
                      />
                      <button
                        type="button"
                        onClick={() => setShowPassword(!showPassword)}
                        className="absolute right-4 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors"
                      >
                        {showPassword ? <FaEyeSlash /> : <FaEye />}
                      </button>
                    </div>
                  </div>

                  <button
                    type="submit"
                    disabled={loadingAuth}
                    className="w-full bg-gradient-to-r from-teal-500 to-teal-600 text-white py-3 rounded-xl font-semibold hover:shadow-lg hover:scale-[1.02] transition-all duration-200 disabled:opacity-50 disabled:transform-none disabled:hover:shadow-none"
                  >
                    {loadingAuth ? (
                      <div className="flex items-center justify-center">
                        <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin mr-2"></div>
                        Logging in...
                      </div>
                    ) : (
                      'Login & Continue'
                    )}
                  </button>

                  <div className="text-center pt-4">
                    <p className="text-gray-600 text-sm">
                      Don't have an account?{' '}
                      <button
                        type="button"
                        onClick={() => {
                          setIsLoginForm(false);
                          setIsRegisterForm(true);
                        }}
                        className="text-teal-600 font-semibold hover:text-teal-700 transition-colors"
                      >
                        Create one here
                      </button>
                    </p>
                  </div>
                </form>
              )}

              {/* Registration Form */}
              {isRegisterForm && (
                <form onSubmit={handleRegister} className="space-y-4">
                  {/* First Name & Last Name */}
                  <div className="grid grid-cols-2 gap-3">
                    <div className="relative">
                      <FaUser className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 text-sm" />
                      <input
                        type="text"
                        name="first_name"
                        value={formData.first_name}
                        onChange={handleInputChange}
                        placeholder="First Name"
                        className="w-full pl-10 pr-3 py-3 text-sm border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-gray-50/50 transition-all duration-200"
                        required
                      />
                    </div>
                    <div className="relative">
                      <FaUser className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 text-sm" />
                      <input
                        type="text"
                        name="last_name"
                        value={formData.last_name}
                        onChange={handleInputChange}
                        placeholder="Last Name"
                        className="w-full pl-10 pr-3 py-3 text-sm border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-gray-50/50 transition-all duration-200"
                        required
                      />
                    </div>
                  </div>

                  {/* Phone Number */}
                  <div className="relative">
                    <FaPhone className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 text-sm" />
                    <div className="flex">
                      <select
                        name="phone_code"
                        value={formData.phone_code}
                        onChange={handleInputChange}
                        className="w-24 pl-8 pr-2 py-3 text-sm border border-gray-200 rounded-l-xl border-r-0 focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-gray-50/50 appearance-none"
                        required
                      >
                        {countries.map(country => (
                          <option key={country.id} value={country.phonecode}>
                            +{country.phonecode}
                          </option>
                        ))}
                      </select>
                      <input
                        type="tel"
                        name="phone"
                        value={formData.phone}
                        onChange={handleInputChange}
                        placeholder="Phone Number"
                        className="flex-1 pl-3 pr-3 py-3 text-sm border border-gray-200 rounded-r-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-gray-50/50 transition-all duration-200"
                        required
                      />
                    </div>
                  </div>

                  {/* Email */}
                  <div className="relative">
                    <FaEnvelope className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 text-sm" />
                    <input
                      type="email"
                      name="email"
                      value={formData.email}
                      onChange={handleInputChange}
                      placeholder="Email Address"
                      className="w-full pl-10 pr-3 py-3 text-sm border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-gray-50/50 transition-all duration-200"
                      required
                    />
                  </div>

                  {/* Password */}
                  <div className="relative">
                    <FaLock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 text-sm" />
                    <input
                      type={showPassword ? "text" : "password"}
                      name="password"
                      value={formData.password}
                      onChange={handleInputChange}
                      placeholder="Password"
                      className="w-full pl-10 pr-10 py-3 text-sm border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-gray-50/50 transition-all duration-200"
                      required
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors"
                    >
                      {showPassword ? <FaEyeSlash size={14} /> : <FaEye size={14} />}
                    </button>
                  </div>

                  {/* Country */}
                  <div className="relative">
                    <FaGlobe className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 text-sm" />
                    <select
                      name="nationality"
                      value={formData.nationality}
                      onChange={handleInputChange}
                      className="w-full pl-10 pr-3 py-3 text-sm border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-gray-50/50 appearance-none"
                      required
                    >
                      <option value="">Select Country</option>
                      {countries.map(country => (
                        <option key={country.id} value={country.id}>
                          {country.name}
                        </option>
                      ))}
                    </select>
                  </div>

                  {/* State & City */}
                  <div className="grid grid-cols-2 gap-3">
                    <div className="relative">
                      <FaMapMarkerAlt className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 text-sm" />
                      <select
                        name="state"
                        value={formData.state}
                        onChange={handleInputChange}
                        className="w-full pl-10 pr-3 py-3 text-sm border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-gray-50/50 appearance-none"
                        required
                        disabled={!formData.nationality}
                      >
                        <option value="">Select State</option>
                        {states.map(state => (
                          <option key={state.id} value={state.id}>
                            {state.name}
                          </option>
                        ))}
                      </select>
                    </div>
                    <div className="relative">
                      <FaMapMarkerAlt className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 text-sm" />
                      <select
                        name="city"
                        value={formData.city}
                        onChange={handleInputChange}
                        className="w-full pl-10 pr-3 py-3 text-sm border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-gray-50/50 appearance-none"
                        required
                        disabled={!formData.state}
                      >
                        <option value="">Select City</option>
                        {cities.map(city => (
                          <option key={city.id} value={city.id}>
                            {city.name}
                          </option>
                        ))}
                      </select>
                    </div>
                  </div>

                  {/* Gender */}
                  <div className="relative">
                    <FaUser className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 text-sm" />
                    <select
                      name="gender"
                      value={formData.gender}
                      onChange={handleInputChange}
                      className="w-full pl-10 pr-3 py-3 text-sm border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-gray-50/50 appearance-none"
                      required
                    >
                      <option value="">Select Gender</option>
                      <option value="Male">Male</option>
                      <option value="Female">Female</option>
                      <option value="Other">Other</option>
                    </select>
                  </div>

                  {/* Program Type */}
                  <div className="relative">
                    <FaGraduationCap className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 text-sm" />
                    <select
                      name="program_type"
                      value={formData.program_type}
                      onChange={handleInputChange}
                      className="w-full pl-10 pr-3 py-3 text-sm border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-gray-50/50 appearance-none"
                      required
                    >
                      <option value="">Select Program Type</option>
                      <option value="undergraduate">Undergraduate</option>
                      <option value="graduate">Graduate</option>
                      <option value="phd">PhD</option>
                      <option value="certificate">Certificate</option>
                    </select>
                  </div>

                  {/* Terms Agreement */}
                  <div className="flex items-start space-x-2 p-3 bg-blue-50 rounded-xl border border-blue-100">
                    <input
                      type="checkbox"
                      name="agree"
                      checked={formData.agree}
                      onChange={handleInputChange}
                      className="w-4 h-4 text-teal-600 border-gray-300 rounded focus:ring-teal-500 mt-1 flex-shrink-0"
                      required
                    />
                    <label className="text-xs text-gray-700">
                      I agree to the <span className="text-teal-600 font-semibold">terms and conditions</span> and <span className="text-teal-600 font-semibold">privacy policy</span>
                    </label>
                  </div>
                  
                  <div className="flex gap-3 pt-2">
                    <button
                      type="button"
                      onClick={() => {
                        setIsRegisterForm(false);
                        setIsLoginForm(true);
                      }}
                      className="flex-1 border border-gray-300 text-gray-700 py-2.5 rounded-xl font-medium hover:bg-gray-50 hover:border-gray-400 transition-all duration-200 text-sm"
                    >
                      Back to Login
                    </button>
                    <button
                      type="submit"
                      disabled={loadingAuth || !formData.agree}
                      className="flex-1 bg-gradient-to-r from-teal-500 to-teal-600 text-white py-2.5 rounded-xl font-medium hover:shadow hover:scale-[1.02] transition-all duration-200 disabled:opacity-50 disabled:transform-none disabled:hover:shadow-none text-sm"
                    >
                      {loadingAuth ? (
                        <div className="flex items-center justify-center">
                          <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2"></div>
                          Creating...
                        </div>
                      ) : (
                        'Create Account'
                      )}
                    </button>
                  </div>
                </form>
              )}
            </div>
          )}

          {/* Booking Interface (Show only if logged in) */}
          {isLoggedIn && (
            <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(student.profile_picture) ? (
                      <img
                        src={getProfileImageUrl(student.profile_picture)}
                        alt={student.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">{student.name}</h4>
                      <div className="flex items-center text-sm text-teal-600">
                        <FaDollarSign />
                        <span className="ml-1">{student.hour_rate || 0}/hour</span>
                      </div>
                    </div>
                  </div>
                  
                  {student.country_name && (
                    <div className="flex items-center text-sm text-gray-600 mb-3">
                      <FaMapMarkerAlt className="mr-2 text-teal-500" />
                      {student.country_name}
                    </div>
                  )}
                  
                  {student.last_education && (
                    <div className="flex items-center text-sm text-gray-600 mb-3">
                      <span className="mr-2">{getEducationIcon(student.last_education)}</span>
                      <span>{getEducationLabel(student.last_education)}</span>
                    </div>
                  )}
                  
                  {/* Booking Legend */}
                  <div className="mt-4 mb-4">
                    <h5 className="text-sm font-medium text-gray-700 mb-2">Booking Status:</h5>
                    <div className="space-y-2">
                      <div className="flex items-center">
                        <div className="w-3 h-3 rounded-full bg-green-500 mr-2"></div>
                        <span className="text-xs text-gray-600">Available</span>
                      </div>
                      <div className="flex items-center">
                        <div className="w-3 h-3 rounded-full bg-red-500 mr-2"></div>
                        <span className="text-xs text-gray-600">Booked</span>
                      </div>
                      <div className="flex items-center">
                        <div className="w-3 h-3 rounded-full bg-gray-300 mr-2"></div>
                        <span className="text-xs text-gray-600">Unavailable</span>
                      </div>
                    </div>
                  </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">
                            {formatDateForDisplay(selectedDate)}
                          </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(student.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 relative
                                ${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' : ''}
                              `}
                            >
                              {/* Show booked indicator */}
                              {day.bookedCount > 0 && (
                                <div className="absolute top-1 right-1 flex items-center">
                                  <span className="text-xs bg-red-100 text-red-700 px-1.5 py-0.5 rounded-full flex items-center">
                                    <FaCalendarTimes className="mr-1 text-xs" />
                                    {day.bookedCount}
                                  </span>
                                </div>
                              )}
                              
                              <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 flex items-center">
                                    <FaCalendarCheck className="mr-1" />
                                    Available
                                  </div>
                                  <div className="text-xs text-gray-500 mt-1">
                                    {day.availableSlots.length} slot{day.availableSlots.length !== 1 ? 's' : ''}
                                  </div>
                                  {day.bookedCount > 0 && (
                                    <div className="text-xs text-red-500 mt-1">
                                      {day.bookedCount} booked
                                    </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) => {
                          const isBooked = isTimeSlotBooked(selectedDate, slot);
                          
                          return (
                            <button
                              key={index}
                              onClick={() => !isBooked && handleTimeSlotSelect(slot)}
                              disabled={isBooked}
                              className={`
                                p-4 rounded-xl border text-center transition-all relative
                                ${isBooked 
                                  ? 'border-red-200 bg-red-50 cursor-not-allowed' 
                                  : 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'
                                }
                                ${!isBooked ? 'hover:shadow-md' : ''}
                              `}
                            >
                              {isBooked && (
                                <div className="absolute top-2 right-2">
                                  <span className="text-xs bg-red-500 text-white px-2 py-1 rounded-full">
                                    Booked
                                  </span>
                                </div>
                              )}
                              
                              <div className={`font-medium ${isBooked ? 'text-gray-500 line-through' : 'text-gray-800'}`}>
                                {slot.start} - {slot.end}
                              </div>
                              <div className={`text-sm mt-1 ${isBooked ? 'text-gray-400' : 'text-gray-500'}`}>
                                {calculateDuration(slot.start, slot.end)}
                              </div>
                              <div className={`text-xs mt-2 ${isBooked ? 'text-gray-400' : 'text-gray-400'}`}>
                                {slot.type === 'special' ? 'Special Hours' : 'Regular Hours'}
                              </div>
                              
                              {isBooked && (
                                <div className="mt-2 text-xs text-red-500">
                                  This slot has been booked
                                </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">
                          All slots may be booked or the tutor is unavailable
                        </p>
                      </div>
                    )}
                  </div>
                )}
              </div>
            </div>
          )}

          {/* Booking Actions (Show only if logged in) */}
          {isLoggedIn && (
            <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={() => {
                  onClose();
                  resetForms();
                }}
                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 || bookingLoading || 
                  (selectedTimeSlot && isTimeSlotBooked(selectedDate, selectedTimeSlot))}
                className={`
                  px-6 py-3 text-sm font-medium text-white rounded-lg transition-all shadow-sm
                  ${!selectedDate || !selectedTimeSlot || loadingAvailability || bookingLoading ||
                    (selectedTimeSlot && isTimeSlotBooked(selectedDate, selectedTimeSlot))
                    ? '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 || bookingLoading ? (
                  <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>
                    {bookingLoading ? 'Processing...' : 'Loading...'}
                  </span>
                ) : (
                  <span className="flex items-center justify-center">
                    <FaCalendarPlus className="mr-2" />
                    {selectedTimeSlot && isTimeSlotBooked(selectedDate, selectedTimeSlot) 
                      ? 'Slot Booked' 
                      : 'Confirm Booking'}
                  </span>
                )}
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default BookingModal;