"use client";

import * as React from "react";
import Link from "next/link";
import { motion, AnimatePresence } from "motion/react";
import { Card, CardHeader, CardContent } from "@/components/ui/card";
import { Avatar } from "@/components/ui/primitives";
import { EmptyState } from "@/components/ui/states";
import { describeActivity, hrefFor, type ActivityDto } from "@/components/dashboard/activity-feed";
import { fmtTime, relativeTime } from "@/lib/dates";

type Item = Omit<ActivityDto, "createdAt"> & { createdAt: string };

export function ActivityStream({ items }: { items: Item[] }) {
  const seen = React.useRef<Set<string>>(new Set(items.map((i) => i.id)));
  const [fresh, setFresh] = React.useState<Set<string>>(new Set());
  React.useEffect(() => {
    const newIds = items.filter((i) => !seen.current.has(i.id)).map((i) => i.id);
    if (newIds.length) {
      newIds.forEach((id) => seen.current.add(id));
      setFresh(new Set(newIds));
      const t = setTimeout(() => setFresh(new Set()), 4000);
      return () => clearTimeout(t);
    }
  }, [items]);
  return (
    <Card className="flex flex-col">
      <CardHeader
        title={
          <span className="flex items-center gap-2">
            Live activity <span className="live-dot" />
          </span>
        }
        description="Every material action, as it happens"
        action={<Link href="/audit" className="text-xs font-medium text-primary hover:underline">Audit log</Link>}
      />
      <CardContent className="flex-1 pt-0">
        {items.length === 0 ? (
          <EmptyState compact title="No activity yet" />
        ) : (
          <ul className="max-h-[520px] divide-y divide-border overflow-y-auto scrollbar-thin">
            <AnimatePresence initial={false}>
              {items.map((a) => {
                const href = hrefFor({ ...a, createdAt: new Date(a.createdAt) });
                const inner = (
                  <>
                    <span className="w-11 shrink-0 pt-0.5 text-2xs tabular text-fg-subtle" title={relativeTime(a.createdAt)} suppressHydrationWarning>
                      {fmtTime(a.createdAt)}
                    </span>
                    <Avatar name={a.userName} size="xs" className="mt-0.5" />
                    <span className="min-w-0 flex-1 text-sm leading-snug text-fg-muted">
                      <span className="font-medium text-fg">{a.userName.split(" ")[0]}</span> {describeActivity({ ...a, createdAt: new Date(a.createdAt) })}
                      {a.reason ? <span className="block text-2xs italic text-fg-subtle">“{a.reason}”</span> : null}
                    </span>
                  </>
                );
                return (
                  <motion.li key={a.id} layout initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.3, ease: [0.16, 1, 0.3, 1] }} className={fresh.has(a.id) ? "animate-stream-in rounded-md" : undefined}>
                    {href ? (
                      <Link href={href} className="-mx-2 flex gap-2.5 rounded-md px-2 py-2 transition hover:bg-surface-2">
                        {inner}
                      </Link>
                    ) : (
                      <div className="flex gap-2.5 py-2">{inner}</div>
                    )}
                  </motion.li>
                );
              })}
            </AnimatePresence>
          </ul>
        )}
      </CardContent>
    </Card>
  );
}
