'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Swal from 'sweetalert2';
import { 
  Calendar,
  Clock,
  User,
  DollarSign,
  Video,
  CheckCircle,
  XCircle,
  Loader2,
  AlertTriangle,
  ChevronDown,
  ChevronUp,
  Send,
  Edit,
  CalendarCheck,
  Trash2,
  MessageSquare,
  Filter,
  Eye,
  EyeOff,
  Link2,
  ExternalLink
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';

const ForeignStudentAppointments = () => {
  const router = useRouter();
  
  const [appointments, setAppointments] = useState([]);
  const [filteredAppointments, setFilteredAppointments] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [statusFilter, setStatusFilter] = useState('all');
  const [expandedAppointment, setExpandedAppointment] = useState(null);
  const [editingMeetingLink, setEditingMeetingLink] = useState(null);
  const [meetingLink, setMeetingLink] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalCount, setTotalCount] = useState(0);

  const itemsPerPage = 10;

  // Load appointments
  useEffect(() => {
    fetchAppointments();
  }, [currentPage, statusFilter]);

  // Calculate earnings
  const calculateEarnings = () => {
    const completedEarnings = appointments
      .filter(app => app.status === 'completed')
      .reduce((sum, app) => sum + (parseFloat(app.amount) || 0), 0);
    
    const reservedEarnings = appointments
      .filter(app => ['pending', 'confirmed', 'scheduled'].includes(app.status))
      .reduce((sum, app) => sum + (parseFloat(app.amount) || 0), 0);
    
    return {
      completed: completedEarnings,
      reserved: reservedEarnings,
      total: completedEarnings + reservedEarnings
    };
  };

  const fetchAppointments = async () => {
    try {
      setIsLoading(true);
      const queryParams = new URLSearchParams({
        page: currentPage.toString(),
        limit: itemsPerPage.toString(),
        status: statusFilter === 'all' ? '' : statusFilter
      }).toString();

      const response = await fetch(`/api/internal/foreign-student/foreign-student-appointments?${queryParams}`, {
        method: 'GET',
        credentials: 'include'
      });

      if (response.ok) {
        const data = await response.json();
        if (data.success && data.appointments) {
          setAppointments(data.appointments);
          setTotalCount(data.total);
          setTotalPages(data.totalPages);
          
          // Sort appointments: upcoming first, then by date descending
          const sortedAppointments = [...data.appointments].sort((a, b) => {
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            
            const dateA = new Date(a.session_date);
            const dateB = new Date(b.session_date);
            
            const isAUpcoming = dateA >= today;
            const isBUpcoming = dateB >= today;
            
            if (isAUpcoming && !isBUpcoming) return -1;
            if (!isAUpcoming && isBUpcoming) return 1;
            
            // For same type, sort by date (newest first for past, closest first for upcoming)
            if (isAUpcoming && isBUpcoming) {
              return dateA - dateB; // Closest upcoming first
            } else {
              return dateB - dateA; // Most recent past first
            }
          });
          
          setFilteredAppointments(sortedAppointments);
        }
      }
    } catch (error) {
      console.error('Error fetching appointments:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to load appointments. Please try again.',
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleStatusUpdate = async (appointmentId, newStatus, notes = '') => {
    try {
      const response = await fetch(`/api/internal/foreign-student/update-appointment-status/${appointmentId}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ status: newStatus, notes }),
        credentials: 'include'
      });

      const data = await response.json();

      if (response.ok && data.success) {
        Swal.fire({
          icon: 'success',
          title: 'Status Updated!',
          text: `Appointment ${newStatus} successfully.`,
          confirmButtonColor: '#0B6D76',
          timer: 1500,
          showConfirmButton: false
        });
        
        // Refresh appointments
        fetchAppointments();
      } else {
        throw new Error(data.message || 'Failed to update status');
      }
    } catch (error) {
      Swal.fire({
        icon: 'error',
        title: 'Update Failed',
        text: error.message || 'Failed to update appointment status.',
        confirmButtonColor: '#0B6D76'
      });
    }
  };

  const handleCancelAppointment = async (appointment) => {
    const { value: reason } = await Swal.fire({
      title: 'Cancel Session',
      html: `
        <div class="text-left">
          <p class="font-medium text-gray-800 mb-3">Are you sure you want to cancel this session?</p>
          <div class="bg-gray-50 rounded-lg p-4 mb-4">
            <div class="space-y-2 text-sm">
              <div class="flex">
                <span class="text-gray-600 w-24">Student:</span>
                <span class="font-medium">${appointment.student_name}</span>
              </div>
              <div class="flex">
                <span class="text-gray-600 w-24">Date:</span>
                <span class="font-medium">${formatDate(appointment.session_date)}</span>
              </div>
              <div class="flex">
                <span class="text-gray-600 w-24">Time:</span>
                <span class="font-medium">${formatTime(appointment.start_time)} - ${formatTime(appointment.end_time)}</span>
              </div>
            </div>
          </div>
          <div class="mt-4">
            <label class="block text-sm font-medium text-gray-700 mb-2">Cancellation Reason (Optional)</label>
            <textarea 
              id="cancellation-reason" 
              class="w-full px-4 py-3 border border-gray-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm transition-all duration-200" 
              rows="3" 
              placeholder="Please provide a reason for cancellation..."
            ></textarea>
          </div>
        </div>
      `,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Yes, Cancel Session',
      cancelButtonText: 'No, Keep Session',
      confirmButtonColor: '#ef4444',
      cancelButtonColor: '#6b7280',
      showLoaderOnConfirm: true,
      preConfirm: () => {
        const reasonInput = document.getElementById('cancellation-reason');
        return reasonInput ? reasonInput.value : '';
      }
    });

    if (reason !== undefined) {
      await handleStatusUpdate(appointment.id, 'cancelled', reason);
    }
  };

  const handleMarkAsCompleted = async (appointmentId, appointment) => {
    const cappointment = appointments.find(app => app.id === appointmentId);
    if (cappointment) {
      const canConfirm = canConfirmAppointment(cappointment);
      
      if (!canConfirm) {
        Swal.fire({
          icon: 'warning',
          title: 'Cannot Complete Yet',
          text: 'You can only Complete a session 1 minute after its scheduled end time.',
          confirmButtonColor: '#0B6D76'
        });
        return;
      }
    }

    const { value: feedback } = await Swal.fire({
      title: 'Mark as Completed',
      html: `
        <div class="text-left">
          <p class="font-medium text-gray-800 mb-3">Mark this appointment as completed?</p>
          <div class="bg-blue-50 rounded-lg p-4 mb-4">
            <div class="space-y-2 text-sm">
              <div class="flex">
                <span class="text-gray-600 w-24">Student:</span>
                <span class="font-medium">${appointment.student_name}</span>
              </div>
              <div class="flex">
                <span class="text-gray-600 w-24">Date:</span>
                <span class="font-medium">${formatDate(appointment.session_date)}</span>
              </div>
              <div class="flex">
                <span class="text-gray-600 w-24">Time:</span>
                <span class="font-medium">${formatTime(appointment.start_time)} - ${formatTime(appointment.end_time)}</span>
              </div>
            </div>
          </div>
          <div class="mt-4">
            <label class="block text-sm font-medium text-gray-700 mb-2">
              Session Feedback
              <span class="text-gray-400 text-xs font-normal ml-1">- Share your experience with the student</span>
            </label>
            <textarea 
              id="completion-feedback" 
              class="w-full px-4 py-3 border border-gray-200 rounded-xl focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm transition-all duration-200" 
              rows="4" 
              placeholder="How was the session? Any comments about the student's performance, engagement, or areas for improvement?"
            ></textarea>
          </div>
        </div>
      `,
      icon: 'question',
      showCancelButton: true,
      confirmButtonText: 'Mark as Completed',
      cancelButtonText: 'Cancel',
      confirmButtonColor: '#0B6D76',
      cancelButtonColor: '#6b7280',
      showLoaderOnConfirm: true,
      preConfirm: () => {
        const feedbackInput = document.getElementById('completion-feedback');
        return feedbackInput ? feedbackInput.value : '';
      }
    });

    if (feedback !== undefined) {
      await handleStatusUpdate(appointmentId, 'completed', feedback);
    }
  };

  const handleDeleteAppointment = async (appointment) => {
    const result = await Swal.fire({
      title: 'Delete Session Record',
      html: `
        <div class="text-left">
          <div class="bg-red-50 border-l-4 border-red-500 p-4 mb-4">
            <div class="flex">
              <AlertTriangle class="h-6 w-6 text-red-500 mr-3" />
              <div>
                <p class="text-red-800 font-semibold">Warning: This action cannot be undone!</p>
                <p class="text-red-600 text-sm mt-1">This will permanently delete the session record.</p>
              </div>
            </div>
          </div>
          <div class="bg-gray-50 rounded-lg p-4">
            <div class="space-y-2 text-sm">
              <div class="flex">
                <span class="text-gray-600 w-24">Student:</span>
                <span class="font-medium">${appointment.student_name}</span>
              </div>
              <div class="flex">
                <span class="text-gray-600 w-24">Date:</span>
                <span class="font-medium">${formatDate(appointment.session_date)}</span>
              </div>
            </div>
          </div>
        </div>
      `,
      icon: 'error',
      showCancelButton: true,
      confirmButtonText: 'Delete Permanently',
      cancelButtonText: 'Cancel',
      confirmButtonColor: '#ef4444',
      cancelButtonColor: '#6b7280'
    });

    if (result.isConfirmed) {
      try {
        const response = await fetch(`/api/internal/foreign-student/delete-appointment/${appointment.id}`, {
          method: 'DELETE',
          credentials: 'include'
        });

        const data = await response.json();

        if (response.ok && data.success) {
          Swal.fire({
            icon: 'success',
            title: 'Deleted!',
            text: 'Session record has been permanently deleted.',
            confirmButtonColor: '#0B6D76'
          });
          
          // Refresh appointments
          fetchAppointments();
        } else {
          throw new Error(data.message || 'Failed to delete appointment');
        }
      } catch (error) {
        Swal.fire({
          icon: 'error',
          title: 'Deletion Failed',
          text: error.message || 'Failed to delete appointment. Please try again.',
          confirmButtonColor: '#0B6D76'
        });
      }
    }
  };

  const handleSendMeetingLink = async (appointmentId) => {
    if (!meetingLink.trim()) {
      Swal.fire({
        icon: 'warning',
        title: 'Missing Link',
        text: 'Please enter a meeting link.',
        confirmButtonColor: '#0B6D76'
      });
      return;
    }

    const isValidUrl = (string) => {
      try {
        new URL(string);
        return true;
      } catch (_) {
        return false;
      }
    };

    if (!isValidUrl(meetingLink)) {
      Swal.fire({
        icon: 'warning',
        title: 'Invalid Link',
        text: 'Please enter a valid URL (e.g., https://meet.google.com/xyz-abc-def)',
        confirmButtonColor: '#0B6D76'
      });
      return;
    }

    try {
      const response = await fetch(`/api/internal/foreign-student/update-meeting-link/${appointmentId}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ meeting_link: meetingLink }),
        credentials: 'include'
      });

      const data = await response.json();

      if (response.ok && data.success) {
        Swal.fire({
          icon: 'success',
          title: 'Link Sent!',
          text: 'Meeting link has been sent to the student.',
          confirmButtonColor: '#0B6D76'
        });
        
        // Reset editing state
        setEditingMeetingLink(null);
        setMeetingLink('');
        
        // Refresh appointments
        fetchAppointments();
      } else {
        throw new Error(data.message || 'Failed to send meeting link');
      }
    } catch (error) {
      Swal.fire({
        icon: 'error',
        title: 'Failed to Send',
        text: error.message || 'Failed to send meeting link. Please try again.',
        confirmButtonColor: '#0B6D76'
      });
    }
  };

  const handleConfirmAppointment = async (appointmentId) => {
    const result = await Swal.fire({
      title: 'Confirm Appointment',
      text: 'Are you sure you want to confirm this appointment?',
      icon: 'question',
      showCancelButton: true,
      confirmButtonText: 'Yes, Confirm',
      cancelButtonText: 'Cancel',
      confirmButtonColor: '#0B6D76',
      cancelButtonColor: '#6b7280'
    });

    if (result.isConfirmed) {
      await handleStatusUpdate(appointmentId, 'confirmed');
    }
  };

  const canConfirmAppointment = (appointment) => {
    const now = new Date();
    const appointmentDate = new Date(appointment.session_date);
    const [hours, minutes] = appointment.end_time.split(':');
    appointmentDate.setHours(parseInt(hours), parseInt(minutes), 0, 0);
    
    const oneMinuteAfterEnd = new Date(appointmentDate.getTime() + 60000);
    return now >= oneMinuteAfterEnd;
  };

  const toggleExpand = (appointmentId) => {
    setExpandedAppointment(expandedAppointment === appointmentId ? null : appointmentId);
  };

  const startEditingMeetingLink = (appointment) => {
    setEditingMeetingLink(appointment.id);
    setMeetingLink(appointment.meeting_link || '');
  };

  const cancelEditing = () => {
    setEditingMeetingLink(null);
    setMeetingLink('');
  };

  const getStatusColor = (status) => {
    switch (status) {
      case 'confirmed':
      case 'scheduled':
        return 'bg-emerald-50 text-emerald-700 border-emerald-200';
      case 'pending':
        return 'bg-amber-50 text-amber-700 border-amber-200';
      case 'cancelled':
        return 'bg-rose-50 text-rose-700 border-rose-200';
      case 'completed':
        return 'bg-blue-50 text-blue-700 border-blue-200';
      case 'no_show':
        return 'bg-gray-50 text-gray-700 border-gray-200';
      default:
        return 'bg-gray-50 text-gray-700 border-gray-200';
    }
  };

  const getStatusIcon = (status) => {
    switch (status) {
      case 'confirmed':
      case 'scheduled':
        return <CheckCircle className="w-4 h-4 text-emerald-500" />;
      case 'pending':
        return <Loader2 className="w-4 h-4 text-amber-500 animate-spin" />;
      case 'cancelled':
        return <XCircle className="w-4 h-4 text-rose-500" />;
      case 'completed':
        return <CheckCircle className="w-4 h-4 text-blue-500" />;
      case 'no_show':
        return <AlertTriangle className="w-4 h-4 text-gray-500" />;
      default:
        return <Loader2 className="w-4 h-4 text-gray-500" />;
    }
  };

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

  const formatTime = (timeString) => {
    const [hours, minutes] = timeString.split(':');
    const hour = parseInt(hours);
    const ampm = hour >= 12 ? 'PM' : 'AM';
    const formattedHour = hour % 12 || 12;
    return `${formattedHour}:${minutes} ${ampm}`;
  };

  const formatDuration = (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 isAppointmentPast = (appointmentDate, appointmentTime) => {
    const today = new Date();
    const [hours, minutes] = appointmentTime.split(':');
    const appointmentDateTime = new Date(appointmentDate);
    appointmentDateTime.setHours(parseInt(hours), parseInt(minutes), 0, 0);
    return appointmentDateTime < today;
  };

  const handlePageChange = (newPage) => {
    if (newPage >= 1 && newPage <= totalPages) {
      setCurrentPage(newPage);
      setExpandedAppointment(null);
    }
  };

  const earnings = calculateEarnings();

  if (isLoading) {
    return (
      <div className="min-h-screen flex justify-center items-center">
        <div className="text-center">
          <motion.div
            animate={{ rotate: 360 }}
            transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
            className="w-12 h-12 border-2 border-blue-500 border-t-transparent rounded-full mx-auto mb-4"
          />
          <p className="text-gray-600 font-medium">Loading appointments...</p>
          <p className="text-gray-400 text-sm mt-2">Fetching your session data</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-b from-gray-50 to-white py-8 px-4">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <motion.div
          initial={{ opacity: 0, y: -20 }}
          animate={{ opacity: 1, y: 0 }}
          className="text-center mb-10"
        >
          <div className="inline-flex items-center gap-2 px-4 py-2 bg-blue-50 rounded-full border border-blue-200 mb-4">
            <Calendar className="w-4 h-4 text-blue-600" />
            <span className="text-sm font-medium text-blue-700">Session Management</span>
          </div>
          <h1 className="text-4xl font-bold bg-gradient-to-r from-gray-800 to-gray-600 bg-clip-text text-black mb-3">
            My Booked Sessions
          </h1>
          <p className="text-gray-600 text-lg max-w-2xl mx-auto">
            Manage all sessions booked by students, track earnings, and update session details
          </p>
        </motion.div>

        {/* Stats Cards - Icons Removed as Requested */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-10"
        >
          {/* Total Bookings Card */}
          <div className="bg-white rounded-2xl p-6 border border-gray-200 shadow-sm hover:shadow-lg transition-all duration-300 group">
            <div>
              <p className="text-sm text-gray-500 mb-1">Total Bookings</p>
              <p className="text-3xl font-bold text-gray-800 mb-2">{totalCount}</p>
            </div>
          </div>

          {/* Completed Earnings Card */}
          <div className="bg-white rounded-2xl p-6 border border-gray-200 shadow-sm hover:shadow-lg transition-all duration-300 group">
            <div>
              <p className="text-sm text-gray-500 mb-1">Completed Earnings</p>
              <p className="text-3xl font-bold text-emerald-600 mb-2">${earnings.completed.toFixed(2)}</p>
            </div>
          </div>

          {/* Reserved Earnings Card */}
          <div className="bg-white rounded-2xl p-6 border border-gray-200 shadow-sm hover:shadow-lg transition-all duration-300 group">
            <div>
              <p className="text-sm text-gray-500 mb-1">Reserved Earnings</p>
              <p className="text-3xl font-bold text-amber-600 mb-2">${earnings.reserved.toFixed(2)}</p>
            </div>
          </div>

          {/* Total Earnings Card */}
          <div className="bg-white rounded-2xl p-6 border border-gray-200 shadow-sm hover:shadow-lg transition-all duration-300 group">
            <div>
              <p className="text-sm text-gray-500 mb-1">Total Earnings</p>
              <p className="text-3xl font-bold text-blue-600 mb-2">${earnings.total.toFixed(2)}</p>
            </div>
          </div>
        </motion.div>

        {/* Filter Bar */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="bg-white rounded-2xl p-6 border border-gray-200 shadow-sm mb-8"
        >
          <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
            <div>
              <div className="flex items-center gap-3">
                <Filter className="w-5 h-5 text-gray-400" />
                <h3 className="text-xl font-bold text-gray-800">
                  {statusFilter === 'all' ? 'All Bookings' : 
                   statusFilter === 'upcoming' ? 'Upcoming Sessions' :
                   `${statusFilter.charAt(0).toUpperCase() + statusFilter.slice(1)} Sessions`}
                </h3>
              </div>
              <p className="text-gray-500 text-sm mt-1">
                Showing {totalCount} total sessions
              </p>
            </div>
            <div className="flex items-center gap-4">
              <div className="relative">
                <select
                  value={statusFilter}
                  onChange={(e) => {
                    setStatusFilter(e.target.value);
                    setCurrentPage(1);
                  }}
                  className="appearance-none bg-white border border-gray-300 rounded-xl pl-4 pr-10 py-3 text-gray-700 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-all duration-200 w-full lg:w-48"
                >
                  <option value="all">All Status</option>
                  <option value="pending">Pending</option>
                  <option value="confirmed">Confirmed</option>
                  <option value="scheduled">Scheduled</option>
                  <option value="completed">Completed</option>
                  <option value="cancelled">Cancelled</option>
                  <option value="no_show">No Show</option>
                </select>
                <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3">
                  <ChevronDown className="w-5 h-5 text-gray-400" />
                </div>
              </div>
            </div>
          </div>
        </motion.div>

        {/* Appointments List */}
        <div className="mb-10">
          {filteredAppointments.length === 0 ? (
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              className="text-center py-20 bg-white rounded-2xl border border-gray-200 shadow-sm"
            >
              <div className="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-6">
                <Calendar className="w-10 h-10 text-gray-400" />
              </div>
              <h3 className="text-xl font-bold text-gray-700 mb-2">No sessions found</h3>
              <p className="text-gray-500 max-w-md mx-auto mb-6">
                {statusFilter === 'all' 
                  ? 'No sessions have been booked yet. Your sessions will appear here once students book appointments.'
                  : `No ${statusFilter} sessions found in your records.`}
              </p>
            </motion.div>
          ) : (
            <div className="space-y-4">
              <AnimatePresence>
                {filteredAppointments.map(appointment => {
                  const isPast = isAppointmentPast(appointment.session_date, appointment.start_time);
                  const canAddMeetingLink = !['cancelled', 'completed', 'no_show'].includes(appointment.status) && !isPast;
                  const canCancel = ['pending', 'confirmed', 'scheduled'].includes(appointment.status) && !isPast;
                  const canDelete = isPast && appointment.status !== 'completed';
                  const canConfirm = appointment.status === 'confirmed' && canConfirmAppointment(appointment);
                  
                  return (
                    <motion.div
                      key={appointment.id}
                      initial={{ opacity: 0, y: 20 }}
                      animate={{ opacity: 1, y: 0 }}
                      exit={{ opacity: 0, y: -20 }}
                      className="bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden hover:shadow-lg transition-shadow duration-300"
                    >
                      {/* Appointment Header */}
                      <div 
                        className="p-6 cursor-pointer hover:bg-gray-50 transition-colors duration-200"
                        onClick={() => toggleExpand(appointment.id)}
                      >
                        <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
                          <div className="flex items-start gap-4">
                            <div className="flex-shrink-0">
                              {appointment.student_profile_picture ? (
                                <div className="relative">
                                  <img
                                    src={`https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${appointment.student_profile_picture}`}
                                    alt={appointment.student_name}
                                    className="w-16 h-16 rounded-xl object-cover border-2 border-gray-100"
                                  />
                                  {isPast && (
                                    <div className="absolute -top-1 -right-1 w-6 h-6 bg-gray-500 rounded-full flex items-center justify-center">
                                      <Clock className="w-3 h-3 text-white" />
                                    </div>
                                  )}
                                </div>
                              ) : (
                                <div className="w-16 h-16 rounded-xl bg-gradient-to-br from-blue-500 to-cyan-500 flex items-center justify-center">
                                  <User className="w-8 h-8 text-white" />
                                </div>
                              )}
                            </div>
                            <div className="flex-1">
                              <div className="flex items-center gap-3 mb-2">
                                <h4 className="font-bold text-gray-800 text-lg">{appointment.student_name}</h4>
                                <span className={`px-3 py-1 rounded-full text-xs font-medium border ${getStatusColor(appointment.status)} flex items-center gap-1.5`}>
                                  {getStatusIcon(appointment.status)}
                                  {appointment.status.charAt(0).toUpperCase() + appointment.status.slice(1)}
                                </span>
                              </div>
                              <div className="flex flex-wrap items-center gap-4 text-sm text-gray-600">
                                <span className="flex items-center gap-2">
                                  <Calendar className="w-4 h-4" />
                                  {formatDate(appointment.session_date)}
                                </span>
                                <span className="flex items-center gap-2">
                                  <Clock className="w-4 h-4" />
                                  {formatTime(appointment.start_time)} - {formatTime(appointment.end_time)}
                                  <span className="text-xs text-gray-400">({formatDuration(appointment.start_time, appointment.end_time)})</span>
                                </span>
                                <span className="flex items-center gap-2">
                                  <DollarSign className="w-4 h-4" />
                                  <span className="font-bold text-gray-800">${parseFloat(appointment.amount).toFixed(2)}</span>
                                </span>
                              </div>
                            </div>
                          </div>
                          <div className="flex items-center gap-4">
                            <div className="text-right">
                              <div className="text-2xl font-bold text-blue-600">
                                ${parseFloat(appointment.amount).toFixed(2)}
                              </div>
                              <p className="text-sm text-gray-500">Session amount</p>
                            </div>
                            <button className="text-gray-400 hover:text-gray-600 transition-colors">
                              {expandedAppointment === appointment.id ? 
                                <ChevronUp className="w-6 h-6" /> : 
                                <ChevronDown className="w-6 h-6" />
                              }
                            </button>
                          </div>
                        </div>
                      </div>

                      {/* Expanded Details - Changed to row-wise layout */}
                      <AnimatePresence>
                        {expandedAppointment === appointment.id && (
                          <motion.div
                            initial={{ height: 0, opacity: 0 }}
                            animate={{ height: 'auto', opacity: 1 }}
                            exit={{ height: 0, opacity: 0 }}
                            transition={{ duration: 0.3 }}
                            className="border-t border-gray-100 overflow-hidden"
                          >
                            <div className="p-6">
                              <div className="space-y-8">
                                {/* Session Details */}
                                <div>
                                  <h5 className="font-bold text-gray-800 mb-4 text-lg">Session Details</h5>
                                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                                    <div className="bg-gray-50 rounded-xl p-4">
                                      <p className="text-sm text-gray-500 mb-1">Student Name</p>
                                      <p className="font-medium">{appointment.student_name}</p>
                                    </div>
                                    <div className="bg-gray-50 rounded-xl p-4">
                                      <p className="text-sm text-gray-500 mb-1">Student Email</p>
                                      <p className="font-medium text-sm truncate">{appointment.student_email}</p>
                                    </div>
                                    <div className="bg-gray-50 rounded-xl p-4">
                                      <p className="text-sm text-gray-500 mb-1">Session Date</p>
                                      <p className="font-medium">{formatDate(appointment.session_date)}</p>
                                    </div>
                                    <div className="bg-gray-50 rounded-xl p-4">
                                      <p className="text-sm text-gray-500 mb-1">Session Time</p>
                                      <div>
                                        <p className="font-medium">{formatTime(appointment.start_time)}</p>
                                        <p className="text-xs text-gray-500">to {formatTime(appointment.end_time)}</p>
                                      </div>
                                    </div>
                                    <div className="bg-gray-50 rounded-xl p-4">
                                      <p className="text-sm text-gray-500 mb-1">Duration</p>
                                      <p className="font-medium">{formatDuration(appointment.start_time, appointment.end_time)}</p>
                                    </div>
                                    <div className="bg-gray-50 rounded-xl p-4">
                                      <p className="text-sm text-gray-500 mb-1">Amount</p>
                                      <p className="font-bold text-blue-600">${parseFloat(appointment.amount).toFixed(2)}</p>
                                    </div>
                                  </div>
                                </div>

                                {/* Session Management & Meeting Link in a row */}
                                <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
                                  {/* Session Management */}
                                  <div>
                                    <h5 className="font-bold text-gray-800 mb-4 text-lg">Session Management</h5>
                                    <div className="space-y-3">
                                      {/* Pending Status Actions */}
                                      {appointment.status === 'pending' && (
                                        <div className="space-y-3">
                                          <motion.button
                                            whileHover={{ scale: 1.02 }}
                                            whileTap={{ scale: 0.98 }}
                                            onClick={() => handleConfirmAppointment(appointment.id)}
                                            className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-gradient-to-r from-emerald-500 to-teal-500 text-white rounded-xl hover:shadow-lg transition-all duration-200 font-medium"
                                          >
                                            <CalendarCheck className="w-5 h-5" />
                                            Confirm Session
                                          </motion.button>
                                          {canCancel && (
                                            <motion.button
                                              whileHover={{ scale: 1.02 }}
                                              whileTap={{ scale: 0.98 }}
                                              onClick={() => handleCancelAppointment(appointment)}
                                              className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-rose-50 text-rose-700 border border-rose-200 rounded-xl hover:bg-rose-100 transition-colors duration-200 font-medium"
                                            >
                                              <XCircle className="w-5 h-5" />
                                              Cancel Session
                                            </motion.button>
                                          )}
                                        </div>
                                      )}

                                      {/* Confirmed Status Actions */}
                                      {appointment.status === 'confirmed' && (
                                        <div className="space-y-3">
                                          {canConfirm ? (
                                            <motion.button
                                              whileHover={{ scale: 1.02 }}
                                              whileTap={{ scale: 0.98 }}
                                              onClick={() => handleMarkAsCompleted(appointment.id, appointment)}
                                              className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-gradient-to-r from-green-500 to-emerald-500 text-white rounded-xl hover:shadow-lg transition-all duration-200 font-medium"
                                            >
                                              <CheckCircle className="w-5 h-5" />
                                              Mark as Completed
                                            </motion.button>
                                          ) : (
                                            <div className="bg-amber-50 border border-amber-200 rounded-xl p-4">
                                              <div className="flex items-center gap-2 text-amber-700 mb-2">
                                                <Clock className="w-5 h-5" />
                                                <span className="font-medium">Completion Available Soon</span>
                                              </div>
                                              <p className="text-sm text-amber-600">
                                                You can confirm this session 1 minute after {formatTime(appointment.end_time)}
                                              </p>
                                            </div>
                                          )}
                                          {canCancel && (
                                            <motion.button
                                              whileHover={{ scale: 1.02 }}
                                              whileTap={{ scale: 0.98 }}
                                              onClick={() => handleCancelAppointment(appointment)}
                                              className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-rose-50 text-rose-700 border border-rose-200 rounded-xl hover:bg-rose-100 transition-colors duration-200 font-medium"
                                            >
                                              <XCircle className="w-5 h-5" />
                                              Cancel Session
                                            </motion.button>
                                          )}
                                        </div>
                                      )}

                                      {/* Scheduled Status Actions */}
                                      {appointment.status === 'scheduled' && (
                                        <div className="space-y-3">
                                          <motion.button
                                            whileHover={{ scale: 1.02 }}
                                            whileTap={{ scale: 0.98 }}
                                            onClick={() => handleMarkAsCompleted(appointment.id, appointment)}
                                            className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-gradient-to-r from-green-500 to-emerald-500 text-white rounded-xl hover:shadow-lg transition-all duration-200 font-medium"
                                          >
                                            <CheckCircle className="w-5 h-5" />
                                            Mark as Completed
                                          </motion.button>
                                          {canCancel && (
                                            <motion.button
                                              whileHover={{ scale: 1.02 }}
                                              whileTap={{ scale: 0.98 }}
                                              onClick={() => handleCancelAppointment(appointment)}
                                              className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-rose-50 text-rose-700 border border-rose-200 rounded-xl hover:bg-rose-100 transition-colors duration-200 font-medium"
                                            >
                                              <XCircle className="w-5 h-5" />
                                              Cancel Session
                                            </motion.button>
                                          )}
                                        </div>
                                      )}

                                      {/* Completed Session Feedback */}
                                      {appointment.status === 'completed' && (
                                        <div className="space-y-4">
                                          {appointment.notes?.trim() && (
                                            <div className="bg-blue-50 border border-blue-200 rounded-xl p-4">
                                              <div className="flex items-center gap-2 text-blue-700 mb-2">
                                                <MessageSquare className="w-5 h-5" />
                                                <span className="font-medium">Your Feedback</span>
                                              </div>
                                              <p className="text-sm text-gray-700 whitespace-pre-line">
                                                {appointment.notes}
                                              </p>
                                            </div>
                                          )}

                                          {appointment.student_feedback?.trim() && (
                                            <div className="bg-emerald-50 border border-emerald-200 rounded-xl p-4">
                                              <div className="flex items-center gap-2 text-emerald-700 mb-2">
                                                <MessageSquare className="w-5 h-5" />
                                                <span className="font-medium">Student's Feedback</span>
                                              </div>
                                              <p className="text-sm text-gray-700 whitespace-pre-line">
                                                {appointment.student_feedback}
                                              </p>
                                            </div>
                                          )}

                                          {(!appointment.notes?.trim() && !appointment.student_feedback?.trim()) && (
                                            <div className="bg-gray-50 border border-gray-200 rounded-xl p-4 text-center">
                                              <MessageSquare className="w-6 h-6 text-gray-400 mx-auto mb-2" />
                                              <p className="text-sm text-gray-600">No feedback exchanged yet</p>
                                            </div>
                                          )}

                                          {canDelete && (
                                            <motion.button
                                              whileHover={{ scale: 1.02 }}
                                              whileTap={{ scale: 0.98 }}
                                              onClick={() => handleDeleteAppointment(appointment)}
                                              className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-gray-100 text-gray-700 rounded-xl hover:bg-gray-200 transition-colors duration-200 font-medium"
                                            >
                                              <Trash2 className="w-5 h-5" />
                                              Delete Record
                                            </motion.button>
                                          )}
                                        </div>
                                      )}

                                      {/* Delete for past non-completed */}
                                      {canDelete && appointment.status !== 'completed' && (
                                        <motion.button
                                          whileHover={{ scale: 1.02 }}
                                          whileTap={{ scale: 0.98 }}
                                          onClick={() => handleDeleteAppointment(appointment)}
                                          className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-gray-100 text-gray-700 rounded-xl hover:bg-gray-200 transition-colors duration-200 font-medium"
                                        >
                                          <Trash2 className="w-5 h-5" />
                                          Delete Record
                                        </motion.button>
                                      )}
                                    </div>
                                  </div>

                                  {/* Meeting Link Section */}
                                  {canAddMeetingLink && (
                                    <div>
                                      <h5 className="font-bold text-gray-800 mb-4 text-lg">Meeting Link</h5>
                                      <div className="bg-gradient-to-br from-blue-50 to-cyan-50 border border-blue-200 rounded-xl p-5 h-full">
                                        <div className="flex items-center justify-between mb-4">
                                          <div className="flex items-center gap-2">
                                            <Link2 className="w-5 h-5 text-blue-600" />
                                            <span className="font-medium text-blue-700">Virtual Session</span>
                                          </div>
                                          {!editingMeetingLink && (
                                            <motion.button
                                              whileHover={{ scale: 1.05 }}
                                              whileTap={{ scale: 0.95 }}
                                              onClick={() => startEditingMeetingLink(appointment)}
                                              className="text-blue-600 hover:text-blue-800 text-sm flex items-center gap-1 font-medium"
                                            >
                                              <Edit className="w-4 h-4" />
                                              {appointment.meeting_link ? 'Edit' : 'Add'} Link
                                            </motion.button>
                                          )}
                                        </div>
                                        
                                        {editingMeetingLink === appointment.id ? (
                                          <div className="space-y-3">
                                            <input
                                              type="url"
                                              value={meetingLink}
                                              onChange={(e) => setMeetingLink(e.target.value)}
                                              placeholder="https://meet.google.com/xyz-abc-def"
                                              className="w-full px-4 py-3 border border-blue-300 rounded-xl text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-all duration-200 bg-white"
                                            />
                                            <div className="flex gap-2">
                                              <motion.button
                                                whileHover={{ scale: 1.03 }}
                                                whileTap={{ scale: 0.97 }}
                                                onClick={() => handleSendMeetingLink(appointment.id)}
                                                className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-gradient-to-r from-blue-500 to-cyan-500 text-white rounded-xl hover:shadow-lg transition-all duration-200 font-medium"
                                              >
                                                <Send className="w-4 h-4" />
                                                Send Link
                                              </motion.button>
                                              <motion.button
                                                whileHover={{ scale: 1.03 }}
                                                whileTap={{ scale: 0.97 }}
                                                onClick={cancelEditing}
                                                className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-gray-200 text-gray-700 rounded-xl hover:bg-gray-300 transition-colors duration-200 font-medium"
                                              >
                                                Cancel
                                              </motion.button>
                                            </div>
                                          </div>
                                        ) : appointment.meeting_link ? (
                                          <div className="h-full flex flex-col">
                                            <div className="flex-1">
                                              <p className="text-sm text-gray-600 mb-3 break-all bg-white p-3 rounded-lg border">
                                                {appointment.meeting_link}
                                              </p>
                                              <div className="flex items-center gap-2 text-emerald-600">
                                                <CheckCircle className="w-4 h-4" />
                                                <span className="text-sm font-medium">Link sent to student</span>
                                              </div>
                                            </div>
                                            {appointment.meeting_link && (
                                              <a
                                                href={appointment.meeting_link}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                className="mt-4 w-full flex items-center justify-center gap-2 px-4 py-2 bg-blue-100 text-blue-700 rounded-lg hover:bg-blue-200 transition-colors"
                                              >
                                                <ExternalLink className="w-4 h-4" />
                                                Join Meeting
                                              </a>
                                            )}
                                          </div>
                                        ) : (
                                          <div className="text-center py-4">
                                            <div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-3">
                                              <Link2 className="w-6 h-6 text-blue-500" />
                                            </div>
                                            <p className="text-amber-600 text-sm font-medium">No meeting link provided</p>
                                            <p className="text-gray-500 text-xs mt-1">Add a link to connect with student</p>
                                          </div>
                                        )}
                                      </div>
                                    </div>
                                  )}
                                </div>
                              </div>
                            </div>
                          </motion.div>
                        )}
                      </AnimatePresence>
                    </motion.div>
                  );
                })}
              </AnimatePresence>
            </div>
          )}
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            className="flex flex-col sm:flex-row items-center justify-between gap-4 bg-white rounded-2xl p-6 border border-gray-200 shadow-sm"
          >
            <div className="text-sm text-gray-600">
              Showing <span className="font-bold text-gray-800">{(currentPage - 1) * itemsPerPage + 1}</span> to{' '}
              <span className="font-bold text-gray-800">{Math.min(currentPage * itemsPerPage, totalCount)}</span> of{' '}
              <span className="font-bold text-gray-800">{totalCount}</span> sessions
            </div>
            <div className="flex items-center gap-2">
              <motion.button
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
                onClick={() => handlePageChange(currentPage - 1)}
                disabled={currentPage === 1}
                className={`flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-medium ${
                  currentPage === 1
                    ? 'text-gray-400 cursor-not-allowed bg-gray-100'
                    : 'text-gray-700 hover:bg-gray-100 bg-white border border-gray-300'
                }`}
              >
                <ChevronLeft className="w-4 h-4" />
                Previous
              </motion.button>
              
              <div className="flex items-center gap-1">
                {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                  let pageNum;
                  if (totalPages <= 5) {
                    pageNum = i + 1;
                  } else if (currentPage <= 3) {
                    pageNum = i + 1;
                  } else if (currentPage >= totalPages - 2) {
                    pageNum = totalPages - 4 + i;
                  } else {
                    pageNum = currentPage - 2 + i;
                  }
                  
                  return (
                    <motion.button
                      key={pageNum}
                      whileHover={{ scale: 1.1 }}
                      whileTap={{ scale: 0.9 }}
                      onClick={() => handlePageChange(pageNum)}
                      className={`w-10 h-10 flex items-center justify-center rounded-xl text-sm font-medium ${
                        currentPage === pageNum
                          ? 'bg-gradient-to-r from-blue-500 to-cyan-500 text-white shadow-md'
                          : 'text-gray-700 hover:bg-gray-100 border border-gray-300'
                      }`}
                    >
                      {pageNum}
                    </motion.button>
                  );
                })}
              </div>
              
              <motion.button
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
                onClick={() => handlePageChange(currentPage + 1)}
                disabled={currentPage === totalPages}
                className={`flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-medium ${
                  currentPage === totalPages
                    ? 'text-gray-400 cursor-not-allowed bg-gray-100'
                    : 'text-gray-700 hover:bg-gray-100 bg-white border border-gray-300'
                }`}
              >
                Next
                <ChevronRight className="w-4 h-4" />
              </motion.button>
            </div>
          </motion.div>
        )}
      </div>
    </div>
  );
};

export default ForeignStudentAppointments;