// src/firebase/notification.js
import { getToken, onMessage } from 'firebase/messaging';
import { messaging } from './firebase';
import { dispatch } from 'store';
import { setFcmToken, setFcmPermission } from 'store/reducers/fcmSlice';
import { enqueueSnackbar, closeSnackbar } from 'notistack';
import CloseIcon from '@mui/icons-material/Close';
import IconButton from '@mui/material/IconButton';
import { GlobalToast } from 'components/nearle_components/GlobalToast';

// ===================== Toast Helper =====================
const opentoast = (message, color, vertical = 'bottom') => {
  enqueueSnackbar(message, {
    variant: color,
    anchorOrigin: { vertical, horizontal: 'right' },
    autoHideDuration: null,
    action: (snackbarId) => (
      <IconButton size="small" color="inherit" onClick={() => closeSnackbar(snackbarId)}>
        <CloseIcon fontSize="small" />
      </IconButton>
    )
  });
};

// ===================== Generate FCM Token =====================
export const generateToken = async () => {
  try {
    const permission = await Notification.requestPermission();
    dispatch(setFcmPermission(permission));

    if (permission !== 'granted') {
      opentoast('Enable notifications to receive OTP, alerts, and updates', 'error');
      return;
    }

    // ✅ Register & reuse the SAME Service Worker
    const registration = await navigator.serviceWorker.register('/firebase-messaging-sw.js', { scope: '/' });

    await navigator.serviceWorker.ready;

    const token = await getToken(messaging, {
      vapidKey: 'BBfin2w2LLwc51gmgIUzSi9F6C6TchC99xwIWVpodbZJckqhyuN_2BKmIaA7cwF2JiqhzYJ0Rqszjh1-pDgYMWw',
      serviceWorkerRegistration: registration
    });

    if (token) {
      console.log('📌 FCM Token:', token);
      dispatch(setFcmToken(token));
    } else {
      console.warn('⚠️ No FCM token generated');
    }
  } catch (err) {
    console.error('❌ FCM token error:', err);
  }
};

// ===================== Foreground Notifications =====================
export const initFirebaseNotificationListener = () => {
  console.log('🔥 Firebase foreground listener initialized');

  onMessage(messaging, async (payload) => {
    console.log('📥 Foreground message:', payload);

    const { notification = {}, data = {} } = payload;

    // ✅ UI Toast (your custom toast)
    if (notification?.body) {
      GlobalToast(notification.body, 'primary', 'top');
    }

    // ✅ System notification ONLY ONCE
    if (Notification.permission === 'granted') {
      const registration = await navigator.serviceWorker.getRegistration();

      if (registration) {
        registration.showNotification(notification.title || 'Nearle', {
          body: notification.body,
          icon: notification.image || '/favicon.ico',
          data,
          tag: 'nearle-foreground',
          renotify: true,
          badge: '/badge.png',
          vibrate: [100, 50, 100]
        });
      }
    }
  });
};
