import type { KeyboardEvent, MouseEvent } from "react";
import {
  Banknote,
  CheckCircle2,
  Circle,
  FileText,
  Pill,
  UserPlus,
  Wrench,
  XCircle,
  type LucideIcon,
} from "lucide-react";
import { fmt } from "@/lib/format";
import type { Activity } from "@/types";
import { cn } from "@/lib/utils";

const kindConfig: Record<
  Activity["kind"],
  { icon: LucideIcon; tone: string; tint: string }
> = {
  claim_submitted: {
    icon: FileText,
    tone: "text-[hsl(var(--accent))]",
    tint: "bg-accent/10",
  },
  claim_accepted: {
    icon: CheckCircle2,
    tone: "text-[hsl(var(--success))]",
    tint: "bg-[hsl(var(--success)/0.12)]",
  },
  claim_paid: {
    icon: Banknote,
    tone: "text-[hsl(var(--success))]",
    tint: "bg-[hsl(var(--success)/0.12)]",
  },
  claim_denied: {
    icon: XCircle,
    tone: "text-destructive",
    tint: "bg-destructive/12",
  },
  remit_received: {
    icon: Pill,
    tone: "text-[hsl(var(--warning))]",
    tint: "bg-[hsl(var(--warning)/0.12)]",
  },
  provider_added: {
    icon: UserPlus,
    tone: "text-foreground",
    tint: "bg-muted/60",
  },
  manual_match: {
    icon: Wrench,
    tone: "text-muted-foreground",
    tint: "bg-muted/40",
  },
};

const FALLBACK_KIND: { icon: LucideIcon; tone: string; tint: string } = {
  icon: Circle,
  tone: "text-muted-foreground",
  tint: "bg-muted/40",
};

export function ActivityFeed({
  items,
  emptyMessage = "No activity yet.",
  onItemClick,
}: {
  items: Activity[];
  emptyMessage?: string;
  /**
   * Optional click handler for SP21 Universal Drill-Down (Task 2.5).
   * When provided, each row becomes a clickable target: the row's
   * outer `<li>` gets `role="button"`, `tabIndex`, the `drillable`
   * hover affordance (chevron + tint), and an Enter/Space keybinding.
   *
   * `e.stopPropagation()` is called before invoking the handler so the
   * click doesn't bubble to a hypothetical parent row click — same
   * fix that landed on `DrillableCell` in Task 2.4. When omitted, the
   * feed renders exactly as before (no extra DOM, no extra attrs).
   */
  onItemClick?: (event: Activity) => void;
}) {
  if (items.length === 0) {
    return (
      <div className="text-[13px] text-muted-foreground px-2 py-6 text-center">
        {emptyMessage}
      </div>
    );
  }
  return (
    <ul className="divide-y divide-border/40">
      {items.map((a) => {
        const cfg = kindConfig[a.kind] ?? FALLBACK_KIND;
        const Icon = cfg.icon;
        // SP21 Task 2.5: when a click handler is wired, the row
        // becomes a keyboard-focusable button-like element with the
        // drillable hover affordance. We attach the handler to the
        // <li> directly (matching the Dashboard's existing patterns
        // for "Top providers" / "Recent denials" rows) so the click
        // target covers the full row width including padding.
        const rowProps = onItemClick
          ? {
              role: "button" as const,
              tabIndex: 0,
              "aria-label": `View ${a.kind.replace(/_/g, " ")}: ${a.message}`,
              className:
                "drillable flex items-start gap-3 py-3 first:pt-0 last:pb-0 rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1",
              onClick: (e: MouseEvent<HTMLLIElement>) => {
                e.stopPropagation();
                onItemClick(a);
              },
              onKeyDown: (e: KeyboardEvent<HTMLLIElement>) => {
                if (e.key === "Enter" || e.key === " ") {
                  e.preventDefault();
                  e.stopPropagation();
                  onItemClick(a);
                }
              },
            }
          : {
              className: "flex items-start gap-3 py-3 first:pt-0 last:pb-0",
            };
        return (
          <li key={a.id} {...rowProps}>
            <div
              className={cn(
                "mt-0.5 h-7 w-7 shrink-0 rounded-md ring-1 ring-inset ring-border/40 flex items-center justify-center",
                cfg.tint,
                cfg.tone
              )}
            >
              <Icon className="h-3.5 w-3.5" strokeWidth={1.75} />
            </div>
            <div className="flex-1 min-w-0">
              <div className="text-[13px] text-foreground/95 leading-snug">
                {a.message}
              </div>
              <div className="mono text-[10.5px] text-muted-foreground mt-0.5 flex items-center gap-2">
                <span>{fmt.relative(a.timestamp)}</span>
                {a.npi ? (
                  <>
                    <span className="opacity-40">·</span>
                    <span>{a.npi}</span>
                  </>
                ) : null}
                {a.amount ? (
                  <>
                    <span className="opacity-40">·</span>
                    <span>{fmt.usd(a.amount)}</span>
                  </>
                ) : null}
              </div>
            </div>
          </li>
        );
      })}
    </ul>
  );
}
