import { Linking, Text, View } from 'react-native';

import { Button } from '~/components/ui/button';
import { Card } from '~/components/ui/card';
import { EmptyState } from '~/components/ui/empty-state';
import { formatDateTime, truncate } from '~/utils/format';

type Commit = {
  _id: string;
  authorLogin?: string;
  authorName?: string;
  committedAt?: number;
  htmlUrl?: string;
  message: string;
};

export const SpoonCommitList = ({
  commits,
  emptyDescription,
  emptyTitle,
  intro,
  showOpenButton = false,
}: {
  commits: Commit[];
  emptyDescription: string;
  emptyTitle: string;
  intro?: string;
  showOpenButton?: boolean;
}) => (
  <View className='gap-3'>
    {intro ? (
      <Text className='text-muted-foreground text-sm'>{intro}</Text>
    ) : null}
    {commits.length ? (
      commits.map((commit) => (
        <Card key={commit._id}>
          <Text className='text-foreground font-medium'>
            {truncate(commit.message, 100)}
          </Text>
          <Text className='text-muted-foreground mt-2 text-xs'>
            {commit.authorLogin ?? commit.authorName ?? 'unknown'} ·{' '}
            {formatDateTime(commit.committedAt)}
          </Text>
          {showOpenButton && commit.htmlUrl ? (
            <Button
              variant='ghost'
              onPress={() => void Linking.openURL(commit.htmlUrl ?? '')}
            >
              Open commit
            </Button>
          ) : null}
        </Card>
      ))
    ) : (
      <EmptyState description={emptyDescription} title={emptyTitle} />
    )}
  </View>
);
