import {
  Clock,
  GitCommit,
  GitPullRequest,
  MessagesSquare,
  TrendingUp,
} from 'lucide-react';

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

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

export const SpoonMetrics = ({
  spoon,
  state,
  latestThread,
}: {
  spoon: Doc<'spoons'>;
  state?: Doc<'spoonRepositoryStates'> | null;
  latestThread?: Doc<'threads'> | null;
}) => {
  const metrics = [
    {
      label: 'Upstream waiting',
      value: state?.upstreamAheadBy ?? spoon.upstreamAheadBy ?? 0,
      icon: TrendingUp,
    },
    {
      label: 'Fork-only commits',
      value: state?.forkAheadBy ?? spoon.forkAheadBy ?? 0,
      icon: GitCommit,
    },
    {
      label: 'Open PRs',
      value:
        (state?.openForkPullRequestCount ?? 0) +
        (state?.openUpstreamPullRequestCount ?? 0),
      icon: GitPullRequest,
    },
    {
      label: 'Latest thread',
      value: latestThread?.status.replaceAll('_', ' ') ?? 'none',
      icon: MessagesSquare,
    },
    {
      label: 'Last check',
      value: formatDate(spoon.lastCheckedAt ?? state?.refreshedAt),
      icon: Clock,
    },
  ];
  return (
    <div className='grid gap-3 md:grid-cols-2 xl:grid-cols-5'>
      {metrics.map((metric) => {
        const Icon = metric.icon;
        return (
          <Card key={metric.label} className='shadow-none'>
            <CardContent className='flex items-center justify-between gap-3 p-4'>
              <div className='min-w-0'>
                <p className='text-muted-foreground text-xs'>{metric.label}</p>
                <p className='mt-1 truncate text-lg font-semibold capitalize'>
                  {metric.value}
                </p>
              </div>
              <div className='bg-primary/10 text-primary flex size-8 shrink-0 items-center justify-center rounded-md'>
                <Icon className='size-4' />
              </div>
            </CardContent>
          </Card>
        );
      })}
    </div>
  );
};
