"use client";

import { useEffect, useRef, useState, useCallback } from "react";
import { useSession } from "next-auth/react";
import { notificationService } from "@/services/notification.service";

interface ToastNotification {
  id: number;
  title: string;
  body: string;
}

let toastId = 0;

export function NotificationProvider() {
  const { status } = useSession();
  const initialized = useRef(false);
  const [toasts, setToasts] = useState<ToastNotification[]>([]);

  const addToast = useCallback(
    (payload: { title: string; body: string }) => {
      const id = ++toastId;
      setToasts((prev) => [...prev, { id, title: payload.title, body: payload.body }]);
      setTimeout(() => {
        setToasts((prev) => prev.filter((t) => t.id !== id));
      }, 5000);
    },
    []
  );

  const removeToast = useCallback((id: number) => {
    setToasts((prev) => prev.filter((t) => t.id !== id));
  }, []);

  useEffect(() => {
    if (status !== "authenticated" || initialized.current) return;
    initialized.current = true;

    let unsubscribe: (() => void) | null = null;

    const init = async () => {
      const registered = await notificationService.requestPermissionAndRegister();
      if (registered) {
        unsubscribe = notificationService.setupForegroundHandler(addToast);
      }
    };

    init();

    return () => {
      if (unsubscribe) unsubscribe();
    };
  }, [status, addToast]);

  // Reset on logout
  useEffect(() => {
    if (status === "unauthenticated") {
      initialized.current = false;
    }
  }, [status]);

  if (toasts.length === 0) return null;

  return (
    <div
      style={{
        position: "fixed",
        top: 16,
        right: 16,
        zIndex: 9999,
        display: "flex",
        flexDirection: "column",
        gap: 8,
        maxWidth: 360,
      }}
    >
      {toasts.map((toast) => (
        <div
          key={toast.id}
          onClick={() => removeToast(toast.id)}
          style={{
            background: "#fff",
            borderRadius: 10,
            padding: "12px 16px",
            boxShadow: "0 4px 12px rgba(0,0,0,0.15)",
            borderLeft: "4px solid #e58625",
            cursor: "pointer",
            animation: "slideIn 0.3s ease-out",
          }}
        >
          <div style={{ fontWeight: 600, fontSize: 14, color: "#00293d", marginBottom: 4 }}>
            {toast.title}
          </div>
          <div style={{ fontSize: 13, color: "#666" }}>{toast.body}</div>
        </div>
      ))}
    </div>
  );
}
