"use client";

import { useEffect, useRef } from "react";
import { ref, onChildAdded, off, get } from "firebase/database";
import { db } from "@/lib/firebase";
import { useAuth } from "@/hooks/useAuth";
import { useToast } from "@/components/ui/toast";

export function NotificationMonitor() {
  const { user } = useAuth();
  const { toast } = useToast();
  const isInitialLoad = useRef(true);
  const seenReservas = useRef<Set<string>>(new Set());

  useEffect(() => {
    if (!user?.email) return;

    const reservasRef = ref(db, "reservas");

    // Primeiro, marcamos todas as reservas existentes como "vistas"
    // para não disparar notificações para o passado
    const loadExisting = async () => {
      const snapshot = await get(reservasRef);
      if (snapshot.exists()) {
        const data = snapshot.val();
        Object.keys(data).forEach(id => seenReservas.current.add(id));
      }
      isInitialLoad.current = false;
    };

    loadExisting();

    const unsubscribe = onChildAdded(reservasRef, (snapshot) => {
      const id = snapshot.key;
      if (!id || seenReservas.current.has(id)) return;
      
      // Adiciona ao set para não repetir se o listener reiniciar
      seenReservas.current.add(id);

      // Se ainda estivermos no load inicial (do get), ignoramos o toast
      if (isInitialLoad.current) return;

      const data = snapshot.val();
      if (data.restauranteEmail === user.email && data.estado === "Pendente") {
        toast(`Nova reserva recebida de ${data.clienteEmail}!`, "info");
      }
    });

    return () => {
      off(reservasRef, "child_added", unsubscribe);
    };
  }, [user?.email, toast]);

  return null; // Componente apenas lógico
}
