import Link from 'next/link';

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

export const MaintenanceQueue = ({
  threads,
}: {
  threads: Doc<'threads'>[];
}) => {
  const queued = threads.filter(
    (thread) =>
      ['upstream_update', 'merge_conflict'].includes(thread.source) &&
      !['resolved', 'ignored', 'failed', 'cancelled'].includes(thread.status),
  );

  return (
    <div className='space-y-3'>
      {queued.length ? (
        queued.map((thread) => (
          <Card key={thread._id} className='shadow-none'>
            <CardContent className='grid gap-3 p-4 md:grid-cols-[1fr_auto] md:items-center'>
              <div>
                <div className='flex flex-wrap items-center gap-2'>
                  <p className='font-medium'>{thread.title}</p>
                  <Badge>{thread.status.replaceAll('_', ' ')}</Badge>
                  {thread.maintenanceOutcome ? (
                    <Badge variant='secondary'>
                      {thread.maintenanceOutcome.replaceAll('_', ' ')}
                    </Badge>
                  ) : null}
                </div>
                <p className='text-muted-foreground mt-1 text-sm'>
                  {thread.summary ?? 'Maintenance thread waiting for review.'}
                </p>
                <p className='text-muted-foreground mt-1 text-xs'>
                  {new Date(thread.updatedAt).toLocaleString()}
                </p>
              </div>
              <Button variant='outline' size='sm' asChild>
                <Link href={`/threads/${thread._id}`}>Open thread</Link>
              </Button>
            </CardContent>
          </Card>
        ))
      ) : (
        <Card className='shadow-none'>
          <CardContent className='text-muted-foreground p-6 text-sm'>
            No Spoons currently need review. Refresh GitHub state to populate
            this queue.
          </CardContent>
        </Card>
      )}
    </div>
  );
};
