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

const shortSha = (sha: string) => sha.slice(0, 7);

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

export const SpoonCommitList = ({
  commits,
  empty,
}: {
  commits: Doc<'spoonCommits'>[];
  empty: string;
}) => (
  <div className='space-y-3'>
    {commits.length ? (
      commits.map((commit) => (
        <Card key={`${commit.side}-${commit.sha}`} className='shadow-none'>
          <CardContent className='flex flex-col gap-3 p-4 md:flex-row md:items-start md:justify-between'>
            <div className='min-w-0'>
              <p className='truncate text-sm font-medium'>
                {commit.message.split('\n')[0]}
              </p>
              <p className='text-muted-foreground mt-1 text-xs'>
                {shortSha(commit.sha)} by{' '}
                {commit.authorLogin ?? commit.authorName ?? 'unknown'} ·{' '}
                {formatDate(commit.committedAt)}
              </p>
            </div>
            {commit.htmlUrl ? (
              <Button variant='outline' size='sm' asChild>
                <a href={commit.htmlUrl} target='_blank' rel='noreferrer'>
                  Open
                </a>
              </Button>
            ) : null}
          </CardContent>
        </Card>
      ))
    ) : (
      <Card className='shadow-none'>
        <CardContent className='text-muted-foreground p-6 text-sm'>
          {empty}
        </CardContent>
      </Card>
    )}
  </div>
);
