'use client';

import { useQuery } from '@tanstack/react-query';
import { format, formatDistanceToNowStrict } from 'date-fns';
import {
  Pencil,
  FileText,
  Clock,
  PlusCircle,
  Archive,
  RotateCcw,
  Trophy,
  XCircle,
  RefreshCcw,
  Bot,
} from 'lucide-react';

import { apiFetch } from '@/lib/api/client';

interface TimelineEvent {
  id: string;
  type: 'audit' | 'document_event';
  action: string;
  description: string;
  userId: string | null;
  /** Resolved display name (server-side join). Falls back to userId when null. */
  userName?: string | null;
  createdAt: string;
  metadata: Record<string, unknown>;
}

interface InterestTimelineProps {
  interestId: string;
}

const LOST_OUTCOMES = new Set([
  'lost_other_marina',
  'lost_unqualified',
  'lost_no_response',
  'lost_other',
  'cancelled',
]);

function eventIcon(event: TimelineEvent) {
  const type = event.metadata?.type as string | undefined;

  if (type === 'outcome_set') {
    const outcome = (event.metadata as Record<string, unknown>).outcome as string | undefined;
    if (outcome === 'won') return <Trophy className="h-4 w-4 text-emerald-600" aria-hidden />;
    if (outcome && LOST_OUTCOMES.has(outcome))
      return <XCircle className="h-4 w-4 text-rose-600" aria-hidden />;
    return <XCircle className="h-4 w-4 text-rose-600" aria-hidden />;
  }
  if (type === 'outcome_cleared')
    return <RefreshCcw className="h-4 w-4 text-blue-500" aria-hidden />;
  if (event.type === 'document_event')
    return <FileText className="h-4 w-4 text-sky-600" aria-hidden />;
  if (event.action === 'create')
    return <PlusCircle className="h-4 w-4 text-green-500" aria-hidden />;
  if (event.action === 'archive')
    return <Archive className="h-4 w-4 text-orange-500" aria-hidden />;
  if (event.action === 'restore')
    return <RotateCcw className="h-4 w-4 text-blue-500" aria-hidden />;
  if (type === 'stage_change') return <Clock className="h-4 w-4 text-purple-500" aria-hidden />;
  return <Pencil className="h-4 w-4 text-muted-foreground" aria-hidden />;
}

function actorLabel(event: TimelineEvent): string | null {
  if (event.userName) return event.userName;
  if (!event.userId) return null;
  if (event.userId === 'system') return 'system';
  // Last-resort fallback when the user row was deleted: show a short token
  // instead of a 36-char UUID. The server-side join is authoritative; this
  // path should be rare in practice.
  return 'a teammate';
}

export function InterestTimeline({ interestId }: InterestTimelineProps) {
  const { data, isLoading } = useQuery<{ data: TimelineEvent[] }>({
    queryKey: ['interest-timeline', interestId],
    queryFn: () => apiFetch(`/api/v1/interests/${interestId}/timeline`),
  });

  if (isLoading) {
    return (
      <div className="space-y-3">
        {[...Array(5)].map((_, i) => (
          <div key={i} className="flex gap-3 animate-pulse">
            <div className="h-8 w-8 rounded-full bg-muted shrink-0" />
            <div className="flex-1 space-y-2">
              <div className="h-3 bg-muted rounded w-3/4" />
              <div className="h-2 bg-muted rounded w-1/2" />
            </div>
          </div>
        ))}
      </div>
    );
  }

  const events = data?.data ?? [];

  if (events.length === 0) {
    return (
      <div className="text-center py-12 text-muted-foreground">
        <p>No activity yet.</p>
      </div>
    );
  }

  return (
    <div className="relative space-y-0">
      {events.map((event, idx) => {
        const actor = actorLabel(event);
        const isAuto = event.userId === 'system';
        const isLast = idx === events.length - 1;
        return (
          <div key={event.id} className="relative flex gap-4 pb-6">
            {/* Vertical line - only between bubbles, never trailing past the last. */}
            {!isLast && (
              <span
                aria-hidden
                className="absolute left-4 top-8 bottom-0 -translate-x-1/2 w-px bg-border"
              />
            )}
            {/* Icon */}
            <div className="relative z-10 flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-background border">
              {eventIcon(event)}
            </div>

            <div className="flex-1 pt-1">
              <p className="text-sm">
                {event.description}
                {isAuto ? (
                  <span className="ml-2 inline-flex items-center gap-1 rounded-full bg-muted px-1.5 py-0.5 align-middle text-xs font-medium uppercase tracking-wide text-muted-foreground">
                    <Bot className="h-3 w-3" aria-hidden />
                    Auto
                  </span>
                ) : null}
              </p>
              <p className="mt-0.5 text-xs text-muted-foreground">
                <time dateTime={event.createdAt} title={format(new Date(event.createdAt), 'PPpp')}>
                  {formatDistanceToNowStrict(new Date(event.createdAt), { addSuffix: true })}
                </time>
                {actor ? <span> · by {actor}</span> : null}
              </p>
            </div>
          </div>
        );
      })}
    </div>
  );
}
