"use client";

import { useEffect, useState } from "react";
import { BellIcon, BellOffIcon, AlertCircleIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  getPermission,
  isOptedIn,
  notificationSupport,
  requestPermission,
  setOptedIn,
  showNotification,
  type NotificationPermission,
} from "@/lib/notifications";

/**
 * Settings-page card that lets the operator opt into browser
 * notifications for "reminder fired" and "send-test sent" events.
 *
 * Three states the UI surfaces:
 *
 *   1. Not supported (server / older browser) — shows a one-line
 *      muted note. No action.
 *   2. Permission not granted — Enable button asks the browser.
 *      If the user blocks the prompt we fall back to a
 *      "blocked in browser" note pointing them at site settings.
 *   3. Granted + opted in — toggle to disable, plus a "Test"
 *      button that fires a sample notification so the operator
 *      knows the wiring works end-to-end.
 */
export function NotificationsToggle() {
  const [supported, setSupported] = useState(false);
  const [permission, setPermission] = useState<NotificationPermission>("default");
  const [optedIn, setOptedInState] = useState(false);
  const [busy, setBusy] = useState(false);

  // Hydrate from the live browser state once on mount; the server
  // can't know any of these values.
  useEffect(() => {
    setSupported(notificationSupport() === "supported");
    setPermission(getPermission());
    setOptedInState(isOptedIn());
  }, []);

  async function enable() {
    setBusy(true);
    const result = await requestPermission();
    setPermission(result);
    if (result === "granted") {
      setOptedIn(true);
      setOptedInState(true);
    }
    setBusy(false);
  }

  function disable() {
    setOptedIn(false);
    setOptedInState(false);
  }

  function fireTest() {
    showNotification({
      title: "Test notification",
      body: "Notifications are wired up. Reminder runs and send-tests will surface here.",
      tag: "settings-test",
    });
  }

  if (!supported) {
    return (
      <div className="flex items-center gap-2 text-xs text-muted-foreground">
        <BellOffIcon className="size-3.5 shrink-0" />
        Notifications aren&apos;t supported by this browser.
      </div>
    );
  }

  if (permission === "denied") {
    return (
      <div className="flex items-start gap-2 text-xs text-muted-foreground">
        <AlertCircleIcon className="size-3.5 shrink-0 mt-0.5" />
        <span>
          Notifications are blocked at the browser level. Enable them
          in your site settings (lock icon next to the URL) and
          reload.
        </span>
      </div>
    );
  }

  if (permission === "granted" && optedIn) {
    return (
      <div className="flex flex-wrap items-center gap-2">
        <span className="inline-flex items-center gap-1.5 text-xs text-emerald-700 dark:text-emerald-400">
          <BellIcon className="size-3.5" />
          On
        </span>
        <Button type="button" size="sm" variant="outline" onClick={fireTest}>
          Send test
        </Button>
        <Button type="button" size="sm" variant="ghost" onClick={disable}>
          Turn off
        </Button>
      </div>
    );
  }

  return (
    <Button type="button" size="sm" onClick={enable} disabled={busy} className="gap-1.5">
      <BellIcon className="size-3.5" />
      {busy ? "Asking…" : "Enable notifications"}
    </Button>
  );
}
