import { Card } from '@/ui/Card';
import { Button } from '@/ui/Button';
import { Box } from '@/ui/Box';
import { Stack } from '@/ui/Stack';
import { Text } from '@/ui/Text';
import { Heading } from '@/ui/Heading';

type UpcomingRace = {
  id: string;
  track: string;
  car: string;
  scheduledAt: string | Date;
};

interface UpcomingRacesSidebarProps {
  races: UpcomingRace[];
}

export function UpcomingRacesSidebar({ races }: UpcomingRacesSidebarProps) {
  if (!races.length) {
    return null;
  }

  return (
    <Card className="bg-iron-gray/80">
      <Stack direction="row" align="baseline" justify="between" mb={3}>
        <Heading level={3}>Upcoming races</Heading>
        <Button
          as="a"
          href="/races"
          variant="secondary"
          size="sm"
        >
          View all
        </Button>
      </Stack>
      <Stack gap={3}>
        {races.slice(0, 4).map((race) => {
          const scheduledAt = typeof race.scheduledAt === 'string' ? new Date(race.scheduledAt) : race.scheduledAt;

          return (
            <Box key={race.id} display="flex" justify="between" gap={3}>
              <Box flex={1} className="min-w-0">
                <Text size="xs" color="text-white" block className="truncate">{race.track}</Text>
                <Text size="xs" color="text-gray-400" block className="truncate">{race.car}</Text>
              </Box>
              <Box textAlign="right">
                <Text size="xs" color="text-gray-500" className="whitespace-nowrap">
                  {scheduledAt.toLocaleDateString(undefined, {
                    month: 'short',
                    day: 'numeric'
                  })}
                </Text>
              </Box>
            </Box>
          );
        })}
      </Stack>
    </Card>
  );
}
