"use client";

import clsx from "clsx";
import Link from "next/link";
import { useEffect, useState } from "react";
import { Bell } from "lucide-react";
import { api } from "@/lib/api";
import { formatDateTime } from "@/lib/format";
import type { AppNotification } from "@/lib/types";

/** Header bell: billing and account alerts for the current workspace. Refreshes every minute. */
export function NotificationBell() {
  const [open, setOpen] = useState(false);
  const [data, setData] = useState<{ items: AppNotification[]; unread: number } | null>(null);

  useEffect(() => {
    let alive = true;
    const load = () =>
      api
        .get<{ data: AppNotification[]; meta: { unread: number } }>("/notifications")
        .then((r) => alive && setData({ items: r.data, unread: r.meta.unread }))
        .catch(() => undefined);
    void load();
    const t = setInterval(load, 60_000);
    return () => {
      alive = false;
      clearInterval(t);
    };
  }, []);

  async function toggle() {
    const next = !open;
    setOpen(next);
    if (!next) return;
    // Opening always shows the latest alerts (a payment may have just created one), then marks them read.
    const r = await api.get<{ data: AppNotification[]; meta: { unread: number } }>("/notifications").catch(() => null);
    if (r) setData({ items: r.data, unread: r.meta.unread });
    if (r?.meta.unread || data?.unread) {
      await api.post("/notifications/read").catch(() => undefined);
      setData((d) => d && { ...d, unread: 0 });
    }
  }

  return (
    <div className="relative">
      <button onClick={toggle} aria-expanded={open} aria-label={data?.unread ? `Notifications, ${data.unread} unread` : "Notifications"} className="relative rounded-full p-2 text-muted hover:bg-paper hover:text-ink">
        <Bell className="size-5" />
        {data?.unread ? <span className="tabular absolute right-1 top-1 grid min-w-4 place-items-center rounded-full bg-brick px-1 text-[10px] font-semibold leading-4 text-white">{data.unread > 9 ? "9+" : data.unread}</span> : null}
      </button>
      {open && (
        <>
          <div className="fixed inset-0 z-30" onClick={() => setOpen(false)} />
          <div className="absolute right-0 z-40 mt-2 w-80 max-w-[calc(100vw-2rem)] rounded-lg border border-line bg-white shadow-lg">
            <p className="flex items-center justify-between border-b border-line px-4 py-2.5 text-sm font-semibold">
              Notifications
              <Link href="/settings/notifications" onClick={() => setOpen(false)} className="text-[13px] font-normal text-teal hover:underline">
                Email settings
              </Link>
            </p>
            <ul className="max-h-96 divide-y divide-line overflow-y-auto">
              {!data?.items.length && <li className="px-4 py-6 text-center text-sm text-muted">Nothing new.</li>}
              {data?.items.map((n) => (
                <li key={n.id}>
                  <Link href={n.link ?? "#"} onClick={() => setOpen(false)} className={clsx("block px-4 py-3 hover:bg-paper", !n.read && "bg-teal-soft/40")}>
                    <p className="text-sm font-medium">{n.title}</p>
                    {n.body && <p className="mt-0.5 text-[13px] text-muted">{n.body}</p>}
                    <p className="mt-1 text-xs text-muted">{formatDateTime(n.created_at)}</p>
                  </Link>
                </li>
              ))}
            </ul>
          </div>
        </>
      )}
    </div>
  );
}
