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,
  threads,
  jobs,
}: {
  syncRuns: Doc<'syncRuns'>[];
  threads: Doc<'threads'>[];
  jobs: Doc<'agentJobs'>[];
}) => {
  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,
    })),
    ...threads.map((item) => ({
      id: item._id,
      kind: item.source.replaceAll('_', ' '),
      status: item.status,
      summary: item.summary ?? item.title,
      time: item.createdAt,
    })),
    ...jobs.map((item) => ({
      id: item._id,
      kind: item.jobType?.replaceAll('_', ' ') ?? 'workspace job',
      status: item.status,
      summary: item.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, threads, and workspace jobs will build this timeline.
          </CardContent>
        </Card>
      )}
    </div>
  );
};
