'use client';

import { useEffect, useState } from 'react';
import { getToken, onMessage } from 'firebase/messaging'; // onMessage for foreground
import { messagingPromise } from '@/lib/firebase-client';
import { fcmApi } from '@/lib/api';
import { toast } from 'sonner';

export const useFcmToken = () => {
    const [token, setToken] = useState<string | null>(null);
    const [notificationPermissionStatus, setNotificationPermissionStatus] = useState<NotificationPermission>('default');

    useEffect(() => {
        const retrieveToken = async () => {
            try {
                if (typeof window !== 'undefined' && 'serviceWorker' in navigator) {
                    const messaging = await messagingPromise;
                    if (!messaging) {
                        console.log("Firebase Messaging not supported/initialized");
                        return;
                    }

                    const permission = await Notification.requestPermission();
                    setNotificationPermissionStatus(permission);

                    if (permission === 'granted') {
                        const currentToken = await getToken(messaging, {
                            vapidKey: process.env.NEXT_PUBLIC_FIREBASE_VAPID_KEY,
                        });

                        if (currentToken) {
                            setToken(currentToken);
                            // Send token to backend
                            // We should probably check if it changed or just send it?
                            // The backend handles UPSERT, so sending every time (on mount) is "okay" but maybe spammy.
                            // Ideally store in localStorage and compare.

                            const storedToken = localStorage.getItem('fcm_token');
                            if (currentToken !== storedToken) {
                                await fcmApi.saveToken(currentToken, 'web');
                                localStorage.setItem('fcm_token', currentToken);
                                console.log("FCM Token synced with backend");
                            }
                        } else {
                            console.log('No registration token available. Request permission to generate one.');
                        }

                        // Listen for foreground messages
                        onMessage(messaging, (payload) => {
                            console.log('Message received. ', payload);
                            toast.info(payload.notification?.title || "New Notification", {
                                description: payload.notification?.body,
                            });
                        });

                    }
                }
            } catch (error) {
                console.error('An error occurred while retrieving token:', error);
            }
        };

        retrieveToken();
    }, []);

    return { token, notificationPermissionStatus };
};
