'use client';

import { useState } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';

export default function AvailabilityForm({ doctorId, onClose }) {
  const [date, setDate] = useState(null); // Now using Date object
  const [selectedSlots, setSelectedSlots] = useState([]);
  const slots = ['10:00', '12:00', '14:00', '16:00', '18:00'];

  const toggleSlot = (slot) => {
    setSelectedSlots((prev) =>
      prev.includes(slot)
        ? prev.filter((s) => s !== slot)
        : [...prev, slot]
    );
  };

  const submitAvailability = async () => {
    try {
      if (!date || selectedSlots.length === 0) {
        alert('Please select a date and at least one time slot.');
        return;
      }

      const formattedDate = date.toISOString().split('T')[0];

      const res = await fetch('/api/consultations/availability/', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ doctorId, date: formattedDate, timeSlots: selectedSlots }),
      });

      if (!res.ok) throw new Error('Failed to set availability');

      alert('✅ Availability saved successfully!');
      onClose();
    } catch (err) {
      console.error(err);
      alert('❌ Error saving availability');
    }
  };

  return (
    <div>
      <label className="block text-sm font-medium mb-1">Select Date</label>
      <DatePicker
        selected={date}
        onChange={(d) => setDate(d)}
        minDate={new Date()}
        placeholderText="Choose a date"
        className="w-full border px-3 py-2 rounded mb-4"
        withPortal // improves mobile/iOS UX
      />

      <label className="block text-sm font-medium mb-2">Select Time Slots</label>
      <div className="flex flex-wrap gap-2 mb-4">
        {slots.map((slot) => (
          <button
            key={slot}
            onClick={() => toggleSlot(slot)}
            className={`px-3 py-1 rounded border text-sm ${
              selectedSlots.includes(slot)
                ? 'bg-purple-600 text-white'
                : 'bg-gray-100 hover:bg-purple-100'
            }`}
          >
            {slot}
          </button>
        ))}
      </div>

      <button
        onClick={submitAvailability}
        className="bg-purple-600 text-white w-full py-2 rounded hover:bg-purple-700"
      >
        Save Availability
      </button>
    </div>
  );
}
