// app/student/dashboard/appointments/student-appointments.jsx
'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Heading from '../../components/atoms/Heading';
import Swal from 'sweetalert2';
import { 
  FaCalendarAlt,
  FaClock,
  FaUser,
  FaDollarSign,
  FaVideo,
  FaCheckCircle,
  FaTimesCircle,
  FaSpinner,
  FaExclamationTriangle,
  FaChevronDown,
  FaChevronUp,
  FaCopy,
  FaExternalLinkAlt,
  FaCommentDots,
  FaStar,
  FaEdit
} from 'react-icons/fa';

const StudentAppointments = () => {
  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 [upcomingAppointments, setUpcomingAppointments] = useState([]);
  const [pastAppointments, setPastAppointments] = useState([]);
  const [feedback, setFeedback] = useState('');
  const [rating, setRating] = useState(5);
  const [editingFeedback, setEditingFeedback] = useState(null);

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

  // Filter and organize appointments
  useEffect(() => {
    let filtered = appointments;
    
    if (statusFilter !== 'all') {
      filtered = appointments.filter(app => app.status === statusFilter);
    }
    
    setFilteredAppointments(filtered);
    
    // Separate upcoming and past appointments
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    const upcoming = filtered.filter(app => {
      const appointmentDate = new Date(app.session_date);
      return appointmentDate >= today;
    }).sort((a, b) => new Date(a.session_date) - new Date(b.session_date));
    
    const past = filtered.filter(app => {
      const appointmentDate = new Date(app.session_date);
      return appointmentDate < today;
    }).sort((a, b) => new Date(b.session_date) - new Date(a.session_date));
    
    setUpcomingAppointments(upcoming);
    setPastAppointments(past);
  }, [appointments, statusFilter]);

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

      if (response.ok) {
        const data = await response.json();
        if (data.success && data.appointments) {
          setAppointments(data.appointments);
        }
      }
    } 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 handleCopyMeetingLink = (link) => {
    navigator.clipboard.writeText(link)
      .then(() => {
        Swal.fire({
          icon: 'success',
          title: 'Copied!',
          text: 'Meeting link copied to clipboard.',
          confirmButtonColor: '#0B6D76',
          timer: 1500,
          showConfirmButton: false
        });
      })
      .catch(() => {
        Swal.fire({
          icon: 'error',
          title: 'Failed',
          text: 'Failed to copy link.',
          confirmButtonColor: '#0B6D76'
        });
      });
  };

  const handleJoinMeeting = (link) => {
    window.open(link, '_blank', 'noopener,noreferrer');
  };

  const handleCancelAppointment = async (appointmentId) => {
    const result = await Swal.fire({
      title: 'Cancel Appointment',
      text: 'Are you sure you want to cancel this appointment?',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Yes, Cancel',
      cancelButtonText: 'No, Keep It',
      confirmButtonColor: '#d33',
      cancelButtonColor: '#3085d6'
    });

    if (result.isConfirmed) {
      try {
        const response = await fetch(`/api/frontend/userdashboard/cancel-appointment/${appointmentId}`, {
          method: 'POST',
          credentials: 'include'
        });

        const data = await response.json();

        if (response.ok && data.success) {
          Swal.fire({
            icon: 'success',
            title: 'Cancelled!',
            text: 'Appointment cancelled successfully.',
            confirmButtonColor: '#0B6D76'
          });
          
          // Refresh appointments
          fetchAppointments();
        } else {
          throw new Error(data.message || 'Failed to cancel appointment');
        }
      } catch (error) {
        Swal.fire({
          icon: 'error',
          title: 'Cancellation Failed',
          text: error.message || 'Failed to cancel appointment. Please try again.',
          confirmButtonColor: '#0B6D76'
        });
      }
    }
  };

  // New function to submit student feedback
  const handleSubmitFeedback = async (appointmentId) => {
    if (!feedback.trim()) {
      Swal.fire({
        icon: 'warning',
        title: 'Missing Feedback',
        text: 'Please provide your feedback.',
        confirmButtonColor: '#0B6D76'
      });
      return;
    }

    if (feedback.length < 10) {
      Swal.fire({
        icon: 'warning',
        title: 'Feedback Too Short',
        text: 'Please provide more detailed feedback (at least 10 characters).',
        confirmButtonColor: '#0B6D76'
      });
      return;
    }

    try {
      const response = await fetch(`/api/frontend/userdashboard/submit-feedback/${appointmentId}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ 
          feedback, 
          rating,
          feedback_type: 'student_to_foreign_student'
        }),
        credentials: 'include'
      });

      const data = await response.json();

      if (response.ok && data.success) {
        Swal.fire({
          icon: 'success',
          title: 'Feedback Submitted!',
          text: 'Thank you for your feedback.',
          confirmButtonColor: '#0B6D76',
          timer: 1500,
          showConfirmButton: false
        });
        
        // Reset feedback form
        setFeedback('');
        setRating(5);
        setEditingFeedback(null);
        
        // Refresh appointments to show updated feedback
        fetchAppointments();
      } else {
        throw new Error(data.message || 'Failed to submit feedback');
      }
    } catch (error) {
      Swal.fire({
        icon: 'error',
        title: 'Submission Failed',
        text: error.message || 'Failed to submit feedback. Please try again.',
        confirmButtonColor: '#0B6D76'
      });
    }
  };

  // Function to show feedback dialog
  const showFeedbackDialog = (appointment) => {
    // Check if feedback already exists
    if (appointment.student_feedback && appointment.student_feedback.trim() !== "") {
      Swal.fire({
        icon: 'info',
        title: 'Feedback Already Submitted',
        text: 'You have already submitted feedback for this session. Feedback cannot be edited.',
        confirmButtonColor: '#0B6D76'
      });
      return;
    }

    Swal.fire({
      title: 'Submit Feedback',
      html: `
        <div class="text-left">
          <p>How was your session with <strong>${appointment.tutor_name}</strong>?</p>
          <div class="mt-4">
            <label class="block text-sm font-medium text-gray-700 mb-1">Your Feedback</label>
            <textarea 
              id="feedback-text" 
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-teal-500 focus:border-transparent text-sm" 
              rows="4" 
              placeholder="Please share your experience with the tutor. What did you like? What could be improved?"
              required
            ></textarea>
          </div>
        </div>
      `,
      icon: 'question',
      showCancelButton: true,
      confirmButtonText: 'Submit Feedback',
      cancelButtonText: 'Cancel',
      confirmButtonColor: '#0B6D76',
      cancelButtonColor: '#6b7280',
      showLoaderOnConfirm: true,
      preConfirm: () => {
        const feedbackInput = document.getElementById('feedback-text');
        
        if (!feedbackInput) {
          Swal.showValidationMessage('Please provide feedback');
          return false;
        }
        
        if (feedbackInput.value.trim().length < 10) {
          Swal.showValidationMessage('Feedback must be at least 10 characters');
          return false;
        }
        
        return {
          feedback: feedbackInput.value.trim()
        };
      }
    }).then((result) => {
      if (result.isConfirmed) {
        setFeedback(result.value.feedback);
        handleSubmitFeedback(appointment.id);
      }
    });
  };

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

  const getStatusColor = (status) => {
    switch (status) {
      case 'confirmed':
      case 'scheduled':
        return 'bg-green-100 text-green-800';
      case 'pending':
        return 'bg-yellow-100 text-yellow-800';
      case 'cancelled':
        return 'bg-red-100 text-red-800';
      case 'completed':
        return 'bg-blue-100 text-blue-800';
      case 'no_show':
        return 'bg-gray-100 text-gray-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  const getStatusIcon = (status) => {
    switch (status) {
      case 'confirmed':
      case 'scheduled':
        return <FaCheckCircle className="text-green-500" />;
      case 'pending':
        return <FaSpinner className="text-yellow-500 animate-spin" />;
      case 'cancelled':
        return <FaTimesCircle className="text-red-500" />;
      case 'completed':
        return <FaCheckCircle className="text-blue-500" />;
      case 'no_show':
        return <FaExclamationTriangle className="text-gray-500" />;
      default:
        return <FaSpinner className="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`;
  };

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

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-6xl mx-auto px-4">
        {/* Header */}
        <div className="text-center mb-8">
          <Heading level={3}>My Appointments</Heading>
          <p className="text-gray-600 mt-2">
            View and manage all your scheduled sessions with tutors
          </p>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
          <div className="bg-white p-6 rounded-xl shadow-sm border">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Total Appointments</p>
                <p className="text-2xl font-bold text-teal-600 mt-1">
                  {appointments.length}
                </p>
              </div>
              <div className="w-12 h-12 bg-teal-100 rounded-full flex items-center justify-center">
                <FaCalendarAlt className="text-teal-600" />
              </div>
            </div>
          </div>

          <div className="bg-white p-6 rounded-xl shadow-sm border">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Upcoming</p>
                <p className="text-2xl font-bold text-blue-600 mt-1">
                  {upcomingAppointments.length}
                </p>
              </div>
              <div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center">
                <FaClock className="text-blue-600" />
              </div>
            </div>
          </div>

          <div className="bg-white p-6 rounded-xl shadow-sm border">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Completed</p>
                <p className="text-2xl font-bold text-green-600 mt-1">
                  {appointments.filter(a => a.status === 'completed').length}
                </p>
              </div>
              <div className="w-12 h-12 bg-green-100 rounded-full flex items-center justify-center">
                <FaCheckCircle className="text-green-600" />
              </div>
            </div>
          </div>

          <div className="bg-white p-6 rounded-xl shadow-sm border">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Pending</p>
                <p className="text-2xl font-bold text-yellow-600 mt-1">
                  {appointments.filter(a => a.status === 'pending').length}
                </p>
              </div>
              <div className="w-12 h-12 bg-yellow-100 rounded-full flex items-center justify-center">
                <FaSpinner className="text-yellow-600" />
              </div>
            </div>
          </div>
        </div>

        {/* Filter Bar */}
        <div className="bg-white rounded-xl shadow-sm p-4 mb-8">
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div>
              <h3 className="font-semibold text-gray-800">
                {statusFilter === 'all' ? 'All Appointments' : 
                 statusFilter === 'upcoming' ? 'Upcoming Appointments' :
                 `${statusFilter.charAt(0).toUpperCase() + statusFilter.slice(1)} Appointments`}
              </h3>
            </div>
            <div className="flex items-center space-x-4">
              <div className="flex items-center space-x-2">
                <span className="text-sm text-gray-600">Filter by:</span>
                <select
                  value={statusFilter}
                  onChange={(e) => setStatusFilter(e.target.value)}
                  className="border rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-teal-500 focus:border-transparent"
                >
                  <option value="all">All Status</option>
                  <option value="upcoming">Upcoming</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>
                </select>
              </div>
            </div>
          </div>
        </div>

        {/* Upcoming Appointments */}
        {statusFilter === 'all' || statusFilter === 'upcoming' ? (
          <div className="mb-8">
            <h3 className="text-lg font-semibold text-gray-800 mb-4">Upcoming Appointments</h3>
            {upcomingAppointments.length === 0 ? (
              <div className="text-center py-8 bg-white rounded-xl shadow-sm">
                <FaCalendarAlt className="mx-auto text-gray-300 text-4xl mb-3" />
                <p className="text-gray-500">No upcoming appointments</p>
                <p className="text-sm text-gray-400 mt-1">Book a session to get started</p>
              </div>
            ) : (
              <div className="space-y-4">
                {upcomingAppointments.map(appointment => (
                  <div key={appointment.id} className="bg-white rounded-xl shadow-sm border overflow-hidden">
                    {/* Appointment Header */}
                    <div 
                      className="p-6 cursor-pointer hover:bg-gray-50 transition-colors"
                      onClick={() => toggleExpand(appointment.id)}
                    >
                      <div className="flex flex-col md:flex-row md:items-center justify-between">
                        <div className="flex items-center space-x-4 mb-4 md:mb-0">
                          <div className="flex-shrink-0">
                            {appointment.tutor_profile_picture ? (
                              <img
                                src={`https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${appointment.tutor_profile_picture}`}
                                alt={appointment.tutor_name}
                                className="w-14 h-14 rounded-full object-cover border-2 border-gray-100"
                              />
                            ) : (
                              <div className="w-14 h-14 rounded-full bg-teal-100 flex items-center justify-center">
                                <FaUser className="text-teal-600 text-xl" />
                              </div>
                            )}
                          </div>
                          <div>
                            <h4 className="font-semibold text-gray-800">{appointment.tutor_name}</h4>
                            <div className="flex items-center space-x-3 mt-1">
                              <span className="flex items-center text-sm text-gray-600">
                                <FaCalendarAlt className="mr-2" />
                                {formatDate(appointment.session_date)}
                              </span>
                              <span className="flex items-center text-sm text-gray-600">
                                <FaClock className="mr-2" />
                                {formatTime(appointment.start_time)} - {formatTime(appointment.end_time)}
                              </span>
                              <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(appointment.status)}`}>
                                <span className="flex items-center">
                                  {getStatusIcon(appointment.status)}
                                  <span className="ml-1">{appointment.status.charAt(0).toUpperCase() + appointment.status.slice(1)}</span>
                                </span>
                              </span>
                            </div>
                          </div>
                        </div>
                        <div className="flex items-center space-x-2">
                          <div className="text-right">
                            <div className="text-lg font-bold text-teal-600">
                              ${appointment.amount || appointment.rate * (calculateDurationHours(appointment.start_time, appointment.end_time))}
                            </div>
                            <div className="text-sm text-gray-500">
                              {formatDuration(appointment.start_time, appointment.end_time)}
                            </div>
                          </div>
                          <button className="text-gray-400 hover:text-gray-600">
                            {expandedAppointment === appointment.id ? <FaChevronUp /> : <FaChevronDown />}
                          </button>
                        </div>
                      </div>
                    </div>

                    {/* Expanded Details */}
                    {expandedAppointment === appointment.id && (
                      <div className="border-t border-gray-100 p-6">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                          {/* Left Column - Appointment Details */}
                          <div>
                            <h5 className="font-semibold text-gray-800 mb-3">Appointment Details</h5>
                            <div className="space-y-3">
                              <div className="flex justify-between">
                                <span className="text-gray-600">Tutor:</span>
                                <span className="font-medium">{appointment.tutor_name}</span>
                              </div>
                              <div className="flex justify-between">
                                <span className="text-gray-600">Date:</span>
                                <span className="font-medium">{formatDate(appointment.session_date)}</span>
                              </div>
                              <div className="flex justify-between">
                                <span className="text-gray-600">Time:</span>
                                <span className="font-medium">{formatTime(appointment.start_time)} - {formatTime(appointment.end_time)}</span>
                              </div>
                              <div className="flex justify-between">
                                <span className="text-gray-600">Duration:</span>
                                <span className="font-medium">{formatDuration(appointment.start_time, appointment.end_time)}</span>
                              </div>
                              <div className="flex justify-between">
                                <span className="text-gray-600">Status:</span>
                                <span className={`font-medium ${getStatusColor(appointment.status)} px-2 py-1 rounded-full text-xs`}>
                                  {appointment.status.charAt(0).toUpperCase() + appointment.status.slice(1)}
                                </span>
                              </div>
                              <div className="flex justify-between">
                                <span className="text-gray-600">Amount Paid:</span>
                                <span className="font-medium text-teal-600">${appointment.amount}</span>
                              </div>
                            </div>
                          </div>

                          {/* Right Column - Actions */}
                          <div>
                            <h5 className="font-semibold text-gray-800 mb-3">Actions</h5>
                            <div className="space-y-3">
                              {/* Meeting Link Section */}
                              {appointment.meeting_link ? (
                                <div className="bg-teal-50 border border-teal-200 rounded-lg p-4">
                                  <div className="flex items-center justify-between mb-2">
                                    <div className="flex items-center text-teal-700">
                                      <FaVideo className="mr-2" />
                                      <span className="font-medium">Meeting Link Available</span>
                                    </div>
                                  </div>
                                  <p className="text-sm text-gray-600 mb-3 break-all">
                                    {appointment.meeting_link}
                                  </p>
                                  <div className="flex space-x-2">
                                    <button
                                      onClick={() => handleCopyMeetingLink(appointment.meeting_link)}
                                      className="flex-1 flex items-center justify-center px-3 py-2 bg-white border border-teal-300 text-teal-700 rounded-lg hover:bg-teal-50 transition-colors text-sm"
                                    >
                                      <FaCopy className="mr-2" />
                                      Copy Link
                                    </button>
                                    <button
                                      onClick={() => handleJoinMeeting(appointment.meeting_link)}
                                      className="flex-1 flex items-center justify-center px-3 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 transition-colors text-sm"
                                    >
                                      <FaExternalLinkAlt className="mr-2" />
                                      Join Meeting
                                    </button>
                                  </div>
                                </div>
                              ) : (
                                <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                                  <div className="flex items-center text-yellow-700">
                                    <FaClock className="mr-2" />
                                    <span className="font-medium">Awaiting Meeting Link</span>
                                  </div>
                                  <p className="text-sm text-yellow-600 mt-1">
                                    The tutor will provide a meeting link soon.
                                  </p>
                                </div>
                              )}

                              {/* Cancel Button for upcoming appointments */}
                              {['pending', 'confirmed', 'scheduled'].includes(appointment.status) && (
                                <button
                                  onClick={() => handleCancelAppointment(appointment.id)}
                                  className="w-full flex items-center justify-center px-4 py-2 bg-red-100 text-red-700 rounded-lg hover:bg-red-200 transition-colors text-sm font-medium"
                                >
                                  <FaTimesCircle className="mr-2" />
                                  Cancel Appointment
                                </button>
                              )}
                            </div>
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>
        ) : null}

        {/* Past Appointments */}
        {(statusFilter === 'all' || statusFilter !== 'upcoming') && pastAppointments.length > 0 && (
          <div>
            <h3 className="text-lg font-semibold text-gray-800 mb-4">Past Appointments</h3>
            <div className="space-y-4">
              {pastAppointments.map(appointment => (
                <div key={appointment.id} className="bg-white rounded-xl shadow-sm border overflow-hidden">
                  {/* Appointment Header */}
                  <div 
                    className="p-6 cursor-pointer hover:bg-gray-50 transition-colors"
                    onClick={() => toggleExpand(appointment.id)}
                  >
                    <div className="flex flex-col md:flex-row md:items-center justify-between">
                      <div className="flex items-center space-x-4 mb-4 md:mb-0">
                        <div className="flex-shrink-0">
                          {appointment.tutor_profile_picture ? (
                            <img
                              src={`https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${appointment.tutor_profile_picture}`}
                              alt={appointment.tutor_name}
                              className="w-14 h-14 rounded-full object-cover border-2 border-gray-100"
                            />
                          ) : (
                            <div className="w-14 h-14 rounded-full bg-teal-100 flex items-center justify-center">
                              <FaUser className="text-teal-600 text-xl" />
                            </div>
                          )}
                        </div>
                        <div>
                          <h4 className="font-semibold text-gray-800">{appointment.tutor_name}</h4>
                          <div className="flex items-center space-x-3 mt-1">
                            <span className="flex items-center text-sm text-gray-600">
                              <FaCalendarAlt className="mr-2" />
                              {formatDate(appointment.session_date)}
                            </span>
                            <span className="flex items-center text-sm text-gray-600">
                              <FaClock className="mr-2" />
                              {formatTime(appointment.start_time)} - {formatTime(appointment.end_time)}
                            </span>
                            <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(appointment.status)}`}>
                              <span className="flex items-center">
                                {getStatusIcon(appointment.status)}
                                <span className="ml-1">{appointment.status.charAt(0).toUpperCase() + appointment.status.slice(1)}</span>
                              </span>
                            </span>
                          </div>
                        </div>
                      </div>
                      <div className="flex items-center space-x-2">
                        <div className="text-right">
                          <div className="text-lg font-bold text-teal-600">
                            ${appointment.amount}
                          </div>
                          <div className="text-sm text-gray-500">
                            {formatDate(appointment.session_date)}
                          </div>
                        </div>
                        <button className="text-gray-400 hover:text-gray-600">
                          {expandedAppointment === appointment.id ? <FaChevronUp /> : <FaChevronDown />}
                        </button>
                      </div>
                    </div>
                  </div>

                  {/* Expanded Details for Past Appointments */}
                  {expandedAppointment === appointment.id && (
                    <div className="border-t border-gray-100 p-6">
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        {/* Left Column - Appointment Details */}
                        <div>
                          <h5 className="font-semibold text-gray-800 mb-3">Session Details</h5>
                          <div className="space-y-3">
                            <div className="flex justify-between">
                              <span className="text-gray-600">Tutor:</span>
                              <span className="font-medium">{appointment.tutor_name}</span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-gray-600">Date:</span>
                              <span className="font-medium">{formatDate(appointment.session_date)}</span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-gray-600">Time:</span>
                              <span className="font-medium">{formatTime(appointment.start_time)} - {formatTime(appointment.end_time)}</span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-gray-600">Duration:</span>
                              <span className="font-medium">{formatDuration(appointment.start_time, appointment.end_time)}</span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-gray-600">Status:</span>
                              <span className={`font-medium ${getStatusColor(appointment.status)} px-2 py-1 rounded-full text-xs`}>
                                {appointment.status.charAt(0).toUpperCase() + appointment.status.slice(1)}
                              </span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-gray-600">Amount Paid:</span>
                              <span className="font-medium text-teal-600">${appointment.amount}</span>
                            </div>
                          </div>
                        </div>

                        {/* Right Column - Actions & Feedback */}
                        <div>
                          <h5 className="font-semibold text-gray-800 mb-3">Session Feedback</h5>
                          <div className="space-y-4">
                            {/* For Completed Sessions */}
                            {appointment.status === 'completed' && (
                              <>
                                {/* Student's Feedback Display/Submission */}
                                {appointment.student_feedback && appointment.student_feedback.trim() !== "" ? (
                                  <div className="bg-green-50 border border-green-200 rounded-lg p-4">
                                    <div className="flex items-center justify-between mb-2">
                                      <div className="flex items-center text-green-700">
                                        <FaCommentDots className="mr-2" />
                                        <span className="font-medium">Your Feedback</span>
                                      </div>
                                    </div>
                                    <p className="text-sm text-gray-700 whitespace-pre-line mb-2">
                                      {appointment.student_feedback}
                                    </p>
                                    {appointment.rating && (
                                      <div className="flex items-center mb-2">
                                        <span className="text-sm text-gray-600 mr-2">Your Rating:</span>
                                        <div className="flex">
                                          {[1, 2, 3, 4, 5].map(star => (
                                            <FaStar
                                              key={star}
                                              className={`text-sm ${star <= appointment.rating ? 'text-yellow-400' : 'text-gray-300'}`}
                                            />
                                          ))}
                                        </div>
                                      </div>
                                    )}
                                    <p className="text-xs text-green-600">
                                      Feedback submitted ✓
                                    </p>
                                  </div>
                                ) : (
                                  <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                                    <div className="flex items-center text-yellow-700 mb-2">
                                      <FaCommentDots className="mr-2" />
                                      <span className="font-medium">Provide Your Feedback</span>
                                    </div>
                                    <p className="text-sm text-yellow-600 mb-3">
                                      Help improve the tutor's service by sharing your experience.
                                    </p>
                                    <button
                                      onClick={() => showFeedbackDialog(appointment)}
                                      className="w-full flex items-center justify-center px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 transition-colors text-sm font-medium"
                                    >
                                      <FaEdit className="mr-2" />
                                      Submit Feedback
                                    </button>
                                  </div>
                                )}

                                {/* Foreign Student Feedback Display */}
                                {appointment.notes && appointment.notes.trim() !== "" && (
                                  <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                                    <div className="flex items-center text-blue-700 mb-2">
                                      <FaCommentDots className="mr-2" />
                                      <span className="font-medium">Tutor's Feedback</span>
                                    </div>
                                    <p className="text-sm text-gray-700 whitespace-pre-line">
                                      {appointment.notes}
                                    </p>
                                    <p className="text-xs text-blue-600 mt-2">
                                      Feedback from tutor
                                    </p>
                                  </div>
                                )}
                              </>
                            )}

                            {/* For Cancelled Sessions */}
                            {appointment.status === 'cancelled' && appointment.notes && appointment.notes.trim() !== "" && (
                              <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
                                <div className="flex items-center text-gray-700 mb-2">
                                  <FaCommentDots className="mr-2" />
                                  <span className="font-medium">Cancellation Reason</span>
                                </div>
                                <p className="text-sm text-gray-700 whitespace-pre-line">
                                  {appointment.notes}
                                </p>
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

// Helper function to calculate duration in hours
const calculateDurationHours = (startTime, endTime) => {
  const [startHour, startMinute] = startTime.split(':').map(Number);
  const [endHour, endMinute] = endTime.split(':').map(Number);
  
  const startTotal = startHour * 60 + startMinute;
  const endTotal = endHour * 60 + endMinute;
  
  return (endTotal - startTotal) / 60;
};

export default StudentAppointments;