"use client";

import { useMemo } from "react";
import Link from "next/link";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { EmptyState } from "@/components/ui/empty-state";
import { cn } from "@/lib/utils";
import { ALL_ORGANIZATIONS } from "@/lib/sag/entities";
import {
  markAllRead,
  markRead,
  type Notification,
  type NotificationSeverity,
} from "@/lib/notifications/registry";

interface NotificationsPanelProps {
  notifications: Notification[];
  /** Called after a row is clicked (so the bell can close itself + refresh). */
  onAfterRead: () => void;
}

const SEVERITY_DOT: Record<NotificationSeverity, string> = {
  critical: "bg-destructive",
  warning: "bg-yellow-500",
  info: "bg-blue-500",
  success: "bg-emerald-500",
};

const SEVERITY_LABEL: Record<NotificationSeverity, string> = {
  critical: "Critical",
  warning: "Warning",
  info: "Info",
  success: "Done",
};

export function NotificationsPanel({
  notifications,
  onAfterRead,
}: NotificationsPanelProps) {
  const unreadList = useMemo(
    () => notifications.filter((n) => !n.readAt),
    [notifications]
  );
  const unread = unreadList.length;
  const total = notifications.length;

  function handleRowClick(n: Notification) {
    if (!n.readAt) markRead(n.id);
    onAfterRead();
  }

  function handleMarkAll() {
    markAllRead();
    onAfterRead();
  }

  return (
    <div className="flex w-[28rem] max-w-[92vw] flex-col">
      {/* Header */}
      <div className="flex items-center justify-between border-b px-4 py-3">
        <div className="flex items-center gap-2 min-w-0">
          <div className="text-sm font-semibold">Notifications</div>
          {unread > 0 ? (
            <Badge variant="destructive" className="text-[10px] px-1.5 py-0">
              {unread > 99 ? "99+" : unread} unread
            </Badge>
          ) : (
            <Badge variant="outline" className="text-[10px] px-1.5 py-0">
              All caught up
            </Badge>
          )}
        </div>
        {unread > 0 && (
          <Button
            variant="ghost"
            size="sm"
            className="text-[11px] h-7"
            onClick={handleMarkAll}
          >
            Mark all read
          </Button>
        )}
      </div>

      {/* Body */}
      <div className="max-h-96 overflow-y-auto">
        {total === 0 ? (
          <div className="p-2">
            <EmptyState
              size="compact"
              icon="🎉"
              title="Inbox zero"
              description="No urgent items across the portfolio. We'll surface bills, filings, license renewals, and agent updates here as they come in."
              className="border-0 shadow-none"
            />
          </div>
        ) : (
          <ul role="list" className="divide-y">
            {notifications.map((n) => (
              <NotificationRow
                key={n.id}
                notification={n}
                onClick={() => handleRowClick(n)}
                onMarkRead={() => {
                  markRead(n.id);
                  onAfterRead();
                }}
              />
            ))}
          </ul>
        )}
      </div>

      {/* Footer */}
      <div className="border-t bg-muted/30 px-4 py-2 flex items-center justify-between text-[11px]">
        <span className="text-muted-foreground tabular-nums">
          {total === 0
            ? "0 notifications"
            : `${unread} unread · ${total} total`}
        </span>
        <Link
          href="/app/activity"
          onClick={onAfterRead}
          className="text-[var(--sag-brand)] font-medium hover:underline"
        >
          View activity log →
        </Link>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Row
// ──────────────────────────────────────────────────────────────────────────

function NotificationRow({
  notification,
  onClick,
  onMarkRead,
}: {
  notification: Notification;
  onClick: () => void;
  onMarkRead: () => void;
}) {
  const n = notification;
  const unread = !n.readAt;
  const org = n.entitySlug
    ? ALL_ORGANIZATIONS.find((o) => o.slug === n.entitySlug)
    : undefined;
  const relative = formatRelative(n.createdAt);

  const body = (
    <div className="flex gap-3 px-4 py-3">
      <span
        className={cn(
          "mt-1.5 inline-block h-2 w-2 shrink-0 rounded-full",
          SEVERITY_DOT[n.severity]
        )}
        aria-hidden="true"
      />
      <div className="min-w-0 flex-1">
        <div
          className={cn(
            "text-sm leading-snug",
            unread ? "font-semibold" : "font-medium text-muted-foreground"
          )}
        >
          {n.title}
        </div>
        {n.description && (
          <div className="mt-0.5 text-xs text-muted-foreground line-clamp-2">
            {n.description}
          </div>
        )}
        <div className="mt-1 flex items-center gap-2 text-[10px] text-muted-foreground">
          <span className="uppercase tracking-wider font-medium">
            {SEVERITY_LABEL[n.severity]}
          </span>
          {org && (
            <span className="truncate">
              · {org.emoji ?? "🏢"} {org.name}
            </span>
          )}
          <span className="ml-auto tabular-nums shrink-0">{relative}</span>
        </div>
      </div>
    </div>
  );

  return (
    <li
      className={cn(
        "group relative transition-colors",
        unread ? "bg-accent/50 hover:bg-accent/70" : "hover:bg-muted/50"
      )}
    >
      {n.href ? (
        <Link
          href={n.href}
          onClick={onClick}
          className="block focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"
        >
          {body}
        </Link>
      ) : (
        <button
          type="button"
          onClick={onClick}
          className="block w-full text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"
        >
          {body}
        </button>
      )}
      {unread && (
        <button
          type="button"
          onClick={(e) => {
            e.preventDefault();
            e.stopPropagation();
            onMarkRead();
          }}
          className="absolute right-2 top-2 opacity-0 group-hover:opacity-100 transition-opacity text-[10px] text-muted-foreground hover:text-foreground bg-background/80 backdrop-blur rounded px-1.5 py-0.5"
          aria-label="Mark read"
        >
          Mark read
        </button>
      )}
    </li>
  );
}

function formatRelative(iso: string): string {
  const t = new Date(iso).getTime();
  if (!Number.isFinite(t)) return "—";
  const diffSec = Math.round((Date.now() - t) / 1000);
  if (diffSec < 60) return diffSec <= 1 ? "just now" : `${diffSec}s ago`;
  const diffMin = Math.round(diffSec / 60);
  if (diffMin < 60) return `${diffMin}m ago`;
  const diffHr = Math.round(diffMin / 60);
  if (diffHr < 24) return `${diffHr}h ago`;
  const diffDay = Math.round(diffHr / 24);
  if (diffDay < 30) return `${diffDay}d ago`;
  const diffMo = Math.round(diffDay / 30);
  if (diffMo < 12) return `${diffMo}mo ago`;
  return `${Math.round(diffMo / 12)}y ago`;
}
