"use client";

import { useCallback, useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { Bell, Settings2, X } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
  Alert,
  AlertDescription,
  AlertTitle,
} from "@/components/ui/alert";
import {
  areBrowserNotificationsEnabled,
  canUseDesktopBrowserNotifications,
  getBrowserNotificationPermission,
  requestBrowserNotificationPermission,
  type BrowserNotificationPermission,
} from "@/lib/browser-notifications";

const DISMISS_SESSION_KEY = "saleshub.browser-notifications-prompt.dismissed";

function isDismissedThisSession(): boolean {
  if (typeof sessionStorage === "undefined") return false;
  return sessionStorage.getItem(DISMISS_SESSION_KEY) === "1";
}

function dismissForSession(): void {
  sessionStorage.setItem(DISMISS_SESSION_KEY, "1");
}

/**
 * Bottom-right prompt when desktop browser notifications are not enabled.
 * User must click Enable to trigger the native permission dialog.
 */
export function BrowserNotificationPermissionPrompt() {
  const { status: sessionStatus } = useSession();
  const [visible, setVisible] = useState(false);
  const [permission, setPermission] =
    useState<BrowserNotificationPermission>("default");
  const [requesting, setRequesting] = useState(false);

  const refresh = useCallback(() => {
    if (sessionStatus !== "authenticated") {
      setVisible(false);
      return;
    }

    if (!canUseDesktopBrowserNotifications()) {
      setVisible(false);
      return;
    }

    if (areBrowserNotificationsEnabled()) {
      setVisible(false);
      return;
    }

    const perm = getBrowserNotificationPermission();
    setPermission(perm);

    if (perm === "unsupported" || perm === "granted") {
      setVisible(false);
      return;
    }

    setVisible(!isDismissedThisSession());
  }, [sessionStatus]);

  useEffect(() => {
    refresh();

    if (typeof navigator === "undefined" || !("permissions" in navigator)) {
      return;
    }

    let cancelled = false;
    let status: PermissionStatus | null = null;

    void navigator.permissions
      .query({ name: "notifications" as PermissionName })
      .then((result) => {
        if (cancelled) return;
        status = result;
        result.addEventListener("change", refresh);
      })
      .catch(() => {
        /* Permissions API unavailable for notifications */
      });

    return () => {
      cancelled = true;
      status?.removeEventListener("change", refresh);
    };
  }, [refresh]);

  const handleGotIt = async () => {
    if (areBrowserNotificationsEnabled()) {
      setVisible(false);
      return;
    }

    setRequesting(true);
    try {
      const result = await requestBrowserNotificationPermission();
      setPermission(result);

      if (result === "granted") {
        sessionStorage.removeItem(DISMISS_SESSION_KEY);
        toast.success("Desktop notifications enabled");
        setVisible(false);
        return;
      }

      // Blocked: browser won't show the native dialog again. The denied UI
      // already renders manual steps, so no error toast is needed.
    } finally {
      setRequesting(false);
      refresh();
    }
  };

  const handleDismiss = () => {
    dismissForSession();
    setVisible(false);
  };

  const handleConfirmedEnabled = () => {
    refresh();

    if (areBrowserNotificationsEnabled()) {
      sessionStorage.removeItem(DISMISS_SESSION_KEY);
      setVisible(false);
      return;
    }

    handleDismiss();
  };

  if (!visible || areBrowserNotificationsEnabled()) return null;

  const isDenied = permission === "denied";

  return (
    <div
      className="pointer-events-none fixed bottom-4 right-4 z-100 w-[min(calc(100vw-2rem),22rem)] animate-in fade-in slide-in-from-bottom-2 duration-300"
      role="region"
      aria-label="Enable browser notifications"
    >
      <Alert
        variant="info"
        className="pointer-events-auto shadow-lg border bg-card/95 backdrop-blur-sm supports-backdrop-filter:bg-card/90"
      >
        <Bell className="size-4" aria-hidden />
        <div className="col-start-2 flex items-start justify-between gap-2">
          <AlertTitle>Enable desktop notifications</AlertTitle>
          <button
            type="button"
            onClick={handleDismiss}
            className="shrink-0 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
            aria-label="Dismiss notification prompt"
          >
            <X className="size-4" />
          </button>
        </div>
        <AlertDescription className="col-start-2 space-y-3">
          <p>
            {isDenied
              ? "Notifications are blocked for this site. Allow them in your browser settings, then refresh."
              : "Get deal reminders and alerts even when this tab is in the background."}
          </p>
          {isDenied ? (
            <ol className="list-decimal space-y-1 pl-4 text-xs text-muted-foreground">
              <li>
                Click the lock / tune icon (
                <Settings2 className="inline size-3 -translate-y-px" />) in the
                address bar, left of the URL.
              </li>
              <li>
                Find <span className="font-medium">Notifications</span> and set
                it to <span className="font-medium">Allow</span>.
              </li>
              <li>Refresh this page.</li>
            </ol>
          ) : null}
          {!isDenied ? (
            <div className="flex flex-wrap items-center gap-2">
              <Button
                size="sm"
                onClick={() => void handleGotIt()}
                disabled={requesting}
              >
                {requesting ? "Enabling…" : "Got it"}
              </Button>
              <Button size="sm" variant="ghost" onClick={handleDismiss}>
                Not now
              </Button>
            </div>
          ) : (
            <div className="flex flex-wrap items-center gap-2">
              <Button size="sm" onClick={handleConfirmedEnabled}>
                I&apos;ve enabled it
              </Button>
              <Button size="sm" variant="ghost" onClick={handleDismiss}>
                Dismiss
              </Button>
            </div>
          )}
        </AlertDescription>
      </Alert>
    </div>
  );
}
