import { useState, useEffect, useCallback, useRef } from "react";
import { useNavigate } from "react-router-dom";
import {
  format,
  addMonths,
  subMonths,
  startOfMonth,
  endOfMonth,
  eachDayOfInterval,
  isSameMonth,
  isSameDay,
  isBefore,
  startOfDay,
} from "date-fns";
import { ptBR } from "date-fns/locale";
import {
  MapPin,
  Video,
  Clock,
  ChevronLeft,
  ChevronRight,
  AlertCircle,
  CheckCircle2,
  Search,
} from "lucide-react";
import { appointmentService, patientService } from "../services";
import { useAuth } from "../hooks/useAuth";

interface Medico {
  id: string;
  nome: string;
  especialidade: string;
  crm: string;
  foto?: string;
  email?: string;
  telefone?: string;
  valorConsulta?: number;
}

interface AgendamentoConsultaProps {
  medicos: Medico[];
}

export default function AgendamentoConsulta({
  medicos,
}: AgendamentoConsultaProps) {
  const { user } = useAuth();
  const navigate = useNavigate();
  const [filteredMedicos, setFilteredMedicos] = useState<Medico[]>(medicos);
  const detailsRef = useRef<HTMLDivElement>(null);
  const [patientId, setPatientId] = useState<string | null>(null);

  // Busca o patient_id da tabela patients usando o user_id
  useEffect(() => {
    const fetchPatientId = async () => {
      if (!user?.id) {
        console.warn("[AgendamentoConsulta] Usuário não autenticado");
        return;
      }

      try {
        const patient = await patientService.getByUserId(user.id);
        if (patient?.id) {
          setPatientId(patient.id);
          console.log("[AgendamentoConsulta] Patient ID encontrado:", patient.id);
        } else {
          console.warn("[AgendamentoConsulta] Paciente não encontrado na tabela patients");
        }
      } catch (error) {
        console.error("[AgendamentoConsulta] Erro ao buscar patient_id:", error);
      }
    };

    fetchPatientId();
  }, [user?.id]);

  // Sempre que a lista de médicos da API mudar, atualiza o filtro
  useEffect(() => {
    setFilteredMedicos(medicos);
  }, [medicos]);
  const [selectedMedico, setSelectedMedico] = useState<Medico | null>(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedSpecialty, setSelectedSpecialty] = useState("all");
  const [currentMonth, setCurrentMonth] = useState(new Date());
  const [selectedDate, setSelectedDate] = useState<Date | undefined>(undefined);
  const [availableSlots, setAvailableSlots] = useState<string[]>([]);
  const [selectedTime, setSelectedTime] = useState("");
  const [appointmentType, setAppointmentType] = useState<
    "presencial" | "online"
  >("presencial");
  const [motivo, setMotivo] = useState("");
  const [showConfirmDialog, setShowConfirmDialog] = useState(false);
  const [bookingError, setBookingError] = useState("");
  const [showResultModal, setShowResultModal] = useState(false);
  const [resultType, setResultType] = useState<"success" | "error">("success");
  const [availableDates, setAvailableDates] = useState<Set<string>>(new Set());

  // Removido o carregamento interno de médicos, pois agora vem por prop

  useEffect(() => {
    let filtered = medicos;
    if (searchTerm) {
      filtered = filtered.filter(
        (medico) =>
          medico.nome.toLowerCase().includes(searchTerm.toLowerCase()) ||
          medico.especialidade.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }
    if (selectedSpecialty !== "all") {
      filtered = filtered.filter(
        (medico) => medico.especialidade === selectedSpecialty
      );
    }
    setFilteredMedicos(filtered);
  }, [searchTerm, selectedSpecialty, medicos]);

  const specialties = Array.from(new Set(medicos.map((m) => m.especialidade)));

  // Busca as disponibilidades do médico e calcula as datas disponíveis
  useEffect(() => {
    const loadAvailableDates = async () => {
      if (!selectedMedico) {
        setAvailableDates(new Set());
        return;
      }

      try {
        const { availabilityService } = await import("../services");

        console.log(
          "[AgendamentoConsulta] Buscando disponibilidades para médico:",
          {
            id: selectedMedico.id,
            nome: selectedMedico.nome,
          }
        );

        // Busca todas as disponibilidades ativas do médico
        const availabilities = await availabilityService.list({
          doctor_id: selectedMedico.id,
          active: true,
        });

        console.log(
          "[AgendamentoConsulta] Disponibilidades retornadas da API:",
          {
            count: availabilities?.length || 0,
            data: availabilities,
          }
        );

        if (!availabilities || availabilities.length === 0) {
          console.warn(
            "[AgendamentoConsulta] Nenhuma disponibilidade encontrada para o médico"
          );
          setAvailableDates(new Set());
          return;
        }

        // Mapeia os dias da semana que o médico atende (weekday é sempre número 0-6)
        const availableWeekdays = new Set<number>(
          availabilities.map((avail) => avail.weekday)
        );

        console.log(
          "[AgendamentoConsulta] Dias da semana disponíveis (números):",
          Array.from(availableWeekdays)
        );

        // Calcula todas as datas do mês atual e próximos 2 meses que têm disponibilidade
        const today = startOfDay(new Date());
        const endDate = endOfMonth(addMonths(today, 2));
        const allDates = eachDayOfInterval({ start: today, end: endDate });

        const availableDatesSet = new Set<string>();

        allDates.forEach((date) => {
          const weekday = date.getDay();
          if (availableWeekdays.has(weekday) && !isBefore(date, today)) {
            availableDatesSet.add(format(date, "yyyy-MM-dd"));
          }
        });

        console.log("[AgendamentoConsulta] Resumo do cálculo:", {
          weekdaysDisponiveis: Array.from(availableWeekdays),
          datasCalculadas: availableDatesSet.size,
          primeiras5Datas: Array.from(availableDatesSet).slice(0, 5),
        });

        setAvailableDates(availableDatesSet);
      } catch (error) {
        console.error(
          "[AgendamentoConsulta] Erro ao carregar disponibilidades:",
          error
        );
        setAvailableDates(new Set());
      }
    };

    loadAvailableDates();
  }, [selectedMedico]);

  // Removemos as funções de availability e exceptions antigas
  // A API de slots já considera tudo automaticamente

  const calculateAvailableSlots = useCallback(async () => {
    if (!selectedDate || !selectedMedico) {
      setAvailableSlots([]);
      return;
    }

    try {
      const dateStr = format(selectedDate, "yyyy-MM-dd");

      console.log("[AgendamentoConsulta] Buscando slots disponíveis:", {
        doctor_id: selectedMedico.id,
        doctor_name: selectedMedico.nome,
        date: dateStr,
      });

      // NOTA: Edge Function get-available-slots não está disponível no Supabase
      // Calculando slots localmente

      // Busca a disponibilidade do médico do Supabase
      const { availabilityService } = await import("../services");

      const availabilities = await availabilityService.list({
        doctor_id: selectedMedico.id,
        active: true,
      });

      console.log(
        "[AgendamentoConsulta] Disponibilidades do médico:",
        availabilities
      );

      if (!availabilities || availabilities.length === 0) {
        console.warn(
          "[AgendamentoConsulta] Nenhuma disponibilidade configurada para este médico"
        );
        setAvailableSlots([]);
        return;
      }

      // Pega o dia da semana da data selecionada (0-6)
      const dayOfWeek = selectedDate.getDay() as 0 | 1 | 2 | 3 | 4 | 5 | 6;
      console.log(
        "[AgendamentoConsulta] Dia da semana selecionado:",
        dayOfWeek
      );

      // Filtra disponibilidades para o dia da semana
      const dayAvailability = availabilities.filter(
        (avail) => avail.weekday === dayOfWeek && avail.active
      );

      console.log(
        "[AgendamentoConsulta] Disponibilidades para o dia:",
        dayAvailability
      );

      if (dayAvailability.length === 0) {
        console.warn(
          "[AgendamentoConsulta] Médico não atende neste dia da semana"
        );
        setAvailableSlots([]);
        return;
      }

      // Gera slots para cada disponibilidade
      const allSlots: string[] = [];
      for (const avail of dayAvailability) {
        const startTime = avail.start_time; // "08:00"
        const endTime = avail.end_time; // "18:00"
        const slotMinutes = avail.slot_minutes || 30;

        // Converte para minutos desde meia-noite
        const [startHour, startMin] = startTime.split(":").map(Number);
        const [endHour, endMin] = endTime.split(":").map(Number);

        let currentMinutes = startHour * 60 + startMin;
        const endMinutes = endHour * 60 + endMin;

        while (currentMinutes < endMinutes) {
          const hours = Math.floor(currentMinutes / 60);
          const minutes = currentMinutes % 60;
          const timeStr = `${hours.toString().padStart(2, "0")}:${minutes
            .toString()
            .padStart(2, "0")}`;
          allSlots.push(timeStr);
          currentMinutes += slotMinutes;
        }
      }

      // Busca exceções (bloqueios) para este médico
      const exceptions = await availabilityService.listExceptions({
        doctor_id: selectedMedico.id,
      });

      console.log("[AgendamentoConsulta] Exceções encontradas:", exceptions);

      // Verifica se a data está bloqueada (exceção de bloqueio)
      const dayException = exceptions.find(
        (exc) => exc.date === dateStr && exc.kind === "bloqueio"
      );

      if (dayException) {
        console.log(
          "[AgendamentoConsulta] Data bloqueada por exceção:",
          dayException
        );

        // Se for bloqueio de dia inteiro (start_time e end_time são null), não há horários disponíveis
        if (!dayException.start_time || !dayException.end_time) {
          console.log("[AgendamentoConsulta] Dia completamente bloqueado");
          setAvailableSlots([]);
          return;
        }

        // Se for bloqueio parcial, remove os horários bloqueados
        if (dayException.start_time && dayException.end_time) {
          const [blockStartHour, blockStartMin] = dayException.start_time
            .split(":")
            .map(Number);
          const [blockEndHour, blockEndMin] = dayException.end_time
            .split(":")
            .map(Number);
          const blockStartMinutes = blockStartHour * 60 + blockStartMin;
          const blockEndMinutes = blockEndHour * 60 + blockEndMin;

          // Filtra slots que não estão no período bloqueado
          const slotsAfterBlock = allSlots.filter((slot) => {
            const [slotHour, slotMin] = slot.split(":").map(Number);
            const slotMinutes = slotHour * 60 + slotMin;
            return (
              slotMinutes < blockStartMinutes || slotMinutes >= blockEndMinutes
            );
          });

          console.log(
            "[AgendamentoConsulta] Slots após remover bloqueio parcial:",
            slotsAfterBlock
          );

          // Usa os slots filtrados em vez de todos
          allSlots.length = 0;
          allSlots.push(...slotsAfterBlock);
        }
      }

      // Busca agendamentos existentes para esta data
      const appointments = await appointmentService.list({
        doctor_id: selectedMedico.id,
      });

      console.log(
        "[AgendamentoConsulta] Agendamentos existentes:",
        appointments
      );

      // Filtra agendamentos para a data selecionada
      const bookedSlots = appointments
        .filter((apt) => {
          if (!apt.scheduled_at) return false;
          const aptDate = new Date(apt.scheduled_at);
          return (
            format(aptDate, "yyyy-MM-dd") === dateStr &&
            apt.status !== "cancelled" &&
            apt.status !== "no_show"
          );
        })
        .map((apt) => {
          const aptDate = new Date(apt.scheduled_at);
          return format(aptDate, "HH:mm");
        });

      console.log("[AgendamentoConsulta] Horários já ocupados:", bookedSlots);

      // Remove slots já ocupados
      const availableSlots = allSlots.filter(
        (slot) => !bookedSlots.includes(slot)
      );

      console.log(
        "[AgendamentoConsulta] Slots disponíveis calculados:",
        availableSlots
      );

      setAvailableSlots(availableSlots);
    } catch (error) {
      console.error("[AgendamentoConsulta] Erro ao buscar slots:", error);
      setAvailableSlots([]);
    }
  }, [selectedDate, selectedMedico]);

  useEffect(() => {
    if (selectedDate && selectedMedico) {
      calculateAvailableSlots();
    } else {
      setAvailableSlots([]);
    }
  }, [selectedDate, selectedMedico, appointmentType, calculateAvailableSlots]);

  const generateCalendarDays = () => {
    const start = startOfMonth(currentMonth);
    const end = endOfMonth(currentMonth);
    const days = eachDayOfInterval({ start, end });
    const startDay = start.getDay();
    const prevMonthDays = [];
    for (let i = startDay - 1; i >= 0; i--) {
      const day = new Date(start);
      day.setDate(day.getDate() - (i + 1));
      prevMonthDays.push(day);
    }
    return [...prevMonthDays, ...days];
  };

  const handlePrevMonth = () => setCurrentMonth(subMonths(currentMonth, 1));
  const handleNextMonth = () => setCurrentMonth(addMonths(currentMonth, 1));

  const handleMonthChange = (monthIndex: number) => {
    const newDate = new Date(currentMonth);
    newDate.setMonth(monthIndex);
    setCurrentMonth(newDate);
  };

  const handleYearChange = (year: number) => {
    const newDate = new Date(currentMonth);
    newDate.setFullYear(year);
    setCurrentMonth(newDate);
  };

  // Gera lista de anos (ano atual até +10 anos)
  const availableYears = Array.from(
    { length: 11 },
    (_, i) => new Date().getFullYear() + i
  );

  const handleSelectDoctor = (medico: Medico) => {
    setSelectedMedico(medico);
    setSelectedDate(undefined);
    setSelectedTime("");
    setMotivo("");
    setBookingError("");

    // Scroll suave para a seção de detalhes
    setTimeout(() => {
      detailsRef.current?.scrollIntoView({
        behavior: "smooth",
        block: "start",
      });
    }, 100);
  };
  const handleBookAppointment = () => {
    if (selectedMedico && selectedDate && selectedTime && motivo) {
      setShowConfirmDialog(true);
    }
  };
  const confirmAppointment = async () => {
    if (!selectedMedico || !selectedDate || !selectedTime || !user) return;

    // Valida se o patient_id foi carregado
    if (!patientId) {
      console.error("[AgendamentoConsulta] ❌ Patient ID não encontrado!");
      setResultType("error");
      setBookingError("Erro: Patient ID não encontrado. Por favor, recarregue a página.");
      setShowResultModal(true);
      setShowConfirmDialog(false);
      return;
    }

    try {
      setBookingError("");

      // Formata a data no formato ISO correto
      const scheduledAt =
        format(selectedDate, "yyyy-MM-dd") + "T" + selectedTime + ":00Z";

      // Payload conforme documentação da API Supabase
      // IMPORTANTE: Usando patientId (da tabela patients) ao invés de user.id
      const appointmentData = {
        doctor_id: selectedMedico.id,
        patient_id: patientId,
        scheduled_at: scheduledAt,
        duration_minutes: 30,
        created_by: user.id,
      };

      console.log(
        "[AgendamentoConsulta] Criando agendamento com dados:",
        appointmentData
      );

      // Cria o agendamento usando a API REST
      const appointment = await appointmentService.create(appointmentData);

      console.log(
        "[AgendamentoConsulta] Consulta criada com sucesso:",
        appointment
      );

      // Mostra modal de sucesso
      setResultType("success");
      setShowResultModal(true);
      setShowConfirmDialog(false);
    } catch (error: unknown) {
      console.error("[AgendamentoConsulta] Erro ao agendar:", error);

      const errorMessage =
        error instanceof Error
          ? error.message
          : "Erro ao agendar consulta. Tente novamente.";

      // Mostra modal de erro
      setResultType("error");
      setShowResultModal(true);
      setBookingError(errorMessage);
      setShowConfirmDialog(false);
    }
  };
  const calendarDays = generateCalendarDays();

  return (
    <div className="space-y-4 sm:space-y-6">
      {/* Modal de Resultado (Sucesso ou Erro) com Animação */}
      {showResultModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black bg-opacity-50 animate-fade-in">
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-2xl p-6 sm:p-8 max-w-md w-full animate-scale-in">
            <div className="flex flex-col items-center text-center space-y-4">
              {/* Ícone com Animação Giratória (1 volta) */}
              <div className="relative">
                <div
                  className={`absolute inset-0 rounded-full animate-pulse-ring ${
                    resultType === "success" ? "bg-blue-100" : "bg-red-100"
                  }`}
                ></div>
                <div
                  className={`relative rounded-full p-4 sm:p-5 ${
                    resultType === "success" ? "bg-blue-500" : "bg-red-500"
                  }`}
                >
                  {resultType === "success" ? (
                    <CheckCircle2 className="h-12 w-12 sm:h-16 sm:w-16 text-white animate-spin-once" />
                  ) : (
                    <AlertCircle className="h-12 w-12 sm:h-16 sm:w-16 text-white animate-spin-once" />
                  )}
                </div>
              </div>

              {/* Mensagem */}
              <div className="space-y-2">
                <h3
                  className={`text-xl sm:text-2xl font-bold ${
                    resultType === "success" ? "text-blue-900" : "text-red-900"
                  }`}
                >
                  {resultType === "success"
                    ? "Consulta Agendada!"
                    : "Erro no Agendamento"}
                </h3>
                {resultType === "success" ? (
                  <div className="space-y-2">
                    <p className="text-sm sm:text-base text-gray-600">
                      Sua consulta foi agendada com sucesso. Você receberá uma
                      confirmação por e-mail ou SMS.
                    </p>
                    <button
                      onClick={() => {
                        setShowResultModal(false);
                        setBookingError("");
                        navigate("/acompanhamento", {
                          state: { activeTab: "appointments" },
                        });
                      }}
                      className="text-blue-600 hover:text-blue-800 underline text-sm sm:text-base font-medium"
                    >
                      Ou veja no painel
                    </button>
                  </div>
                ) : (
                  <p className="text-sm sm:text-base text-gray-600">
                    {bookingError ||
                      "Não foi possível agendar a consulta. Tente novamente."}
                  </p>
                )}
              </div>

              {/* Botão OK */}
              <button
                onClick={() => {
                  setShowResultModal(false);
                  setBookingError("");
                  // Limpa o formulário se for sucesso
                  if (resultType === "success") {
                    setSelectedMedico(null);
                    setSelectedDate(undefined);
                    setSelectedTime("");
                    setMotivo("");
                  }
                }}
                className={`w-full font-semibold py-3 px-6 rounded-lg transition-colors ${
                  resultType === "success"
                    ? "bg-blue-500 hover:bg-blue-600 text-white"
                    : "bg-red-500 hover:bg-red-600 text-white"
                }`}
              >
                OK, Entendi!
              </button>
            </div>
          </div>
        </div>
      )}

      <div>
        <h1 className="text-xl sm:text-2xl font-bold">Agendar Consulta</h1>
        <p className="text-sm sm:text-base text-muted-foreground">
          Escolha um médico e horário disponível
        </p>
      </div>
      <div className="bg-white dark:bg-gray-800 rounded-lg sm:rounded-xl border dark:border-gray-700 p-4 sm:p-6 space-y-3 sm:space-y-4">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4">
          <div className="space-y-2">
            <label className="text-xs sm:text-sm font-medium dark:text-gray-200">
              Buscar por nome ou especialidade
            </label>
            <div className="relative">
              <Search className="absolute left-2 sm:left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground flex-shrink-0" />
              <input
                type="text"
                placeholder="Ex: Cardiologia, Dr. Silva..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-9 w-full border border-gray-300 rounded-lg py-2.5 px-3 text-sm sm:text-base focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>
          </div>
          <div className="space-y-2">
            <label className="text-xs sm:text-sm font-medium">
              Especialidade
            </label>
            <select
              value={selectedSpecialty}
              onChange={(e) => setSelectedSpecialty(e.target.value)}
              className="w-full border border-gray-300 dark:border-gray-600 rounded-lg py-2.5 px-3 text-sm sm:text-base focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-gray-700 dark:text-white"
            >
              <option value="all">Todas as especialidades</option>
              {specialties.map((esp) => (
                <option key={esp} value={esp}>
                  {esp}
                </option>
              ))}
            </select>
          </div>
        </div>
      </div>
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {filteredMedicos.map((medico) => (
          <div
            key={medico.id}
            className={`bg-white dark:bg-gray-800 rounded-lg sm:rounded-xl border dark:border-gray-700 p-4 sm:p-6 flex flex-col sm:flex-row gap-3 sm:gap-4 items-start sm:items-center ${
              selectedMedico?.id === medico.id
                ? "border-blue-500 bg-blue-50 dark:bg-blue-900/30"
                : ""
            }`}
          >
            <div className="h-12 w-12 sm:h-16 sm:w-16 rounded-full bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center text-base sm:text-xl font-bold text-white flex-shrink-0">
              {medico.nome
                .split(" ")
                .map((n) => n[0])
                .join("")
                .substring(0, 2)
                .toUpperCase()}
            </div>
            <div className="flex-1 min-w-0 space-y-1.5 sm:space-y-2 w-full">
              <div>
                <h3 className="text-sm sm:text-base font-semibold truncate">
                  {medico.nome}
                </h3>
                <p className="text-xs sm:text-sm text-muted-foreground truncate">
                  {medico.especialidade}
                </p>
              </div>
              <div className="flex flex-wrap items-center gap-2 sm:gap-4 text-xs sm:text-sm text-muted-foreground">
                <span className="truncate">CRM: {medico.crm}</span>
                {medico.valorConsulta ? (
                  <span className="whitespace-nowrap">
                    R$ {medico.valorConsulta.toFixed(2)}
                  </span>
                ) : null}
              </div>
              <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2">
                <span className="text-xs sm:text-sm text-foreground truncate w-full sm:w-auto">
                  {medico.email || "-"}
                </span>
                <div className="flex gap-2 w-full sm:w-auto">
                  <button
                    className="flex-1 sm:flex-none px-3 py-1.5 sm:py-1 rounded-lg border text-xs sm:text-sm hover:bg-blue-50 transition-colors whitespace-nowrap"
                    onClick={() => handleSelectDoctor(medico)}
                  >
                    {selectedMedico?.id === medico.id
                      ? "✓ Selecionado"
                      : "Selecionar"}
                  </button>
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>
      {selectedMedico && (
        <div
          ref={detailsRef}
          className="bg-white dark:bg-gray-800 rounded-lg shadow dark:shadow-gray-900/50 p-4 sm:p-6 space-y-4 sm:space-y-6"
        >
          <div>
            <h2 className="text-lg sm:text-xl font-semibold truncate dark:text-white">
              Detalhes do Agendamento
            </h2>
            <p className="text-sm sm:text-base text-gray-600 dark:text-gray-400 truncate">
              Consulta com {selectedMedico.nome} -{" "}
              {selectedMedico.especialidade}
            </p>
          </div>
          <div className="flex flex-col sm:flex-row gap-2">
            <button
              onClick={() => setAppointmentType("presencial")}
              className={`flex-1 flex items-center justify-center gap-2 py-2.5 sm:py-3 rounded-lg border-2 transition-colors ${
                appointmentType === "presencial"
                  ? "border-blue-500 bg-blue-50 text-blue-600"
                  : "border-gray-300 text-gray-600"
              }`}
            >
              <MapPin className="h-4 w-4 sm:h-5 sm:w-5 flex-shrink-0" />
              <span className="text-sm sm:text-base font-medium">
                Presencial
              </span>
            </button>
            <button
              onClick={() => setAppointmentType("online")}
              className={`flex-1 flex items-center justify-center gap-2 py-2.5 sm:py-3 rounded-lg border-2 transition-colors ${
                appointmentType === "online"
                  ? "border-blue-500 bg-blue-50 text-blue-600"
                  : "border-gray-300 text-gray-600"
              }`}
            >
              <Video className="h-4 w-4 sm:h-5 sm:w-5 flex-shrink-0" />
              <span className="text-sm sm:text-base font-medium">Online</span>
            </button>
          </div>
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <div className="space-y-3 sm:space-y-4">
              <div>
                <label className="text-xs sm:text-sm font-medium">
                  Selecione a Data
                </label>
                <div className="mt-2">
                  <div className="flex items-center justify-between gap-2 mb-3 sm:mb-4">
                    <button
                      onClick={handlePrevMonth}
                      className="p-1.5 sm:p-2 hover:bg-gray-100 rounded-lg flex-shrink-0"
                      aria-label="Mês anterior"
                    >
                      <ChevronLeft className="h-4 w-4 sm:h-5 sm:w-5" />
                    </button>

                    <div className="flex items-center gap-2 flex-1 justify-center">
                      <select
                        value={currentMonth.getMonth()}
                        onChange={(e) =>
                          handleMonthChange(Number(e.target.value))
                        }
                        className="text-xs sm:text-sm font-semibold border border-gray-300 rounded-lg px-2 py-1 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500"
                      >
                        <option value={0}>Janeiro</option>
                        <option value={1}>Fevereiro</option>
                        <option value={2}>Março</option>
                        <option value={3}>Abril</option>
                        <option value={4}>Maio</option>
                        <option value={5}>Junho</option>
                        <option value={6}>Julho</option>
                        <option value={7}>Agosto</option>
                        <option value={8}>Setembro</option>
                        <option value={9}>Outubro</option>
                        <option value={10}>Novembro</option>
                        <option value={11}>Dezembro</option>
                      </select>

                      <select
                        value={currentMonth.getFullYear()}
                        onChange={(e) =>
                          handleYearChange(Number(e.target.value))
                        }
                        className="text-xs sm:text-sm font-semibold border border-gray-300 rounded-lg px-2 py-1 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500"
                      >
                        {availableYears.map((year) => (
                          <option key={year} value={year}>
                            {year}
                          </option>
                        ))}
                      </select>
                    </div>

                    <button
                      onClick={handleNextMonth}
                      className="p-1.5 sm:p-2 hover:bg-gray-100 rounded-lg flex-shrink-0"
                      aria-label="Próximo mês"
                    >
                      <ChevronRight className="h-4 w-4 sm:h-5 sm:w-5" />
                    </button>
                  </div>
                  <div className="border rounded-lg overflow-hidden">
                    <div className="grid grid-cols-7 bg-gray-50">
                      {["D", "S", "T", "Q", "Q", "S", "S"].map((day, idx) => (
                        <div
                          key={idx}
                          className="text-center py-1.5 sm:py-2 text-xs sm:text-sm font-medium text-gray-600"
                        >
                          {day}
                        </div>
                      ))}
                    </div>
                    <div className="grid grid-cols-7">
                      {calendarDays.map((day, index) => {
                        const isCurrentMonth = isSameMonth(day, currentMonth);
                        const isSelected =
                          selectedDate && isSameDay(day, selectedDate);
                        const isPast = isBefore(day, startOfDay(new Date()));

                        // Verifica se a data está no conjunto de datas disponíveis
                        const dateStr = format(day, "yyyy-MM-dd");
                        const isAvailable =
                          isCurrentMonth &&
                          !isPast &&
                          availableDates.has(dateStr);
                        const isUnavailable =
                          isCurrentMonth &&
                          !isPast &&
                          !availableDates.has(dateStr);

                        // Debug apenas para o primeiro dia do mês atual
                        if (index === 0 && isCurrentMonth) {
                          console.log(
                            "[AgendamentoConsulta] Debug calendário:",
                            {
                              totalDatasDisponiveis: availableDates.size,
                              primeiraData: dateStr,
                              diaDaSemana: day.getDay(),
                              isAvailable,
                              isUnavailable,
                              datas5Primeiras: Array.from(availableDates).slice(
                                0,
                                5
                              ),
                            }
                          );
                        }

                        return (
                          <button
                            key={index}
                            onClick={() => isAvailable && setSelectedDate(day)}
                            disabled={!isAvailable}
                            className={`aspect-square p-1 sm:p-2 text-xs sm:text-sm border-r border-b border-gray-200 transition-colors ${
                              !isCurrentMonth ? "text-gray-300 bg-gray-50" : ""
                            } ${
                              isSelected
                                ? "bg-blue-600 text-white font-bold"
                                : ""
                            } ${
                              isAvailable && !isSelected
                                ? "text-blue-600 font-semibold hover:bg-blue-50 cursor-pointer"
                                : ""
                            } ${
                              isUnavailable
                                ? "text-red-600 font-semibold cursor-not-allowed"
                                : ""
                            } ${
                              isPast && isCurrentMonth
                                ? "text-gray-400 cursor-not-allowed"
                                : ""
                            }`}
                          >
                            {format(day, "d")}
                          </button>
                        );
                      })}
                    </div>
                  </div>
                  <div className="mt-2 sm:mt-3 space-y-0.5 sm:space-y-1 text-xs text-gray-600">
                    <p>
                      <span className="text-blue-600 font-semibold">●</span>{" "}
                      Datas disponíveis
                    </p>
                    <p>
                      <span className="text-red-600 font-semibold">●</span>{" "}
                      Datas indisponíveis
                    </p>
                    <p>
                      <span className="text-gray-400">●</span> Datas passadas
                    </p>
                  </div>
                </div>
              </div>
            </div>
            <div className="space-y-3 sm:space-y-4">
              <div>
                <label className="text-xs sm:text-sm font-medium">
                  Horários Disponíveis
                </label>
                {selectedDate ? (
                  <p className="text-xs sm:text-sm text-gray-600 mt-1 break-words">
                    {format(selectedDate, "EEEE, d 'de' MMMM 'de' yyyy", {
                      locale: ptBR,
                    })}
                  </p>
                ) : (
                  <p className="text-xs sm:text-sm text-gray-600 mt-1">
                    Selecione uma data
                  </p>
                )}
              </div>
              {selectedDate && availableSlots.length > 0 ? (
                <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
                  {availableSlots.map((slot) => (
                    <button
                      key={slot}
                      onClick={() => setSelectedTime(slot)}
                      className={`flex items-center justify-center gap-1 py-2 rounded-lg border-2 transition-colors text-xs sm:text-sm ${
                        selectedTime === slot
                          ? "border-blue-500 bg-blue-50 text-blue-600 font-medium"
                          : "border-gray-300 hover:border-blue-300"
                      }`}
                    >
                      <Clock className="h-3 w-3 flex-shrink-0" />
                      {slot}
                    </button>
                  ))}
                </div>
              ) : selectedDate ? (
                <div className="p-3 sm:p-4 rounded-lg border border-gray-300 bg-gray-50 text-center">
                  <p className="text-xs sm:text-sm text-gray-600">
                    Nenhum horário disponível para esta data
                  </p>
                </div>
              ) : (
                <div className="p-3 sm:p-4 rounded-lg border border-gray-300 bg-gray-50 text-center">
                  <p className="text-xs sm:text-sm text-gray-600">
                    Selecione uma data para ver os horários
                  </p>
                </div>
              )}
              <div className="space-y-2">
                <label className="text-xs sm:text-sm font-medium">
                  Motivo da Consulta *
                </label>
                <textarea
                  placeholder="Descreva brevemente o motivo da consulta..."
                  value={motivo}
                  onChange={(e) => setMotivo(e.target.value)}
                  rows={4}
                  className="form-input"
                />
              </div>
              {selectedDate && selectedTime && (
                <div className="p-3 sm:p-4 bg-blue-50 rounded-lg space-y-2">
                  <h4 className="text-sm sm:text-base font-semibold">Resumo</h4>
                  <div className="space-y-1 text-xs sm:text-sm text-gray-600">
                    <p>📅 Data: {format(selectedDate, "dd/MM/yyyy")}</p>
                    <p>⏰ Horário: {selectedTime}</p>
                    <p>
                      📍 Tipo:{" "}
                      {appointmentType === "online" ? "Online" : "Presencial"}
                    </p>
                    {selectedMedico.valorConsulta && (
                      <p>
                        💰 Valor: R$ {selectedMedico.valorConsulta.toFixed(2)}
                      </p>
                    )}
                  </div>
                </div>
              )}
              <button
                onClick={handleBookAppointment}
                disabled={!selectedTime || !motivo.trim()}
                className="w-full py-2.5 sm:py-3 rounded-lg text-sm sm:text-base font-semibold bg-blue-600 text-white hover:bg-blue-700 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors"
              >
                Confirmar Agendamento
              </button>
            </div>
          </div>
        </div>
      )}
      {showConfirmDialog && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-4 sm:p-6 space-y-3 sm:space-y-4 max-h-[90vh] overflow-y-auto">
            <h3 className="text-lg sm:text-xl font-semibold dark:text-white">
              Confirmar Agendamento
            </h3>
            <p className="text-sm sm:text-base text-gray-600 dark:text-gray-400">
              Revise os detalhes da sua consulta antes de confirmar
            </p>
            <div className="space-y-3">
              <div className="flex items-center gap-3">
                <div className="h-10 w-10 sm:h-12 sm:w-12 rounded-full bg-blue-100 flex items-center justify-center text-blue-600 font-bold text-sm sm:text-base flex-shrink-0">
                  {selectedMedico?.nome
                    .split(" ")
                    .map((n) => n[0])
                    .join("")
                    .substring(0, 2)}
                </div>
                <div className="min-w-0 flex-1">
                  <p className="text-sm sm:text-base font-medium text-gray-900 truncate">
                    {selectedMedico?.nome}
                  </p>
                  <p className="text-xs sm:text-sm text-gray-600 truncate">
                    {selectedMedico?.especialidade}
                  </p>
                </div>
              </div>
              <div className="space-y-1.5 sm:space-y-2 text-xs sm:text-sm text-gray-600">
                <p>
                  📅 Data: {selectedDate && format(selectedDate, "dd/MM/yyyy")}
                </p>
                <p>⏰ Horário: {selectedTime}</p>
                <p>
                  📍 Tipo:{" "}
                  {appointmentType === "online"
                    ? "Consulta Online"
                    : "Consulta Presencial"}
                </p>
                {selectedMedico?.valorConsulta && (
                  <p>💰 Valor: R$ {selectedMedico.valorConsulta.toFixed(2)}</p>
                )}
                <div className="mt-2 sm:mt-3 pt-2 sm:pt-3 border-t border-gray-200">
                  <p className="font-medium text-gray-900 mb-1">Motivo:</p>
                  <p className="text-gray-600 break-words">{motivo}</p>
                </div>
              </div>
            </div>
            <div className="flex flex-col sm:flex-row gap-2 sm:gap-3 pt-3 sm:pt-4">
              <button
                onClick={() => setShowConfirmDialog(false)}
                className="flex-1 px-4 py-2 rounded-lg border border-gray-300 text-gray-700 hover:bg-gray-50 transition-colors text-sm sm:text-base order-2 sm:order-1"
              >
                Cancelar
              </button>
              <button
                onClick={confirmAppointment}
                className="flex-1 px-4 py-2 rounded-lg bg-blue-600 text-white hover:bg-blue-700 transition-colors font-medium text-sm sm:text-base order-1 sm:order-2"
              >
                Confirmar
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
