import React, { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { appointmentService } from "../../services";

interface Props {
  doctorId: string;
  date: string; // YYYY-MM-DD
  onSelect: (time: string) => void; // HH:MM
}

const AvailableSlotsPicker: React.FC<Props> = ({
  doctorId,
  date,
  onSelect,
}) => {
  const [slots, setSlots] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    async function fetchSlots() {
      if (!doctorId || !date) return;

      console.log("🔍 [AvailableSlotsPicker] Buscando slots:", {
        doctorId,
        date,
      });

      setLoading(true);
      try {
        const res = await appointmentService.getAvailableSlots({
          doctor_id: doctorId,
          date: date,
        });

        console.log("📅 [AvailableSlotsPicker] Resposta da API:", res);

        setLoading(false);

        if (res.slots && Array.isArray(res.slots)) {
          const times = res.slots.filter((s) => s.available).map((s) => s.time);

          console.log("✅ [AvailableSlotsPicker] Horários disponíveis:", times);
          setSlots(times);
        } else {
          console.error(
            "❌ [AvailableSlotsPicker] Formato de resposta inválido:",
            res
          );
          toast.error("Erro ao processar horários disponíveis");
        }
      } catch (error) {
        console.error("❌ [AvailableSlotsPicker] Erro ao buscar slots:", error);
        setLoading(false);
        toast.error("Erro ao buscar horários disponíveis");
      }
    }
    void fetchSlots();
  }, [doctorId, date]);

  if (!date || !doctorId) return null;

  if (loading)
    return <div className="text-sm text-gray-500">Carregando horários...</div>;

  if (!slots.length)
    return (
      <div className="text-sm text-gray-500">
        Nenhum horário disponível para a data selecionada.
      </div>
    );

  return (
    <div className="grid grid-cols-3 md:grid-cols-6 gap-2">
      {slots.map((t) => (
        <button
          key={t}
          onClick={() => onSelect(t)}
          className="px-3 py-2 rounded bg-blue-50 hover:bg-blue-100 text-blue-700 text-sm"
        >
          {t}
        </button>
      ))}
    </div>
  );
};

export default AvailableSlotsPicker;
