/**
 * RescheduleModal Component
 * Modal para reagendamento inteligente de consultas
 * @version 1.0
 */

import { useState, useMemo } from "react";
import { X, Calendar, Clock, AlertCircle, CheckCircle } from "lucide-react";
import { format, addDays, isBefore, startOfDay } from "date-fns";
import { ptBR } from "date-fns/locale";
import { useAvailability } from "../../hooks/useAvailability";
import { useUpdateAppointment } from "../../hooks/useAppointments";

interface RescheduleModalProps {
  appointmentId: string;
  appointmentDate: string;
  doctorId: string;
  doctorName: string;
  patientName: string;
  onClose: () => void;
}

interface SuggestedSlot {
  date: string;
  time: string;
  datetime: string;
  distance: number; // dias de distância da data original
}

export function RescheduleModal({
  appointmentId,
  appointmentDate,
  doctorId,
  doctorName,
  patientName,
  onClose,
}: RescheduleModalProps) {
  const [selectedSlot, setSelectedSlot] = useState<SuggestedSlot | null>(null);
  const { data: availabilities = [], isLoading: loadingAvailabilities } =
    useAvailability(doctorId);
  const updateMutation = useUpdateAppointment();

  // Gerar sugestões inteligentes de horários
  const suggestedSlots = useMemo(() => {
    const originalDate = new Date(appointmentDate);
    const today = startOfDay(new Date());
    const slots: SuggestedSlot[] = [];

    // Buscar próximos 30 dias
    for (let i = 0; i < 30; i++) {
      const checkDate = addDays(today, i);

      // Pular datas passadas
      if (isBefore(checkDate, today)) continue;

      const dayOfWeek = checkDate.getDay();
      const dayAvailabilities = availabilities.filter((avail) => {
        if (typeof avail.weekday === "undefined") return false;
        // Mapear weekday de 0-6 (domingo-sábado)
        return avail.weekday === dayOfWeek && avail.active !== false;
      });

      dayAvailabilities.forEach((avail) => {
        if (avail.start_time && avail.end_time) {
          // Gerar slots de 30 em 30 minutos
          const startHour = parseInt(avail.start_time.split(":")[0]);
          const startMin = parseInt(avail.start_time.split(":")[1]);
          const endHour = parseInt(avail.end_time.split(":")[0]);
          const endMin = parseInt(avail.end_time.split(":")[1]);

          const startMinutes = startHour * 60 + startMin;
          const endMinutes = endHour * 60 + endMin;

          for (
            let minutes = startMinutes;
            minutes < endMinutes;
            minutes += 30
          ) {
            const slotHour = Math.floor(minutes / 60);
            const slotMin = minutes % 60;
            const timeStr = `${String(slotHour).padStart(2, "0")}:${String(
              slotMin
            ).padStart(2, "0")}`;

            const datetime = new Date(checkDate);
            datetime.setHours(slotHour, slotMin, 0, 0);

            // Calcular distância em dias da data original
            const distance = Math.abs(
              Math.floor(
                (datetime.getTime() - originalDate.getTime()) /
                  (1000 * 60 * 60 * 24)
              )
            );

            slots.push({
              date: format(checkDate, "EEEE, dd 'de' MMMM", { locale: ptBR }),
              time: timeStr,
              datetime: datetime.toISOString(),
              distance,
            });
          }
        }
      });
    }

    // Ordenar por distância (mais próximo da data original)
    return slots.sort((a, b) => a.distance - b.distance).slice(0, 10); // Top 10 sugestões
  }, [availabilities, appointmentDate]);

  const handleReschedule = async () => {
    if (!selectedSlot) return;

    try {
      await updateMutation.mutateAsync({
        id: appointmentId,
        scheduled_at: selectedSlot.datetime,
      });
      onClose();
    } catch (error) {
      console.error("Erro ao reagendar:", error);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
      <div
        className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl max-w-2xl w-full max-h-[90vh] overflow-hidden flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
          <div>
            <h2 className="text-2xl font-bold text-gray-900 dark:text-white">
              Reagendar Consulta
            </h2>
            <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
              {patientName} · Dr(a). {doctorName}
            </p>
          </div>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
          >
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>

        {/* Info da consulta atual */}
        <div className="px-6 py-4 bg-amber-50 dark:bg-amber-900/20 border-b border-amber-100 dark:border-amber-800">
          <div className="flex items-center gap-2 text-amber-800 dark:text-amber-300">
            <AlertCircle className="w-5 h-5" />
            <div>
              <p className="font-medium">Data atual da consulta</p>
              <p className="text-sm">
                {format(
                  new Date(appointmentDate),
                  "EEEE, dd 'de' MMMM 'às' HH:mm",
                  {
                    locale: ptBR,
                  }
                )}
              </p>
            </div>
          </div>
        </div>

        {/* Lista de sugestões */}
        <div className="flex-1 overflow-y-auto p-6">
          <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-4 uppercase tracking-wide">
            Horários Sugeridos (mais próximos)
          </h3>

          {loadingAvailabilities ? (
            <div className="space-y-3">
              {[...Array(5)].map((_, i) => (
                <div
                  key={i}
                  className="p-4 bg-gray-100 dark:bg-gray-700 rounded-lg animate-pulse h-20"
                />
              ))}
            </div>
          ) : suggestedSlots.length === 0 ? (
            <div className="text-center py-12 text-gray-500 dark:text-gray-400">
              <Calendar className="w-12 h-12 mx-auto mb-3 opacity-50" />
              <p>Nenhum horário disponível encontrado</p>
              <p className="text-sm mt-1">
                Configure a disponibilidade do médico ou tente outro período
              </p>
            </div>
          ) : (
            <div className="space-y-2">
              {suggestedSlots.map((slot, index) => (
                <button
                  key={index}
                  onClick={() => setSelectedSlot(slot)}
                  className={`
                    w-full flex items-center justify-between p-4 rounded-lg border-2 transition-all
                    ${
                      selectedSlot?.datetime === slot.datetime
                        ? "border-green-500 bg-green-50 dark:bg-green-900/20"
                        : "border-gray-200 dark:border-gray-700 hover:border-green-300 dark:hover:border-green-700"
                    }
                  `}
                >
                  <div className="flex items-center gap-4">
                    <div
                      className={`
                      p-3 rounded-lg
                      ${
                        selectedSlot?.datetime === slot.datetime
                          ? "bg-green-500 text-white"
                          : "bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400"
                      }
                    `}
                    >
                      <Calendar className="w-5 h-5" />
                    </div>
                    <div className="text-left">
                      <p
                        className={`font-medium ${
                          selectedSlot?.datetime === slot.datetime
                            ? "text-green-900 dark:text-green-100"
                            : "text-gray-900 dark:text-gray-100"
                        }`}
                      >
                        {slot.date}
                      </p>
                      <div className="flex items-center gap-2 mt-1">
                        <Clock className="w-4 h-4 text-gray-400" />
                        <p className="text-sm text-gray-600 dark:text-gray-400">
                          {slot.time}
                        </p>
                      </div>
                    </div>
                  </div>

                  <div className="text-right">
                    <span
                      className={`
                      text-xs px-2 py-1 rounded-full
                      ${
                        slot.distance === 0
                          ? "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300"
                          : slot.distance <= 3
                          ? "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300"
                          : "bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300"
                      }
                    `}
                    >
                      {slot.distance === 0
                        ? "Mesmo dia"
                        : `${slot.distance} dias`}
                    </span>
                  </div>
                </button>
              ))}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between p-6 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900">
          <button
            onClick={onClose}
            className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors"
          >
            Cancelar
          </button>
          <button
            onClick={handleReschedule}
            disabled={!selectedSlot || updateMutation.isPending}
            className="
              px-6 py-2 bg-green-600 text-white rounded-lg font-medium
              hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed
              transition-colors flex items-center gap-2
            "
          >
            {updateMutation.isPending ? (
              <>
                <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                Reagendando...
              </>
            ) : (
              <>
                <CheckCircle className="w-4 h-4" />
                Confirmar Novo Horário
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
}
