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';

type SpoonCardData = Doc<'spoons'> & {
  rawUpstreamAheadBy?: number;
  effectiveUpstreamAheadBy?: number;
  ignoredUpstreamCount?: number;
};

export const SpoonCard = ({ spoon }: { spoon: SpoonCardData }) => (
  <Link href={`/spoons/${spoon._id}`} className='group/spoon-card block'>
    <Card className='group-hover/spoon-card:border-primary/50 group-hover/spoon-card:bg-muted/20 shadow-none transition-colors'>
      <CardHeader className='flex-row items-start justify-between gap-4'>
        <div>
          <CardTitle className='group-hover/spoon-card:text-primary text-lg transition-colors'>
            {spoon.name}
          </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'>Actionable upstream</p>
          <p className='font-medium'>
            {spoon.effectiveUpstreamAheadBy ?? spoon.upstreamAheadBy ?? 0}
          </p>
          {spoon.ignoredUpstreamCount ? (
            <p className='text-muted-foreground text-xs'>
              {spoon.ignoredUpstreamCount} ignored
            </p>
          ) : null}
        </div>
        <div>
          <p className='text-muted-foreground'>Fork-only commits</p>
          <p className='font-medium'>{spoon.forkAheadBy ?? 0}</p>
        </div>
      </CardContent>
    </Card>
  </Link>
);
