import { Link } from "@tanstack/react-router";
import {
  CheckCircle2,
  CloudUpload,
  Ban,
  MessageSquareText,
  MessageSquareReply,
  PencilLine,
  Sparkles,
  Upload,
  XCircle,
  Link2,
  type LucideIcon,
} from "lucide-react";
import type { ActivityEvent } from "@/lib/ledger-types";
import { relativeTime } from "@/lib/ledger-store";

const ICONS: Record<ActivityEvent["type"], { icon: LucideIcon; className: string }> = {
  upload: { icon: Upload, className: "bg-muted text-muted-foreground" },
  ai: { icon: Sparkles, className: "bg-primary-soft text-primary" },
  approve: { icon: CheckCircle2, className: "bg-success-soft text-success" },
  reject: { icon: XCircle, className: "bg-destructive-soft text-destructive" },
  sync: { icon: CloudUpload, className: "bg-primary-soft text-primary" },
  "sync-failed": { icon: Ban, className: "bg-destructive-soft text-destructive" },
  query: { icon: MessageSquareText, className: "bg-attention-soft text-attention" },
  answer: { icon: MessageSquareReply, className: "bg-muted text-foreground" },
  edit: { icon: PencilLine, className: "bg-muted text-muted-foreground" },
  match: { icon: Link2, className: "bg-muted text-foreground" },
};

export function ActivityTimeline({
  events,
  showLinks = false,
}: {
  events: ActivityEvent[];
  showLinks?: boolean;
}) {
  return (
    <ol className="relative px-5 py-4">
      <span className="absolute top-6 bottom-6 left-[31px] w-px bg-border" aria-hidden="true" />
      {events.map((e) => {
        const conf = ICONS[e.type];
        const Icon = conf.icon;
        return (
          <li key={e.id} className="relative flex gap-3 py-2.5">
            <span
              className={`relative z-10 flex size-7 shrink-0 items-center justify-center rounded-full ring-4 ring-surface ${conf.className}`}
            >
              <Icon size={14} aria-hidden="true" />
            </span>
            <div className="min-w-0 flex-1">
              <p className="text-[13.5px] leading-5 text-foreground">{e.text}</p>
              <p className="mt-0.5 flex flex-wrap items-center gap-x-2 text-[12px] text-muted-foreground">
                <span>{e.actor}</span>
                <span aria-hidden="true">·</span>
                <span>{relativeTime(e.at)}</span>
                {showLinks && e.invoiceId ? (
                  <>
                    <span aria-hidden="true">·</span>
                    <Link
                      to="/firm/invoices/$id"
                      params={{ id: e.invoiceId }}
                      className="text-primary hover:underline"
                    >
                      View invoice
                    </Link>
                  </>
                ) : null}
              </p>
            </div>
          </li>
        );
      })}
    </ol>
  );
}
