"use client";

import { useEffect, useRef, useState, useTransition } from "react";
import Link from "next/link";
import { markNotificationReadAction } from "@/lib/actions/notifications";

type NotificationRow = {
  id: string;
  title: string;
  body: string;
  link: string;
  read: boolean;
  createdAt: string;
};

function timeAgo(iso: string, locale: string): string {
  const diffMs = Date.now() - new Date(iso).getTime();
  const minutes = Math.floor(diffMs / 60000);
  const isEn = locale === "en";
  if (minutes < 1) return isEn ? "just now" : "gerade eben";
  if (minutes < 60) return isEn ? `${minutes}m ago` : `vor ${minutes} Min.`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return isEn ? `${hours}h ago` : `vor ${hours} Std.`;
  const days = Math.floor(hours / 24);
  return isEn ? `${days}d ago` : `vor ${days} Tag${days === 1 ? "" : "en"}`;
}

export function NotificationBell({
  initialUnreadCount,
  initialNotifications,
  viewAllHref,
  locale = "de",
  emptyLabel = "Keine Benachrichtigungen.",
  viewAllLabel = "Alle anzeigen",
}: {
  initialUnreadCount: number;
  initialNotifications: NotificationRow[];
  viewAllHref: string;
  locale?: string;
  emptyLabel?: string;
  viewAllLabel?: string;
}) {
  const [open, setOpen] = useState(false);
  const [unreadCount, setUnreadCount] = useState(initialUnreadCount);
  const [notifications, setNotifications] = useState(initialNotifications);
  const [, startTransition] = useTransition();
  const containerRef = useRef<HTMLDivElement>(null);

  // Alle 45s im Hintergrund nachladen, damit die Glocke einigermaßen aktuell
  // bleibt, ohne eine echte Push-Verbindung aufbauen zu müssen.
  useEffect(() => {
    const interval = setInterval(() => {
      fetch("/api/notifications/summary")
        .then((r) => r.json())
        .then((data: { unreadCount: number; notifications: NotificationRow[] }) => {
          setUnreadCount(data.unreadCount);
          setNotifications(data.notifications);
        })
        .catch(() => {});
    }, 45000);
    return () => clearInterval(interval);
  }, []);

  useEffect(() => {
    function onClickOutside(e: MouseEvent) {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) setOpen(false);
    }
    document.addEventListener("mousedown", onClickOutside);
    return () => document.removeEventListener("mousedown", onClickOutside);
  }, []);

  function handleClick(n: NotificationRow) {
    setOpen(false);
    if (!n.read) {
      setUnreadCount((c) => Math.max(0, c - 1));
      setNotifications((prev) => prev.map((x) => (x.id === n.id ? { ...x, read: true } : x)));
      startTransition(() => markNotificationReadAction(n.id));
    }
  }

  return (
    <div className="relative" ref={containerRef}>
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        className="relative flex items-center hover:text-[var(--rk-ink)] transition-colors"
        aria-label="Benachrichtigungen"
      >
        <svg width="17" height="17" viewBox="0 0 24 24" fill="none">
          <path
            d="M6 8a6 6 0 1 1 12 0c0 4.5 1.5 6 2 6.5H4c.5-.5 2-2 2-6.5Z"
            stroke="currentColor"
            strokeWidth="1.6"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
          <path d="M9.5 17.5a2.5 2.5 0 0 0 5 0" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
        </svg>
        {unreadCount > 0 && (
          <span className="absolute -top-1.5 -right-2 min-w-[1rem] h-4 px-1 rounded-full bg-red-500 text-white text-[0.6rem] leading-4 text-center font-medium">
            {unreadCount > 9 ? "9+" : unreadCount}
          </span>
        )}
      </button>

      {open && (
        <div className="absolute right-0 top-full mt-2 w-80 max-w-[90vw] bg-[var(--rk-surface)] border border-white/10 rounded-xl shadow-xl shadow-black/40 overflow-hidden normal-case tracking-normal text-left z-50">
          <div className="max-h-96 overflow-y-auto">
            {notifications.length === 0 ? (
              <p className="text-xs text-[var(--rk-ink-muted)] px-4 py-6 text-center">{emptyLabel}</p>
            ) : (
              notifications.map((n) => (
                <Link
                  key={n.id}
                  href={n.link || viewAllHref}
                  onClick={() => handleClick(n)}
                  className={`flex gap-2 px-4 py-3 border-b border-white/5 hover:bg-white/5 transition-colors ${
                    n.read ? "" : "bg-white/[0.03]"
                  }`}
                >
                  <span className={`mt-1.5 w-1.5 h-1.5 rounded-full shrink-0 ${n.read ? "bg-transparent" : "bg-emerald-400"}`} />
                  <span className="min-w-0">
                    <span className="block text-xs text-[var(--rk-ink)]">{n.title}</span>
                    {n.body && <span className="block text-xs text-[var(--rk-ink-muted)] mt-0.5 truncate">{n.body}</span>}
                    <span className="block text-[0.65rem] text-[var(--rk-ink-muted)] mt-1">{timeAgo(n.createdAt, locale)}</span>
                  </span>
                </Link>
              ))
            )}
          </div>
          <Link
            href={viewAllHref}
            onClick={() => setOpen(false)}
            className="block text-center text-xs text-[var(--rk-ink-muted)] hover:text-[var(--rk-ink)] px-4 py-2.5 border-t border-white/10 transition-colors"
          >
            {viewAllLabel}
          </Link>
        </div>
      )}
    </div>
  );
}
