"use client";

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { apiGet, apiPost } from "@/lib/api";
import type { AppNotification, AppNotificationSnapshot } from "@/types";

type AppNotificationsResponse = { snapshot: AppNotificationSnapshot };
type StateResponse = { snapshot: AppNotificationSnapshot };

function toneClass(tone: AppNotification["tone"]) {
  if (tone === "URGENT") return "border-rose-200 bg-rose-50 text-rose-700";
  if (tone === "WATCH") return "border-amber-200 bg-amber-50 text-amber-700";
  if (tone === "GOOD") return "border-emerald-200 bg-emerald-50 text-emerald-700";
  return "border-slate-200 bg-slate-50 text-slate-700";
}

function countLabel(count: number) {
  if (count > 9) return "9+";
  return String(count);
}

export function AppNotificationBell() {
  const [open, setOpen] = useState(false);
  const [snapshot, setSnapshot] = useState<AppNotificationSnapshot | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    let active = true;
    function handleNotificationUpdate(event: Event) {
      const nextSnapshot = (event as CustomEvent<AppNotificationSnapshot>).detail;
      if (nextSnapshot) setSnapshot(nextSnapshot);
    }

    window.addEventListener("dispatchspot:notifications-updated", handleNotificationUpdate);
    apiGet<AppNotificationsResponse>("/api/app-notifications")
      .then((data) => {
        if (!active) return;
        setSnapshot(data.snapshot);
        setError(null);
      })
      .catch(() => {
        if (!active) return;
        setError("Notifications unavailable");
      });
    return () => {
      active = false;
      window.removeEventListener("dispatchspot:notifications-updated", handleNotificationUpdate);
    };
  }, []);

  const items = useMemo(() => snapshot?.items.slice(0, 4) ?? [], [snapshot]);
  const attentionCount = snapshot?.bellCount ?? 0;

  async function markAllRead() {
    if (!snapshot || snapshot.unreadCount === 0) return;
    setBusy(true);
    try {
      const response = await apiPost<StateResponse>("/api/app-notifications/state", { action: "MARK_ALL_READ" });
      setSnapshot(response.snapshot);
      window.dispatchEvent(new CustomEvent("dispatchspot:notifications-updated", { detail: response.snapshot }));
      setError(null);
    } catch {
      setError("Could not mark alerts as read");
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="relative">
      <button
        type="button"
        onClick={() => setOpen((value) => !value)}
        className="relative inline-flex h-11 w-11 items-center justify-center rounded-2xl border border-slate-200 bg-white text-lg text-slate-700 shadow-sm transition hover:bg-slate-50"
        aria-label="Open notifications"
        aria-expanded={open}
      >
        🔔
        {attentionCount > 0 ? (
          <span className="absolute -right-1 -top-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-rose-600 px-1 text-[10px] font-bold text-white">
            {countLabel(attentionCount)}
          </span>
        ) : null}
      </button>

      {open ? (
        <div className="absolute right-0 z-40 mt-3 w-[min(92vw,420px)] overflow-hidden rounded-3xl border border-slate-200 bg-white shadow-2xl">
          <div className="border-b border-slate-200 bg-slate-50 px-4 py-3">
            <div className="flex items-center justify-between gap-3">
              <div>
                <div className="text-sm font-semibold text-slate-950">Notifications</div>
                <div className="mt-0.5 text-xs text-slate-500">
                  {snapshot ? `${snapshot.unreadCount} unread · ${snapshot.attentionCount} active` : "Important dispatch, paperwork, billing, and task alerts."}
                </div>
              </div>
              <div className="flex shrink-0 items-center gap-2">
                {snapshot?.unreadCount ? (
                  <button
                    type="button"
                    onClick={markAllRead}
                    disabled={busy}
                    className="rounded-full border border-slate-200 bg-white px-3 py-1.5 text-xs font-semibold text-slate-700 disabled:cursor-wait disabled:text-slate-400"
                  >
                    Read all
                  </button>
                ) : null}
                <Link href="/notifications" onClick={() => setOpen(false)} className="rounded-full bg-slate-900 px-3 py-1.5 text-xs font-semibold text-white">
                  View all
                </Link>
              </div>
            </div>
          </div>

          <div className="max-h-[420px] overflow-y-auto p-3">
            {error ? (
              <div className="rounded-2xl border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800">{error}</div>
            ) : snapshot && items.length === 0 ? (
              <div className="rounded-2xl border border-emerald-200 bg-emerald-50 p-3 text-sm text-emerald-800">
                {snapshot.emptyState?.title ?? "No urgent alerts right now"}
              </div>
            ) : !snapshot ? (
              <div className="rounded-2xl border border-slate-200 bg-slate-50 p-3 text-sm text-slate-600">Checking notifications...</div>
            ) : (
              <div className="space-y-2">
                {items.map((item) => (
                  <Link
                    key={item.id}
                    href={item.href}
                    onClick={() => setOpen(false)}
                    className={`block rounded-2xl border p-3 transition hover:bg-slate-50 ${item.isRead ? "border-slate-200" : "border-blue-200 bg-blue-50/50"}`}
                  >
                    <div className="flex items-start justify-between gap-3">
                      <div className="min-w-0">
                        <div className="flex items-center gap-2">
                          {!item.isRead ? <span className="h-2.5 w-2.5 rounded-full bg-blue-600" aria-label="Unread alert" /> : null}
                          <div className="truncate text-sm font-semibold text-slate-950">{item.title}</div>
                        </div>
                        <p className="mt-1 line-clamp-2 text-xs leading-5 text-slate-600">{item.message}</p>
                      </div>
                      <span className={`shrink-0 rounded-full border px-2 py-1 text-[10px] font-semibold ${toneClass(item.tone)}`}>{item.sourceLabel}</span>
                    </div>
                  </Link>
                ))}
              </div>
            )}
          </div>
        </div>
      ) : null}
    </div>
  );
}
