"use client";

import { useEffect } from "react";
import toast from "react-hot-toast";

import { getFcmMessaging } from "@/app/lib/firebase";
import { useLocaleRouter } from "@/app/lib/useLocaleRouter";

/*
* Confirmed real data.type strings (Consultation API Handbook, section
* 06). `data.screen`, if the backend sends one, is the intended
* navigation target directly and wins over this table — this is the
* fallback plus the record of what each type means. consultation_id
* (if present) routes straight to the session; verify the exact field
* name once a real push is captured. CONSULTATION_ENDED must NOT
* trigger a client-side /end call — just tear down.
*/
function resolveNotificationUrl(data: Record<string, any> | undefined): string {
  // The queue pushes send logical screen names ("waiting_queue",
  // "astrologer_profile"), not paths — only a real path can be
  // navigated to directly; names fall through to the type table.
  if (typeof data?.screen === "string" && data.screen.startsWith("/")) return data.screen;

  const type = data?.type || "";
  const cid = data?.consultation_id;

  switch (type) {
    case "CONSULTATION_REQUEST":
      return "/astrologer/requests";
    case "QUEUE_TURN":
      return data?.queue_id ? `/waiting-queue/${data.queue_id}` : "/chat-with-astrologer";
    case "QUEUE_EXPIRED":
      // No slug is available in the payload to reach the astrologer's
      // profile page, so land on the list to try connecting again.
      return "/chat-with-astrologer";
    case "CONSULTATION_ACCEPTED":
    case "CONSULTATION_REJECTED":
    case "CONSULTATION_MISSED":
    case "CONSULTATION_NOT_JOINED":
    case "CONSULTATION_ENDED":
    case "FREE_CHAT_ENDING":
    case "INSUFFICIENT_FUND":
      return cid ? `/consultation/${cid}` : "/chat-with-astrologer";
    case "CONSULTATION_CANCELLED":
      return cid ? `/astrologer/consultation/${cid}` : "/astrologer/requests";
    case "SESSION_ENDING_SOON":
      return cid ? `/astrologer/consultation/${cid}` : "/astrologer/dashboard";
    case "profile_approved":
    case "PROFILE_APPROVED":
      return "/astrologer/dashboard";
    case "profile_rejected":
    case "PROFILE_REJECTED":
      return "/astrologer/profile/review";
    default:
      return data?.account_type === "astrologer"
        ? "/astrologer/dashboard"
        : "/notifications";
  }
}

// Mounted once in app/layout.tsx, renders nothing — same pattern as
// BodyClass.tsx/BootstrapClient.tsx. Only subscribes to foreground FCM
// messages when a session (either account type) actually exists;
// background delivery while the tab is closed/hidden is handled
// separately by public/firebase-messaging-sw.js.
export default function PushNotificationManager() {
  const router = useLocaleRouter();

  useEffect(() => {
    const hasSession =
      !!localStorage.getItem("token") || !!localStorage.getItem("astrologerToken");

    if (!hasSession) return;

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

    getFcmMessaging().then(async (messaging) => {
      if (!messaging) return;

      const { onMessage } = await import("firebase/messaging");

      unsubscribe = onMessage(messaging, (payload) => {
        const title =
          payload.notification?.title ?? payload.data?.title ?? "AstroEye";
        const body = payload.notification?.body ?? payload.data?.body ?? "";
        const url = resolveNotificationUrl(payload.data);

        toast(
          (toastInstance) => (
            <div
              onClick={() => {
                toast.dismiss(toastInstance.id);
                router.push(url);
              }}
              style={{ cursor: "pointer" }}
            >
              <strong>{title}</strong>
              {body && <div>{body}</div>}
            </div>
          ),
          { icon: "🔔", duration: payload.data?.type === "QUEUE_TURN" ? 15000 : undefined }
        );
      });
    });

    return () => unsubscribe?.();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return null;
}
