import Link from 'next/link';
import { SpoonStatusBadge } from '@/components/spoons/spoon-status-badge';

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

export const MaintenanceQueue = ({ spoons }: { spoons: Doc<'spoons'>[] }) => {
  const queued = spoons
    .filter((spoon) =>
      ['behind', 'diverged', 'conflict', 'error'].includes(
        spoon.syncStatus ?? '',
      ),
    )
    .sort((a, b) => (b.upstreamAheadBy ?? 0) - (a.upstreamAheadBy ?? 0));

  return (
    <div className='space-y-3'>
      {queued.length ? (
        queued.map((spoon) => (
          <Card key={spoon._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'>{spoon.name}</p>
                  <SpoonStatusBadge status={spoon.syncStatus} />
                </div>
                <p className='text-muted-foreground mt-1 text-sm'>
                  {spoon.upstreamOwner}/{spoon.upstreamRepo} →{' '}
                  {spoon.forkOwner ?? 'unknown'}/{spoon.forkRepo ?? 'unknown'}
                </p>
                <p className='text-muted-foreground mt-1 text-xs'>
                  {spoon.upstreamAheadBy ?? 0} upstream commit(s),{' '}
                  {spoon.forkAheadBy ?? 0} fork-only commit(s)
                </p>
              </div>
              <Button variant='outline' size='sm' asChild>
                <Link href={`/spoons/${spoon._id}`}>Open Spoon</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>
  );
};
