'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Swal from 'sweetalert2';
import { 
  Calendar,
  Clock,
  Save,
  X,
  Plus,
  Trash2,
  CalendarCheck,
  CalendarX,
  Globe,
  AlertCircle,
  CheckCircle,
  XCircle,
  ChevronDown,
  RefreshCw
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';

const AvailabilitySchedule = () => {
  const router = useRouter();
  
  // Days of week configuration
  const daysOfWeek = [
    { id: 1, name: 'Monday', short: 'Mon', color: 'from-blue-500 to-cyan-500' },
    { id: 2, name: 'Tuesday', short: 'Tue', color: 'from-purple-500 to-pink-500' },
    { id: 3, name: 'Wednesday', short: 'Wed', color: 'from-emerald-500 to-teal-500' },
    { id: 4, name: 'Thursday', short: 'Thu', color: 'from-amber-500 to-orange-500' },
    { id: 5, name: 'Friday', short: 'Fri', color: 'from-rose-500 to-red-500' },
    { id: 6, name: 'Saturday', short: 'Sat', color: 'from-indigo-500 to-violet-500' },
    { id: 0, name: 'Sunday', short: 'Sun', color: 'from-green-500 to-lime-500' }
  ];

  // Generate time slots (30 min intervals)
  const generateTimeSlots = () => {
    const slots = [];
    for (let hour = 0; hour < 24; hour++) {
      for (let minute of [0, 30]) {
        const time = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
        const displayTime = `${hour % 12 || 12}:${minute.toString().padStart(2, '0')} ${hour >= 12 ? 'PM' : 'AM'}`;
        slots.push({ value: time, display: displayTime });
      }
    }
    return slots;
  };
  
  const timeSlots = generateTimeSlots();

  // Initial state for weekly schedule
  const [weeklySchedule, setWeeklySchedule] = useState(
    daysOfWeek.map(day => ({
      dayId: day.id,
      dayName: day.name,
      dayShort: day.short,
      dayColor: day.color,
      isAvailable: false,
      timeSlots: []
    }))
  );

  // Special dates (exceptions)
  const [specialDates, setSpecialDates] = useState([]);
  const [newSpecialDate, setNewSpecialDate] = useState({
    date: '',
    type: 'unavailable',
    timeSlots: [{ start: '09:00', end: '17:00', id: Date.now() }],
    reason: ''
  });

  const [isLoading, setIsLoading] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [timezone, setTimezone] = useState('UTC');
  const [viewMode, setViewMode] = useState('weekly'); // 'weekly' or 'special'

  // Load existing schedule
  useEffect(() => {
    fetchSchedule();
    fetchTimezone();
  }, []);

  const fetchSchedule = async () => {
    try {
      setIsLoading(true);
      const response = await fetch('/api/internal/foreign-student/availability', {
        method: 'GET',
        credentials: 'include'
      });

      if (response.ok) {
        const data = await response.json();
        if (data.success && data.schedule) {
          const updatedSchedule = weeklySchedule.map(day => {
            const savedDay = data.schedule.find(d => d.day_of_week === day.dayId);
            if (savedDay) {
              return {
                ...day,
                isAvailable: savedDay.is_available === 1 || savedDay.is_available === true,
                timeSlots: savedDay.time_slots || []
              };
            }
            return day;
          });
          setWeeklySchedule(updatedSchedule);
        }

        if (data.specialDates) {
          const processedSpecialDates = data.specialDates.map(date => ({
            ...date,
            timeSlots: date.time_slots || []
          }));
          setSpecialDates(processedSpecialDates);
        }
      }
    } catch (error) {
      console.error('Error fetching schedule:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const fetchTimezone = async () => {
    const userTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
    setTimezone(userTimezone);
  };

  // Toggle day availability
  const toggleDayAvailability = (dayId) => {
    setWeeklySchedule(prev => prev.map(day => 
      day.dayId === dayId 
        ? { ...day, isAvailable: !day.isAvailable }
        : day
    ));
  };

  // Add time slot to a day
  const addTimeSlot = (dayId) => {
    setWeeklySchedule(prev => prev.map(day => 
      day.dayId === dayId 
        ? { 
            ...day, 
            timeSlots: [
              ...day.timeSlots, 
              { start: '09:00', end: '17:00', id: Date.now() }
            ] 
          }
        : day
    ));
  };

  // Remove time slot from a day
  const removeTimeSlot = (dayId, slotIndex) => {
    setWeeklySchedule(prev => prev.map(day => 
      day.dayId === dayId 
        ? { 
            ...day, 
            timeSlots: day.timeSlots.filter((_, index) => index !== slotIndex)
          }
        : day
    ));
  };

  // Update time slot
  const updateTimeSlot = (dayId, slotIndex, field, value) => {
    setWeeklySchedule(prev => prev.map(day => 
      day.dayId === dayId 
        ? { 
            ...day, 
            timeSlots: day.timeSlots.map((slot, index) => 
              index === slotIndex ? { ...slot, [field]: value } : slot
            )
          }
        : day
    ));
  };

  // Add time slot to special date
  const addSpecialDateTimeSlot = () => {
    setNewSpecialDate(prev => ({
      ...prev,
      timeSlots: [
        ...prev.timeSlots,
        { start: '09:00', end: '17:00', id: Date.now() }
      ]
    }));
  };

  // Remove time slot from special date
  const removeSpecialDateTimeSlot = (slotIndex) => {
    setNewSpecialDate(prev => ({
      ...prev,
      timeSlots: prev.timeSlots.filter((_, index) => index !== slotIndex)
    }));
  };

  // Update special date time slot
  const updateSpecialDateTimeSlot = (slotIndex, field, value) => {
    setNewSpecialDate(prev => ({
      ...prev,
      timeSlots: prev.timeSlots.map((slot, index) => 
        index === slotIndex ? { ...slot, [field]: value } : slot
      )
    }));
  };

  // Add special date
  const addSpecialDate = () => {
    if (!newSpecialDate.date) {
      Swal.fire({
        icon: 'warning',
        title: 'Date Required',
        text: 'Please select a date',
        confirmButtonColor: '#0B6D76'
      });
      return;
    }

    const dateExists = specialDates.some(date => date.date === newSpecialDate.date);
    if (dateExists) {
      Swal.fire({
        icon: 'warning',
        title: 'Date Already Added',
        text: 'This date is already in your special dates',
        confirmButtonColor: '#0B6D76'
      });
      return;
    }

    // Validate time slots for available dates
    if (newSpecialDate.type === 'available') {
      const invalidSlots = newSpecialDate.timeSlots.filter(slot => slot.start >= slot.end);
      if (invalidSlots.length > 0) {
        Swal.fire({
          icon: 'error',
          title: 'Invalid Time Slots',
          text: 'End time must be after start time for all time slots',
          confirmButtonColor: '#0B6D76'
        });
        return;
      }
    }

    setSpecialDates(prev => [...prev, { 
      ...newSpecialDate, 
      id: Date.now(),
      timeSlots: newSpecialDate.type === 'available' ? newSpecialDate.timeSlots : []
    }]);
    setNewSpecialDate({
      date: '',
      type: 'unavailable',
      timeSlots: [{ start: '09:00', end: '17:00', id: Date.now() }],
      reason: ''
    });
  };

  // Remove special date
  const removeSpecialDate = (dateId) => {
    Swal.fire({
      title: 'Remove Date?',
      text: 'Are you sure you want to remove this special date?',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#ef4444',
      cancelButtonColor: '#6b7280',
      confirmButtonText: 'Yes, remove it'
    }).then((result) => {
      if (result.isConfirmed) {
        setSpecialDates(prev => prev.filter(date => date.id !== dateId));
        Swal.fire({
          title: 'Removed!',
          text: 'The special date has been removed.',
          icon: 'success',
          timer: 1500,
          showConfirmButton: false
        });
      }
    });
  };

  // Save schedule
  const saveSchedule = async () => {
    try {
      setIsSaving(true);

      // Validate schedule
      const validationErrors = [];
      weeklySchedule.forEach(day => {
        if (day.isAvailable) {
          if (day.timeSlots.length === 0) {
            validationErrors.push(`${day.dayName}: No time slots added`);
          }
          day.timeSlots.forEach((slot, index) => {
            if (slot.start >= slot.end) {
              validationErrors.push(`${day.dayName} Slot ${index + 1}: End time must be after start time`);
            }
          });
        }
      });

      // Validate special dates
      specialDates.forEach(date => {
        if (date.type === 'available') {
          date.timeSlots.forEach((slot, index) => {
            if (slot.start >= slot.end) {
              validationErrors.push(`${date.date} Slot ${index + 1}: End time must be after start time`);
            }
          });
        }
      });

      if (validationErrors.length > 0) {
        Swal.fire({
          icon: 'error',
          title: 'Validation Errors',
          html: `
            <div class="text-left">
              <div class="bg-red-50 border-l-4 border-red-500 p-4 mb-4">
                <div class="flex items-center">
                  <AlertCircle class="h-5 w-5 text-red-500 mr-3" />
                  <p class="text-red-800 font-semibold">Please fix the following issues:</p>
                </div>
              </div>
              <ul class="space-y-1 max-h-40 overflow-y-auto">
                ${validationErrors.map(error => `<li class="text-sm text-gray-700 flex items-center"><span class="w-2 h-2 bg-red-500 rounded-full mr-2"></span>${error}</li>`).join('')}
              </ul>
            </div>
          `,
          confirmButtonColor: '#0B6D76'
        });
        return;
      }

      // Prepare payload
      const payload = {
        weeklySchedule: weeklySchedule.map(day => ({
          dayId: day.dayId,
          dayName: day.dayName,
          isAvailable: Boolean(day.isAvailable),
          timeSlots: day.timeSlots.map(slot => ({
            start: slot.start,
            end: slot.end
          }))
        })),
        specialDates: specialDates.map(date => ({
          date: date.date,
          type: date.type,
          reason: date.reason,
          timeSlots: date.type === 'available' ? date.timeSlots.map(slot => ({
            start: slot.start,
            end: slot.end
          })) : []
        })),
        timezone
      };

      const response = await fetch('/api/internal/foreign-student/availability', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload),
        credentials: 'include'
      });

      const data = await response.json();

      if (response.ok) {
        Swal.fire({
          icon: 'success',
          title: 'Schedule Saved!',
          text: 'Your availability schedule has been updated successfully.',
          confirmButtonColor: '#0B6D76',
          timer: 2000,
          showConfirmButton: false
        });

        // Refresh the data
        fetchSchedule();
      } else {
        Swal.fire({
          icon: 'error',
          title: 'Save Failed',
          text: data.message || 'Failed to save schedule. Please try again.',
          confirmButtonColor: '#0B6D76'
        });
      }
    } catch (error) {
      console.error('Error saving schedule:', error);
      Swal.fire({
        icon: 'error',
        title: 'Network Error',
        text: 'Please check your connection and try again.',
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setIsSaving(false);
    }
  };

  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 schedule...</p>
          <p className="text-gray-400 text-sm mt-2">Fetching your availability 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-6xl 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">Availability 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">
            Set Your Teaching Schedule
          </h1>
          <p className="text-gray-600 text-lg max-w-2xl mx-auto mb-6">
            Configure your weekly availability and special dates for student appointments
          </p>
          <div className="inline-flex items-center gap-2 px-4 py-2 bg-gray-100 rounded-xl">
            <Globe className="w-4 h-4 text-gray-600" />
            <span className="text-sm text-gray-700">
              Timezone: <span className="font-medium text-blue-600">{timezone}</span>
            </span>
          </div>
        </motion.div>

        {/* View Mode Toggle */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="flex items-center justify-center mb-8"
        >
          <div className="bg-white rounded-xl p-1 border border-gray-200 shadow-sm inline-flex">
            <button
              onClick={() => setViewMode('weekly')}
              className={`px-6 py-3 rounded-lg font-medium transition-all duration-200 ${
                viewMode === 'weekly'
                  ? 'bg-gradient-to-r from-blue-500 to-cyan-500 text-white shadow-md'
                  : 'text-gray-600 hover:text-gray-800'
              }`}
            >
              Weekly Schedule
            </button>
            <button
              onClick={() => setViewMode('special')}
              className={`px-6 py-3 rounded-lg font-medium transition-all duration-200 ${
                viewMode === 'special'
                  ? 'bg-gradient-to-r from-purple-500 to-pink-500 text-white shadow-md'
                  : 'text-gray-600 hover:text-gray-800'
              }`}
            >
              Special Dates
            </button>
          </div>
        </motion.div>

        {/* Weekly Schedule Section */}
        <AnimatePresence mode="wait">
          {viewMode === 'weekly' ? (
            <motion.div
              key="weekly"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              className="space-y-8"
            >
              <div className="bg-white rounded-2xl p-8 border border-gray-200 shadow-sm">
                <div className="flex items-center justify-between mb-8">
                  <div>
                    <h2 className="text-2xl font-bold text-gray-800 mb-2">Weekly Schedule</h2>
                    <p className="text-gray-600">Set your regular weekly teaching availability</p>
                  </div>
                  <motion.button
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    onClick={saveSchedule}
                    disabled={isSaving}
                    className="flex items-center gap-2 px-6 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 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {isSaving ? (
                      <>
                        <RefreshCw className="w-5 h-5 animate-spin" />
                        Saving...
                      </>
                    ) : (
                      <>
                        <Save className="w-5 h-5" />
                        Save Schedule
                      </>
                    )}
                  </motion.button>
                </div>

                {/* Days Grid - 2 days per row */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  {weeklySchedule.map(day => (
                    <motion.div
                      key={day.dayId}
                      whileHover={{ y: -4 }}
                      className={`relative overflow-hidden rounded-2xl border-2 p-6 transition-all duration-300 ${
                        day.isAvailable 
                          ? 'border-emerald-200 bg-gradient-to-b from-emerald-50 to-white' 
                          : 'border-gray-200 bg-gradient-to-b from-gray-50 to-white'
                      }`}
                    >
                      {/* Day Header */}
                      <div className="flex items-start justify-between mb-6">
                        <div>
                          <div className={`w-14 h-14 rounded-xl mb-3 flex items-center justify-center bg-gradient-to-br ${day.dayColor}`}>
                            <span className="text-white font-bold text-lg">{day.dayShort}</span>
                          </div>
                          <h3 className="text-xl font-bold text-gray-800">{day.dayName}</h3>
                          <div className="flex items-center gap-2 mt-1">
                            <div className={`w-2 h-2 rounded-full ${day.isAvailable ? 'bg-emerald-500' : 'bg-gray-400'}`}></div>
                            <span className={`text-sm font-medium ${day.isAvailable ? 'text-emerald-600' : 'text-gray-500'}`}>
                              {day.isAvailable ? 'Available' : 'Not Available'}
                            </span>
                          </div>
                        </div>
                        <motion.button
                          whileTap={{ scale: 0.9 }}
                          onClick={() => toggleDayAvailability(day.dayId)}
                          className={`relative overflow-hidden rounded-lg px-4 py-2 font-medium text-sm transition-all duration-200 ${
                            day.isAvailable
                              ? 'bg-emerald-100 text-emerald-700 hover:bg-emerald-200'
                              : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
                          }`}
                        >
                          {day.isAvailable ? 'Disable' : 'Enable'}
                        </motion.button>
                      </div>

                      {day.isAvailable && (
                        <div className="space-y-4">
                          {/* Time Slots */}
                          <div>
                            <div className="flex items-center justify-between mb-3">
                              <span className="text-sm font-semibold text-gray-700">Time Slots</span>
                              <motion.button
                                whileHover={{ scale: 1.1 }}
                                whileTap={{ scale: 0.9 }}
                                onClick={() => addTimeSlot(day.dayId)}
                                className="text-blue-600 hover:text-blue-800 text-sm flex items-center gap-1 font-medium"
                              >
                                <Plus className="w-4 h-4" />
                                Add Slot
                              </motion.button>
                            </div>
                            
                            {day.timeSlots.length === 0 ? (
                              <div className="text-center py-4 bg-gray-50 rounded-xl border border-dashed border-gray-300">
                                <Clock className="w-8 h-8 text-gray-400 mx-auto mb-2" />
                                <p className="text-sm text-gray-500">No time slots added</p>
                              </div>
                            ) : (
                              <div className="space-y-3">
                                {day.timeSlots.map((slot, index) => (
                                  <motion.div
                                    key={index}
                                    initial={{ opacity: 0, x: -20 }}
                                    animate={{ opacity: 1, x: 0 }}
                                    className="flex items-center gap-3 p-3 bg-white border border-gray-200 rounded-xl"
                                  >
                                    <div className="flex-1 grid grid-cols-2 gap-3">
                                      <div>
                                        <label className="text-xs font-medium text-gray-500 mb-1 block">Start</label>
                                        <div className="relative">
                                          <select
                                            value={slot.start}
                                            onChange={(e) => updateTimeSlot(day.dayId, index, 'start', e.target.value)}
                                            className="w-full appearance-none bg-gray-50 border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-all duration-200"
                                          >
                                            {timeSlots.map(time => (
                                              <option key={time.value} value={time.value}>
                                                {time.display}
                                              </option>
                                            ))}
                                          </select>
                                          <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3">
                                            <ChevronDown className="w-4 h-4 text-gray-400" />
                                          </div>
                                        </div>
                                      </div>
                                      <div>
                                        <label className="text-xs font-medium text-gray-500 mb-1 block">End</label>
                                        <div className="relative">
                                          <select
                                            value={slot.end}
                                            onChange={(e) => updateTimeSlot(day.dayId, index, 'end', e.target.value)}
                                            className="w-full appearance-none bg-gray-50 border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-all duration-200"
                                          >
                                            {timeSlots.map(time => (
                                              <option key={time.value} value={time.value}>
                                                {time.display}
                                              </option>
                                            ))}
                                          </select>
                                          <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3">
                                            <ChevronDown className="w-4 h-4 text-gray-400" />
                                          </div>
                                        </div>
                                      </div>
                                    </div>
                                    <motion.button
                                      whileHover={{ scale: 1.1 }}
                                      whileTap={{ scale: 0.9 }}
                                      onClick={() => removeTimeSlot(day.dayId, index)}
                                      className="text-rose-500 hover:text-rose-700 p-2"
                                      title="Remove slot"
                                    >
                                      <Trash2 className="w-4 h-4" />
                                    </motion.button>
                                  </motion.div>
                                ))}
                              </div>
                            )}
                          </div>
                        </div>
                      )}
                    </motion.div>
                  ))}
                </div>
              </div>
            </motion.div>
          ) : (
            <motion.div
              key="special"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              className="space-y-8"
            >
              <div className="bg-white rounded-2xl p-8 border border-gray-200 shadow-sm">
                <div className="flex items-center justify-between mb-8">
                  <div>
                    <h2 className="text-2xl font-bold text-gray-800 mb-2">Special Dates</h2>
                    <p className="text-gray-600">Add exceptions for holidays or special availability</p>
                  </div>
                  <motion.button
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    onClick={saveSchedule}
                    disabled={isSaving}
                    className="flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-purple-500 to-pink-500 text-white rounded-xl hover:shadow-lg transition-all duration-200 font-medium disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {isSaving ? (
                      <>
                        <RefreshCw className="w-5 h-5 animate-spin" />
                        Saving...
                      </>
                    ) : (
                      <>
                        <Save className="w-5 h-5" />
                        Save Changes
                      </>
                    )}
                  </motion.button>
                </div>

                {/* Add Special Date Form */}
                <div className="bg-gradient-to-br from-gray-50 to-white p-6 rounded-2xl border border-gray-200 mb-8">
                  <h3 className="text-lg font-bold text-gray-800 mb-6">Add New Special Date</h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        Date
                      </label>
                      <input
                        type="date"
                        value={newSpecialDate.date}
                        onChange={(e) => setNewSpecialDate(prev => ({ ...prev, date: e.target.value }))}
                        className="w-full border border-gray-300 rounded-xl px-4 py-3 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-all duration-200"
                        min={new Date().toISOString().split('T')[0]}
                      />
                    </div>
                    
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        Type
                      </label>
                      <select
                        value={newSpecialDate.type}
                        onChange={(e) => setNewSpecialDate(prev => ({ ...prev, type: e.target.value }))}
                        className="w-full border border-gray-300 rounded-xl px-4 py-3 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-all duration-200"
                      >
                        <option value="unavailable">Unavailable (Day Off)</option>
                        <option value="available">Available (Special Hours)</option>
                      </select>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        Reason (Optional)
                      </label>
                      <input
                        type="text"
                        value={newSpecialDate.reason}
                        onChange={(e) => setNewSpecialDate(prev => ({ ...prev, reason: e.target.value }))}
                        placeholder="e.g., Holiday, Personal Day, etc."
                        className="w-full border border-gray-300 rounded-xl px-4 py-3 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-all duration-200"
                      />
                    </div>

                    <div className="flex items-end">
                      <motion.button
                        whileHover={{ scale: 1.05 }}
                        whileTap={{ scale: 0.95 }}
                        onClick={addSpecialDate}
                        className="w-full 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"
                      >
                        <Plus className="w-5 h-5" />
                        Add Date
                      </motion.button>
                    </div>
                  </div>

                  {newSpecialDate.type === 'available' && (
                    <div className="mt-6 p-6 bg-white border border-gray-200 rounded-2xl">
                      <div className="flex items-center justify-between mb-4">
                        <span className="text-sm font-semibold text-gray-700">Time Slots for This Date</span>
                        <motion.button
                          whileHover={{ scale: 1.1 }}
                          whileTap={{ scale: 0.9 }}
                          onClick={addSpecialDateTimeSlot}
                          className="text-blue-600 hover:text-blue-800 text-sm flex items-center gap-1 font-medium"
                        >
                          <Plus className="w-4 h-4" />
                          Add Time Slot
                        </motion.button>
                      </div>
                      
                      {newSpecialDate.timeSlots.length === 0 ? (
                        <div className="text-center py-6 bg-gray-50 rounded-xl border border-dashed border-gray-300">
                          <Clock className="w-8 h-8 text-gray-400 mx-auto mb-2" />
                          <p className="text-sm text-gray-500">No time slots added for this date</p>
                        </div>
                      ) : (
                        <div className="space-y-3">
                          {newSpecialDate.timeSlots.map((slot, index) => (
                            <motion.div
                              key={index}
                              initial={{ opacity: 0, x: -20 }}
                              animate={{ opacity: 1, x: 0 }}
                              className="flex items-center gap-3 p-3 bg-gray-50 border border-gray-200 rounded-xl"
                            >
                              <div className="flex-1 grid grid-cols-2 gap-3">
                                <div>
                                  <label className="text-xs font-medium text-gray-500 mb-1 block">Start</label>
                                  <div className="relative">
                                    <select
                                      value={slot.start}
                                      onChange={(e) => updateSpecialDateTimeSlot(index, 'start', e.target.value)}
                                      className="w-full appearance-none bg-white border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-all duration-200"
                                    >
                                      {timeSlots.map(time => (
                                        <option key={time.value} value={time.value}>
                                          {time.display}
                                        </option>
                                      ))}
                                    </select>
                                    <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3">
                                      <ChevronDown className="w-4 h-4 text-gray-400" />
                                    </div>
                                  </div>
                                </div>
                                <div>
                                  <label className="text-xs font-medium text-gray-500 mb-1 block">End</label>
                                  <div className="relative">
                                    <select
                                      value={slot.end}
                                      onChange={(e) => updateSpecialDateTimeSlot(index, 'end', e.target.value)}
                                      className="w-full appearance-none bg-white border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none transition-all duration-200"
                                    >
                                      {timeSlots.map(time => (
                                        <option key={time.value} value={time.value}>
                                          {time.display}
                                        </option>
                                      ))}
                                    </select>
                                    <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3">
                                      <ChevronDown className="w-4 h-4 text-gray-400" />
                                    </div>
                                  </div>
                                </div>
                              </div>
                              <motion.button
                                whileHover={{ scale: 1.1 }}
                                whileTap={{ scale: 0.9 }}
                                onClick={() => removeSpecialDateTimeSlot(index)}
                                className="text-rose-500 hover:text-rose-700 p-2"
                                title="Remove slot"
                              >
                                <Trash2 className="w-4 h-4" />
                              </motion.button>
                            </motion.div>
                          ))}
                        </div>
                      )}
                    </div>
                  )}
                </div>

                {/* Special Dates List */}
                {specialDates.length > 0 ? (
                  <div className="space-y-4">
                    <h3 className="text-lg font-bold text-gray-800 mb-4">Added Special Dates</h3>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      {specialDates.map(date => (
                        <motion.div
                          key={date.id}
                          initial={{ opacity: 0, y: 20 }}
                          animate={{ opacity: 1, y: 0 }}
                          className={`border rounded-2xl p-5 ${date.type === 'available' ? 'bg-emerald-50 border-emerald-200' : 'bg-rose-50 border-rose-200'}`}
                        >
                          <div className="flex items-start justify-between mb-4">
                            <div className="flex-1">
                              <div className="flex items-center gap-3 mb-2">
                                <div className={`w-10 h-10 rounded-xl flex items-center justify-center ${date.type === 'available' ? 'bg-emerald-100' : 'bg-rose-100'}`}>
                                  {date.type === 'available' ? 
                                    <CalendarCheck className="w-5 h-5 text-emerald-600" /> : 
                                    <CalendarX className="w-5 h-5 text-rose-600" />
                                  }
                                </div>
                                <div>
                                  <span className="font-bold text-gray-800">
                                    {new Date(date.date).toLocaleDateString('en-US', {
                                      weekday: 'short',
                                      year: 'numeric',
                                      month: 'short',
                                      day: 'numeric'
                                    })}
                                  </span>
                                  <div className="flex items-center gap-2 mt-1">
                                    <span className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-medium ${date.type === 'available' ? 'bg-emerald-100 text-emerald-700' : 'bg-rose-100 text-rose-700'}`}>
                                      {date.type === 'available' ? <CheckCircle className="w-3 h-3" /> : <XCircle className="w-3 h-3" />}
                                      {date.type === 'available' ? 'Available' : 'Unavailable'}
                                    </span>
                                    {date.reason && (
                                      <span className="text-sm text-gray-600">- {date.reason}</span>
                                    )}
                                  </div>
                                </div>
                              </div>
                              
                              {date.type === 'available' && date.timeSlots && date.timeSlots.length > 0 && (
                                <div className="mt-4">
                                  <span className="text-sm font-semibold text-gray-700">Time Slots:</span>
                                  <div className="flex flex-wrap gap-2 mt-2">
                                    {date.timeSlots.map((slot, index) => (
                                      <span key={index} className="px-3 py-2 bg-white text-emerald-700 text-sm rounded-lg border border-emerald-200 font-medium">
                                        {timeSlots.find(t => t.value === slot.start)?.display} - {timeSlots.find(t => t.value === slot.end)?.display}
                                      </span>
                                    ))}
                                  </div>
                                </div>
                              )}
                            </div>
                            <motion.button
                              whileHover={{ scale: 1.1 }}
                              whileTap={{ scale: 0.9 }}
                              onClick={() => removeSpecialDate(date.id)}
                              className="text-rose-500 hover:text-rose-700 p-2"
                              title="Remove date"
                            >
                              <Trash2 className="w-5 h-5" />
                            </motion.button>
                          </div>
                        </motion.div>
                      ))}
                    </div>
                  </div>
                ) : (
                  <div className="text-center py-12 bg-gray-50 rounded-2xl border border-dashed border-gray-300">
                    <Calendar className="w-12 h-12 text-gray-400 mx-auto mb-4" />
                    <h3 className="text-xl font-bold text-gray-700 mb-2">No special dates added yet</h3>
                    <p className="text-gray-500 max-w-md mx-auto">
                      Add holidays, vacations, or special working days above
                    </p>
                  </div>
                )}
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </div>
  );
};

export default AvailabilitySchedule;