"use client";

import React, { createContext, useContext, useEffect, useState } from "react";
import { requestForToken, onMessageListener } from "@/lib/firebase";
import toast from "react-hot-toast";

interface NotificationContextProps {
    token: string | null;
}

const NotificationContext = createContext<NotificationContextProps | undefined>(undefined);

export function NotificationProvider({ children }: { children: React.ReactNode }) {
    const [token, setToken] = useState<string | null>(null);

    useEffect(() => {
        const setupNotifications = async () => {
            // Request permission and get token
            const currentToken = await requestForToken();
            if (currentToken) {
                console.log("FCM Token:", currentToken);
                setToken(currentToken);
                // You might want to send this token to your backend here
            }
        };

        if (typeof window !== "undefined" && "serviceWorker" in navigator) {
            setupNotifications();

            // Listen for messages in the foreground
            const unsubscribe = onMessageListener((payload: any) => {
                console.log("Foreground Message received:", payload);
                const { notification, data } = payload;
                const appointmentId = data?.appointmentId;

                toast(
                    (t) => (
                        <div
                            className="flex items-center gap-3 cursor-pointer group px-1"
                            onClick={() => {
                                if (appointmentId) {
                                    // router.push(`/${locale}/dashboard/calendar?id=${appointmentId}`)
                                }
                                toast.dismiss(t.id);
                            }}
                        >
                            <div className="flex-shrink-0 flex items-center justify-center w-10 h-10 bg-primary-gradient rounded-xl shadow-lg ring-1 ring-white/20">
                                <span className="text-lg">🔔</span>
                            </div>
                            <div className="flex flex-col min-w-0">
                                <h4 className="font-bold text-[14px] text-white leading-tight truncate">
                                    {notification?.title || "New Message"}
                                </h4>
                                <p className="text-[13px] text-gray-300 leading-snug line-clamp-2 mt-0.5">
                                    {notification?.body || "You have a new update."}
                                </p>
                            </div>
                        </div>
                    ),
                    {
                        duration: 5000,
                        style: {
                            borderRadius: '14px',
                            background: 'rgba(15, 23, 42, 0.85)',
                            backdropFilter: 'blur(12px)',
                            WebkitBackdropFilter: 'blur(12px)',
                            color: '#fff',
                            border: '1px solid rgba(255, 255, 255, 0.1)',
                            padding: '12px 14px',
                            boxShadow: '0 8px 32px 0 rgba(0, 0, 0, 0.37)',
                            width: '320px',
                            maxWidth: '90vw',
                        },
                    }
                );
            });

            return () => {
                if (typeof unsubscribe === 'function') unsubscribe();
            };
        }
    }, []);

    return (
        <NotificationContext.Provider value={{ token }}>
            {children}
        </NotificationContext.Provider>
    );
}

export function useNotification() {
    const context = useContext(NotificationContext);
    if (context === undefined) {
        throw new Error("useNotification must be used within a NotificationProvider");
    }
    return context;
}
