/**
 * Exemplo de componente usando os novos serviços de Backend
 */

import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  analyticsService,
  waitlistService,
  notificationService,
  appointmentService,
  type WaitlistEntry,
  type KPISummary,
} from "@/services";

export function ExemploBackendServices() {
  const queryClient = useQueryClient();

  // ===== ANALYTICS / KPIs =====
  const { data: kpis, isLoading: loadingKpis } = useQuery<KPISummary>({
    queryKey: ["analytics", "summary"],
    queryFn: () => analyticsService.getSummary(),
    refetchInterval: 60_000, // Auto-refresh a cada 1 minuto
  });

  // ===== WAITLIST (Lista de Espera) =====
  const { data: waitlist } = useQuery<WaitlistEntry[]>({
    queryKey: ["waitlist"],
    queryFn: () => waitlistService.list(),
  });

  const addToWaitlist = useMutation({
    mutationFn: waitlistService.create,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["waitlist"] });
      alert("Adicionado à lista de espera!");
    },
  });

  // ===== NOTIFICATIONS =====
  const { data: pendingNotifications } = useQuery({
    queryKey: ["notifications", "pending"],
    queryFn: () => notificationService.list({ status: "pending" }),
  });

  const sendNotification = useMutation({
    mutationFn: notificationService.create,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["notifications"] });
      alert("Notificação enviada!");
    },
  });

  // ===== APPOINTMENTS ENHANCED =====
  const { data: appointments } = useQuery({
    queryKey: ["appointments", "enhanced"],
    queryFn: () => appointmentService.listEnhanced(),
  });

  // ===== HANDLERS =====
  const handleAddToWaitlist = () => {
    addToWaitlist.mutate({
      patient_id: "example-patient-uuid",
      doctor_id: "example-doctor-uuid",
      desired_date: "2025-12-15",
    });
  };

  const handleSendReminder = () => {
    sendNotification.mutate({
      type: "sms",
      payload: {
        to: "+5511999999999",
        message: "Lembrete: Você tem uma consulta amanhã às 14h!",
      },
    });
  };

  return (
    <div className="p-6 space-y-6">
      <h1 className="text-2xl font-bold">Backend Services - Exemplos</h1>

      {/* KPIs / Analytics */}
      <section className="bg-white p-4 rounded-lg shadow">
        <h2 className="text-xl font-semibold mb-3">📊 KPIs (Analytics)</h2>
        {loadingKpis ? (
          <p>Carregando...</p>
        ) : kpis ? (
          <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
            <div className="text-center">
              <p className="text-3xl font-bold text-blue-600">
                {kpis.total_appointments}
              </p>
              <p className="text-sm text-gray-600">Total</p>
            </div>
            <div className="text-center">
              <p className="text-3xl font-bold text-green-600">{kpis.today}</p>
              <p className="text-sm text-gray-600">Hoje</p>
            </div>
            <div className="text-center">
              <p className="text-3xl font-bold text-yellow-600">
                {kpis.pending}
              </p>
              <p className="text-sm text-gray-600">Pendentes</p>
            </div>
            <div className="text-center">
              <p className="text-3xl font-bold text-purple-600">
                {kpis.completed}
              </p>
              <p className="text-sm text-gray-600">Concluídas</p>
            </div>
            <div className="text-center">
              <p className="text-3xl font-bold text-red-600">{kpis.canceled}</p>
              <p className="text-sm text-gray-600">Canceladas</p>
            </div>
          </div>
        ) : null}
      </section>

      {/* Waitlist */}
      <section className="bg-white p-4 rounded-lg shadow">
        <h2 className="text-xl font-semibold mb-3">⏳ Lista de Espera</h2>
        <button
          onClick={handleAddToWaitlist}
          className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 mb-3"
        >
          Adicionar à Lista de Espera
        </button>
        <div className="space-y-2">
          {waitlist?.map((entry) => (
            <div key={entry.id} className="border p-2 rounded">
              <p>
                <strong>Paciente:</strong> {entry.patient_id}
              </p>
              <p>
                <strong>Médico:</strong> {entry.doctor_id}
              </p>
              <p>
                <strong>Data desejada:</strong> {entry.desired_date}
              </p>
              <p>
                <strong>Status:</strong> {entry.status}
              </p>
            </div>
          ))}
        </div>
      </section>

      {/* Notifications */}
      <section className="bg-white p-4 rounded-lg shadow">
        <h2 className="text-xl font-semibold mb-3">
          🔔 Notificações Pendentes
        </h2>
        <button
          onClick={handleSendReminder}
          className="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600 mb-3"
        >
          Enviar Lembrete de Consulta
        </button>
        <p className="text-sm text-gray-600">
          {pendingNotifications?.length || 0} notificações na fila
        </p>
      </section>

      {/* Appointments Enhanced */}
      <section className="bg-white p-4 rounded-lg shadow">
        <h2 className="text-xl font-semibold mb-3">
          📅 Agendamentos (com metadados)
        </h2>
        <p className="text-sm text-gray-600 mb-2">
          Agendamentos mesclados com notificações pendentes do backend próprio
        </p>
        <div className="space-y-2">
          {appointments?.slice(0, 5).map((appt: any) => (
            <div key={appt.id} className="border p-2 rounded">
              <p>
                <strong>ID:</strong> {appt.id}
              </p>
              <p>
                <strong>Data:</strong> {appt.scheduled_at}
              </p>
              {appt.meta && (
                <p className="text-orange-600">⚠️ Tem notificação pendente</p>
              )}
            </div>
          ))}
        </div>
      </section>
    </div>
  );
}
