import type { Doc } from '@spoon/backend/convex/_generated/dataModel.js';
import { Badge, Card, CardContent } from '@spoon/ui';

const formatDate = (value: number) =>
  new Intl.DateTimeFormat('en', {
    dateStyle: 'medium',
    timeStyle: 'short',
  }).format(value);

export const SpoonActivityTimeline = ({
  syncRuns,
  reviews,
  requests,
}: {
  syncRuns: Doc<'syncRuns'>[];
  reviews: Doc<'aiReviews'>[];
  requests: Doc<'agentRequests'>[];
}) => {
  const items = [
    ...syncRuns.map((item) => ({
      id: item._id,
      kind: item.kind.replaceAll('_', ' '),
      status: item.status,
      summary: item.summary ?? item.error ?? 'Sync run recorded.',
      time: item.createdAt,
    })),
    ...reviews.map((item) => ({
      id: item._id,
      kind: 'AI review',
      status: item.status,
      summary: item.outputSummary ?? item.inputSummary,
      time: item.createdAt,
    })),
    ...requests.map((item) => ({
      id: item._id,
      kind: 'Agent request',
      status: item.status,
      summary: item.prompt,
      time: item.createdAt,
    })),
  ].sort((a, b) => b.time - a.time);

  return (
    <div className='space-y-3'>
      {items.length ? (
        items.map((item) => (
          <Card key={item.id} className='shadow-none'>
            <CardContent className='p-4'>
              <div className='flex flex-wrap items-center gap-2'>
                <p className='font-medium'>{item.kind}</p>
                <Badge variant='outline'>{item.status}</Badge>
              </div>
              <p className='text-muted-foreground mt-1 text-sm'>
                {item.summary}
              </p>
              <p className='text-muted-foreground mt-2 text-xs'>
                {formatDate(item.time)}
              </p>
            </CardContent>
          </Card>
        ))
      ) : (
        <Card className='shadow-none'>
          <CardContent className='text-muted-foreground p-6 text-sm'>
            Refreshes, AI reviews, and queued requests will build this timeline.
          </CardContent>
        </Card>
      )}
    </div>
  );
};
