'use client';

import { useState, useEffect } from 'react';
import Image from 'next/image';
import { X } from 'lucide-react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';

export default function AppointmentModal({ doctor, onClose }) {
  const [selectedDate, setSelectedDate] = useState(null); // now Date object
  const [selectedTime, setSelectedTime] = useState('');
  const [timeSlots, setTimeSlots] = useState([]);
  const [loadingSlots, setLoadingSlots] = useState(false);

  const doctorName = `${doctor.firstName} ${doctor.lastName}`;
  const backendUrl = process.env.NEXT_PUBLIC_BACKEND_URL || '';
  const doctorImage = doctor?.avatar
    ? doctor.avatar
    : '/images/patient2.jpg';

  const today = new Date();

  useEffect(() => {
    const fetchAvailableSlots = async () => {
      if (!selectedDate) return;
      setLoadingSlots(true);
      try {
        const formattedDate = selectedDate.toISOString().split('T')[0];
        const res = await fetch(`/api/consultations/availability/free?doctorId=${doctor.userId}&date=${formattedDate}`);
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || 'Failed to fetch available slots');

        const transformed = data.freeSlots.map((time) => ({
          time: convertToReadableRange(time),
          raw: time,
          disabled: false,
        }));

        setTimeSlots(transformed);
      } catch (err) {
        console.error(err);
        setTimeSlots([]);
      } finally {
        setLoadingSlots(false);
      }
    };

    fetchAvailableSlots();
  }, [selectedDate, doctor.userId]);

  const convertToReadableRange = (time) => {
    const [hourStr, minuteStr] = time.split(':');
    let hour = parseInt(hourStr, 10);
    const endHour = hour + 2;
    const ampm = hour >= 12 ? 'PM' : 'AM';
    const endAmpm = endHour >= 12 ? 'PM' : 'AM';

    const startHourDisplay = hour > 12 ? hour - 12 : hour === 0 ? 12 : hour;
    const endHourDisplay = endHour > 12 ? endHour - 12 : endHour === 0 ? 12 : endHour;

    return `${startHourDisplay} ${ampm} - ${endHourDisplay} ${endAmpm}`;
  };

  const handleBook = async () => {
    if (!selectedDate || !selectedTime) return;

    try {
      const selectedSlot = timeSlots.find((s) => s.time === selectedTime);
      if (!selectedSlot) throw new Error('Selected time slot not found');

      const formattedDate = selectedDate.toISOString().split('T')[0];
      const appointmentDateTime = new Date(`${formattedDate}T${selectedSlot.raw}:00`);

      const payload = {
        doctorId: doctor.id,
        doctorUserId: doctor.userId,
        doctorName,
        appointmentDateTime: appointmentDateTime.toISOString(),
        timeRange: selectedTime,
      };

      const res = await fetch('/api/appointmentbooking', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      const result = await res.json();
      if (!res.ok) throw new Error(result.error || 'Failed to book appointment');

      alert(`✅ Appointment booked on ${formattedDate} at ${selectedTime}`);
      onClose();
    } catch (err) {
      console.error('Booking error:', err);
      alert('❌ Failed to book appointment');
    }
  };

  return (
    <div className="fixed inset-0 bg-white/30 backdrop-blur-sm flex items-center justify-center z-50 px-4">
      <div className="bg-white w-full max-w-md rounded-xl shadow-lg p-5 relative">
        <button
          onClick={onClose}
          className="absolute top-3 right-3 text-gray-500 hover:text-red-500"
        >
          <X />
        </button>

        {/* Doctor Info */}
        <div className="flex flex-col items-center text-center mb-4">
          <div className="w-20 h-20 relative rounded-full overflow-hidden border-4 border-purple-500 shadow mb-2">
            <img
              src={doctorImage}
              alt={`${doctor?.firstName || ''} ${doctor?.lastName || ''}`}
              width={80}
              height={80}
              className="rounded-full border-4 border-white shadow-md object-cover"
            />
          </div>
          <h2 className="text-xl font-bold">{doctorName}</h2>
          <p className="text-sm text-gray-600">{doctor.specialization}</p>
          <p className="text-sm text-gray-500">
            Email: {doctor.email || 'doctor@example.com'}
          </p>
        </div>

        {/* Date Picker */}
        <label className="block text-sm font-semibold mb-1">Select Date</label>
        <DatePicker
          selected={selectedDate}
          onChange={(date) => {
            setSelectedTime('');
            setSelectedDate(date);
          }}
          minDate={today}
          placeholderText="Choose a date"
          className="w-full border border-gray-300 rounded px-3 py-2 mb-4"
          withPortal
        />

        {/* Time Slots */}
        {selectedDate && (
          <>
            <label className="block text-sm font-semibold mb-2">Available Time Slots</label>
            {loadingSlots ? (
              <p className="text-sm text-gray-500 mb-4">Loading slots...</p>
            ) : timeSlots.length === 0 ? (
              <p className="text-sm text-red-500 mb-4">No available slots for selected date</p>
            ) : (
              <div className="grid grid-cols-2 gap-2 mb-4">
                {timeSlots.map((slot, index) => (
                  <button
                    key={index}
                    disabled={slot.disabled}
                    onClick={() => setSelectedTime(slot.time)}
                    className={`py-2 rounded-lg text-sm font-medium border transition-all duration-200 ${
                      slot.disabled
                        ? 'bg-gray-200 text-gray-400 cursor-not-allowed'
                        : selectedTime === slot.time
                        ? 'bg-purple-600 text-white'
                        : 'bg-white hover:bg-purple-100'
                    }`}
                  >
                    {slot.time}
                  </button>
                ))}
              </div>
            )}
          </>
        )}

        {/* Confirm Button */}
        <button
          onClick={handleBook}
          disabled={!selectedDate || !selectedTime}
          className="w-full bg-purple-600 text-white py-2 rounded-lg font-semibold hover:bg-purple-700 disabled:opacity-50"
        >
          Confirm Appointment
        </button>
      </div>
    </div>
  );
}
