"use client";

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

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);

      // Dispatch event so the header can refresh unread count
      window.dispatchEvent(new Event("notification-received"));
    },
    []
  );

  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 () => {
      console.log('[NotificationProvider] Initializing push notifications...');
      const registered = await notificationService.requestPermissionAndRegister();
      console.log('[NotificationProvider] Registration result:', registered);
      if (registered) {
        unsubscribe = await notificationService.setupForegroundHandler((payload) => {
          console.log('[NotificationProvider] Foreground message received:', payload);
          addToast(payload);
        });
        console.log('[NotificationProvider] Foreground handler set up');
      }
    };

    init();

    // Listen to socket events for real-time toast notifications
    const unsubConnectionReq = socketService.onConnectionRequest((data) => {
      const senderName = (data.senderName as string) || "Someone";
      addToast({ title: "New Connection Request", body: `${senderName} wants to connect with you` });
    });

    const unsubConnectionRes = socketService.onConnectionResponse((data) => {
      const agentName = (data.agentName as string) || "An agent";
      const status = data.status as string;
      if (status === "ACCEPTED") {
        addToast({ title: "Connection Accepted", body: `${agentName} accepted your connection request` });
      } else {
        addToast({ title: "Connection Declined", body: `${agentName} declined your connection request` });
      }
    });

    return () => {
      if (unsubscribe) unsubscribe();
      unsubConnectionReq();
      unsubConnectionRes();
    };
  }, [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>
  );
}
