import React, { useState, useEffect } from 'react';
import './styles.css';

interface TimeSlot {
  time: string;
  available: boolean;
}

interface DayAvailability {
  date: string;
  slots: TimeSlot[];
}

export default function AvailabilityCalendar() {
  const [availability, setAvailability] = useState<DayAvailability[]>([]);
  const [selectedDate, setSelectedDate] = useState<string>(new Date().toISOString().split('T')[0]);
  const [calendarId, setCalendarId] = useState<number>(1);
  const [appointmentTypeId, setAppointmentTypeId] = useState<number>(1);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetchAvailability();
  }, [selectedDate, calendarId, appointmentTypeId]);

  const fetchAvailability = async () => {
    setLoading(true);
    try {
      // Mock data
      const mockSlots: TimeSlot[] = Array.from({ length: 16 }, (_, i) => ({
        time: `${9 + Math.floor(i / 2)}:${i % 2 === 0 ? '00' : '30'}`,
        available: Math.random() > 0.3
      }));
      setAvailability([{ date: selectedDate, slots: mockSlots }]);
    } catch (error) {
      console.error('Error fetching availability:', error);
    } finally {
      setLoading(false);
    }
  };

  const currentSlots = availability.find(d => d.date === selectedDate)?.slots || [];

  return (
    <div className="availability-calendar">
      <header>
        <h1>📅 Availability Calendar</h1>
        <button onClick={fetchAvailability}>🔄 Refresh</button>
      </header>

      <div className="controls">
        <div className="form-group">
          <label>Date</label>
          <input type="date" value={selectedDate} onChange={(e) => setSelectedDate(e.target.value)} />
        </div>
        <div className="form-group">
          <label>Calendar</label>
          <select value={calendarId} onChange={(e) => setCalendarId(Number(e.target.value))}>
            <option value={1}>Main Calendar</option>
            <option value={2}>Secondary Calendar</option>
          </select>
        </div>
        <div className="form-group">
          <label>Appointment Type</label>
          <select value={appointmentTypeId} onChange={(e) => setAppointmentTypeId(Number(e.target.value))}>
            <option value={1}>Consultation</option>
            <option value={2}>Follow-up</option>
            <option value={3}>Assessment</option>
          </select>
        </div>
      </div>

      {loading ? (
        <div className="loading-inline"><div className="spinner"></div></div>
      ) : (
        <div className="slots-grid">
          {currentSlots.map((slot, i) => (
            <div key={i} className={`slot ${slot.available ? 'available' : 'unavailable'}`}>
              <span className="time">{slot.time}</span>
              <span className="status">{slot.available ? '✓ Available' : '✗ Booked'}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
