'use client';
import { useEffect, useState } from 'react';
import { io, Socket } from 'socket.io-client';
import { useAuthStore } from '@/store/auth.store';
import { useQueryClient } from '@tanstack/react-query';

export function useRealtimeNotifications() {
  const tenant = useAuthStore((s) => s.tenant);
  const queryClient = useQueryClient();
  const [socket, setSocket] = useState<Socket | null>(null);
  const [unreadCount, setUnreadCount] = useState(0);

  useEffect(() => {
    if (!tenant?.id) return;
    const s = io(`${process.env.NEXT_PUBLIC_API_URL?.replace('/api/v1', '')}/notifications`, {
      query: { tenantId: tenant.id },
    });

    s.on('notification', () => {
      queryClient.invalidateQueries({ queryKey: ['notifications'] });
      setUnreadCount((c) => c + 1);
      if ('Notification' in window && Notification.permission === 'granted') {
        new Notification('Manutix', { body: 'Você tem novas notificações', icon: '/icons/icon-192x192.png' });
      }
    });

    s.on('order:completed', () => {
      queryClient.invalidateQueries({ queryKey: ['orders'] });
      queryClient.invalidateQueries({ queryKey: ['dashboard'] });
    });

    setSocket(s);
    return () => { s.disconnect(); };
  }, [tenant?.id]);

  return { socket, unreadCount, resetCount: () => setUnreadCount(0) };
}

export function requestPushPermission() {
  if ('Notification' in window && Notification.permission === 'default') {
    Notification.requestPermission();
  }
}
