import { useQuery } from "@tanstack/react-query";
import { appointmentService } from "../services";
import { patientService } from "../services";
import { format, startOfMonth, startOfDay, endOfDay } from "date-fns";

interface MetricsData {
  totalAppointments: number;
  appointmentsToday: number;
  completedAppointments: number;
  activePatients: number;
  occupancyRate: number;
  cancelledRate: number;
}

const metricsKeys = {
  all: ["metrics"] as const,
  summary: (doctorId?: string) =>
    [...metricsKeys.all, "summary", doctorId] as const,
};

/**
 * Hook para buscar métricas gerais do dashboard
 * Auto-refresh a cada 5 minutos
 */
export function useMetrics(doctorId?: string) {
  return useQuery({
    queryKey: metricsKeys.summary(doctorId),
    queryFn: async (): Promise<MetricsData> => {
      const today = new Date();
      const startOfToday = format(startOfDay(today), "yyyy-MM-dd'T'HH:mm:ss");
      const endOfToday = format(endOfDay(today), "yyyy-MM-dd'T'HH:mm:ss");
      const startOfThisMonth = format(
        startOfMonth(today),
        "yyyy-MM-dd'T'HH:mm:ss"
      );

      // Buscar todas as consultas (ou filtradas por médico)
      const allAppointments = await appointmentService.list(
        doctorId ? { doctor_id: doctorId } : {}
      );

      // Buscar consultas de hoje
      const todayAppointments = allAppointments.filter((apt) => {
        if (!apt.scheduled_at) return false;
        const aptDate = new Date(apt.scheduled_at);
        return (
          aptDate >= new Date(startOfToday) && aptDate <= new Date(endOfToday)
        );
      });

      // Consultas concluídas (total)
      const completedAppointments = allAppointments.filter(
        (apt) => apt.status === "completed"
      );

      // Consultas canceladas
      const cancelledAppointments = allAppointments.filter(
        (apt) => apt.status === "cancelled" || apt.status === "no_show"
      );

      // Buscar pacientes ativos (pode ajustar a lógica)
      const allPatients = await patientService.list();
      const activePatients = allPatients.filter((patient) => {
        // Considera ativo se tem consulta nos últimos 3 meses
        const hasRecentAppointment = allAppointments.some(
          (apt) =>
            apt.patient_id === patient.id &&
            apt.scheduled_at &&
            new Date(apt.scheduled_at) >= new Date(startOfThisMonth)
        );
        return hasRecentAppointment;
      });

      // Taxa de ocupação (consultas confirmadas + em andamento vs total de slots disponíveis)
      // Simplificado: confirmadas + in_progress / total agendado
      const scheduledAppointments = todayAppointments.filter(
        (apt) =>
          apt.status === "confirmed" ||
          apt.status === "in_progress" ||
          apt.status === "completed" ||
          apt.status === "checked_in"
      );
      const occupancyRate =
        todayAppointments.length > 0
          ? Math.round(
              (scheduledAppointments.length / todayAppointments.length) * 100
            )
          : 0;

      // Taxa de cancelamento
      const cancelledRate =
        allAppointments.length > 0
          ? Math.round(
              (cancelledAppointments.length / allAppointments.length) * 100
            )
          : 0;

      return {
        totalAppointments: allAppointments.length,
        appointmentsToday: todayAppointments.length,
        completedAppointments: completedAppointments.length,
        activePatients: activePatients.length,
        occupancyRate,
        cancelledRate,
      };
    },
    staleTime: 5 * 60 * 1000, // 5 minutos
    refetchInterval: 5 * 60 * 1000, // Auto-refresh a cada 5 minutos
    refetchOnWindowFocus: true,
  });
}

/**
 * Hook para buscar dados de ocupação dos últimos 7 dias
 * Para uso em gráficos
 */
export function useOccupancyData(doctorId?: string) {
  return useQuery({
    queryKey: [...metricsKeys.all, "occupancy", doctorId],
    queryFn: async () => {
      const today = new Date();
      const last7Days = Array.from({ length: 7 }, (_, i) => {
        const date = new Date(today);
        date.setDate(date.getDate() - (6 - i));
        return date;
      });

      const appointments = await appointmentService.list(
        doctorId ? { doctor_id: doctorId } : {}
      );

      const occupancyByDay = last7Days.map((date) => {
        const dayStart = startOfDay(date);
        const dayEnd = endOfDay(date);

        const dayAppointments = appointments.filter((apt) => {
          if (!apt.scheduled_at) return false;
          const aptDate = new Date(apt.scheduled_at);
          return aptDate >= dayStart && aptDate <= dayEnd;
        });

        const completedOrInProgress = dayAppointments.filter(
          (apt) =>
            apt.status === "completed" ||
            apt.status === "in_progress" ||
            apt.status === "confirmed" ||
            apt.status === "checked_in"
        );

        const rate =
          dayAppointments.length > 0
            ? Math.round(
                (completedOrInProgress.length / dayAppointments.length) * 100
              )
            : 0;

        return {
          date: format(date, "yyyy-MM-dd"), // ISO format para compatibilidade
          dayName: format(date, "EEE"),
          total: dayAppointments.length,
          completed: completedOrInProgress.length,
          rate,
          // Formato compatível com OccupancyHeatmap
          total_slots: dayAppointments.length,
          occupied_slots: completedOrInProgress.length,
          available_slots:
            dayAppointments.length - completedOrInProgress.length,
          occupancy_rate: rate,
        };
      });

      return occupancyByDay;
    },
    staleTime: 10 * 60 * 1000, // 10 minutos (muda menos frequentemente)
    refetchInterval: 10 * 60 * 1000,
  });
}

// Exemplo de uso:
// import { useMetrics } from '@/hooks/useMetrics';
//
// function Dashboard() {
//   const { data: metrics, isLoading } = useMetrics(doctorId);
//
//   if (isLoading) return <Skeleton />;
//
//   return (
//     <div>
//       <MetricCard
//         title="Total de Consultas"
//         value={metrics.totalAppointments}
//         icon={Calendar}
//       />
//     </div>
//   );
// }
