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

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

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

export const SpoonCard = ({ spoon }: { spoon: Doc<'spoons'> }) => (
  <Card className='hover:border-primary/50 shadow-none transition-colors'>
    <CardHeader className='flex-row items-start justify-between gap-4'>
      <div>
        <CardTitle className='text-lg'>
          <Link href={`/spoons/${spoon._id}`} className='hover:underline'>
            {spoon.name}
          </Link>
        </CardTitle>
        <p className='text-muted-foreground mt-1 text-sm'>
          {spoon.upstreamOwner}/{spoon.upstreamRepo}
        </p>
      </div>
      <SpoonStatusBadge status={spoon.syncStatus ?? spoon.status} />
    </CardHeader>
    <CardContent className='grid gap-3 text-sm md:grid-cols-2'>
      <div>
        <p className='text-muted-foreground'>Provider</p>
        <p className='font-medium'>{spoon.provider}</p>
      </div>
      <div>
        <p className='text-muted-foreground'>Cadence</p>
        <p className='font-medium'>{spoon.syncCadence}</p>
      </div>
      <div>
        <p className='text-muted-foreground'>Fork</p>
        <p className='font-medium'>
          {spoon.forkOwner && spoon.forkRepo
            ? `${spoon.forkOwner}/${spoon.forkRepo}`
            : 'Not connected'}
        </p>
      </div>
      <div>
        <p className='text-muted-foreground'>Last checked</p>
        <p className='font-medium'>{formatDate(spoon.lastCheckedAt)}</p>
      </div>
      <div>
        <p className='text-muted-foreground'>Upstream waiting</p>
        <p className='font-medium'>{spoon.upstreamAheadBy ?? 0}</p>
      </div>
      <div>
        <p className='text-muted-foreground'>Fork-only commits</p>
        <p className='font-medium'>{spoon.forkAheadBy ?? 0}</p>
      </div>
    </CardContent>
  </Card>
);
