"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import type { ReactNode } from "react";
import { useRouter } from "next/navigation";

/*
|--------------------------------------------------------------------------
| Leave-confirmation for an ongoing call / chat
|--------------------------------------------------------------------------
| While `active` (the consultation is ONGOING) any attempt to leave the screen
| is held back behind a popup:
|   "Your consultation is currently ongoing. Do you want to end the call/chat
|    and leave this screen?"  →  [End & Leave]  [Continue Consultation]
|
| Covered: clicks on any in-app link (header / sidebar / bell menus — anything
| that renders an <a>), the browser Back button, and closing / reloading the tab
| (the browser's own native prompt — a page cannot show a custom popup there).
| Programmatic router.push() calls made by other components' buttons cannot be
| intercepted by the App Router.
|
| End & Leave → `onEnd()` (the page's normal end-session flow), then go where the
| person was heading. Continue Consultation → close the popup, stay put.
*/

type Pending = { type: "back" } | { type: "href"; href: string; external: boolean };

interface Options {
  active: boolean;
  medium?: string;
  /** Ends the live session exactly as the page's own End button does. */
  onEnd: () => Promise<void>;
  /** Where "Back" lands if the browser has no earlier history entry. */
  fallbackHref?: string;
}

export function useConsultationLeaveGuard({ active, medium, onEnd, fallbackHref = "/" }: Options): ReactNode {
  const router = useRouter();

  const [open, setOpen] = useState(false);
  const [busy, setBusy] = useState(false);

  const pending = useRef<Pending | null>(null);
  const leaving = useRef(false);
  const onEndRef = useRef(onEnd);

  onEndRef.current = onEnd;

  useEffect(() => {
    if (!active) return;

    leaving.current = false;

    // Extra history entry the Back button "consumes" instead of leaving.
    // Keep Next's own history.state fields so its popstate handling stays happy.
    window.history.pushState({ ...(window.history.state ?? {}), __consultGuard: true }, "", window.location.href);

    const onPopState = () => {
      if (leaving.current) return;

      // Back was pressed: put the guard entry back and ask first.
      window.history.pushState({ ...(window.history.state ?? {}), __consultGuard: true }, "", window.location.href);

      pending.current = { type: "back" };
      setOpen(true);
    };

    const onClick = (event: MouseEvent) => {
      if (leaving.current || event.defaultPrevented || event.button !== 0) return;
      if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;

      const anchor = (event.target as Element | null)?.closest?.("a");

      if (!anchor || anchor.hasAttribute("download")) return;
      if (anchor.target && anchor.target !== "_self") return;

      const rawHref = anchor.getAttribute("href");

      if (!rawHref || rawHref.startsWith("#") || /^(mailto:|tel:|javascript:)/i.test(rawHref)) return;

      let url: URL;

      try {
        url = new URL(anchor.href, window.location.href);
      } catch {
        return;
      }

      const external = url.origin !== window.location.origin;

      if (!external && url.pathname + url.search === window.location.pathname + window.location.search) return;

      event.preventDefault();
      event.stopPropagation();

      pending.current = {
        type: "href",
        href: external ? url.href : url.pathname + url.search + url.hash,
        external,
      };

      setOpen(true);
    };

    const onBeforeUnload = (event: BeforeUnloadEvent) => {
      if (leaving.current) return;

      event.preventDefault();
      event.returnValue = "";
    };

    window.addEventListener("popstate", onPopState);
    window.addEventListener("beforeunload", onBeforeUnload);
    // Capture phase: runs before Next's <Link> click handler.
    document.addEventListener("click", onClick, true);

    return () => {
      window.removeEventListener("popstate", onPopState);
      window.removeEventListener("beforeunload", onBeforeUnload);
      document.removeEventListener("click", onClick, true);
    };
  }, [active]);

  const stay = useCallback(() => {
    pending.current = null;
    setOpen(false);
  }, []);

  const endAndLeave = useCallback(async () => {
    const target = pending.current;

    setBusy(true);

    try {
      await onEndRef.current();
    } catch {
      // the page shows its own error; leave anyway since the person asked to
    }

    setBusy(false);
    setOpen(false);
    pending.current = null;
    leaving.current = true;

    if (!target) return;

    if (target.type === "back") {
      // One entry for the page itself + one for our guard entry.
      const before = window.location.href;

      window.history.go(-2);

      window.setTimeout(() => {
        if (window.location.href === before) router.push(fallbackHref);
      }, 600);

      return;
    }

    if (target.external) {
      window.location.assign(target.href);
    } else {
      router.push(target.href);
    }
  }, [fallbackHref, router]);

  if (!open) return null;

  const word = medium === "AUDIO" || medium === "VIDEO" ? "call" : "chat";

  return (
    <div className="leave-consult-backdrop" role="dialog" aria-modal="true" aria-labelledby="leave-consult-title">
      <div className="leave-consult-modal">
        <h5 id="leave-consult-title">Consultation in progress</h5>

        <p>
          Your consultation is currently ongoing. Do you want to end the {word} and leave this screen?
        </p>

        <div className="leave-consult-actions">
          <button type="button" className="leave-consult-continue" onClick={stay} disabled={busy}>
            Continue Consultation
          </button>

          <button type="button" className="leave-consult-end" onClick={endAndLeave} disabled={busy}>
            {busy ? "Ending..." : "End & Leave"}
          </button>
        </div>
      </div>
    </div>
  );
}
