import { Box, Flex, Heading, Text, HStack, Image, Button } from '@chakra-ui/react';
import { useQuery } from '@tanstack/react-query';
import { usePublicSettings } from '../../hooks/usePublicSettings';
import { facrApi } from '../../services/facr/facrApi';
import { useClubTheme } from '../../contexts/ClubThemeContext';

function formatCountdown(dt: string) {
  const target = new Date(dt).getTime();
  const diff = target - Date.now();
  if (isNaN(target) || diff <= 0) return '';
  const d = Math.floor(diff / (1000 * 60 * 60 * 24));
  const h = Math.floor((diff / (1000 * 60 * 60)) % 24);
  const m = Math.floor((diff / (1000 * 60)) % 60);
  return `${String(d).padStart(2,'0')}d ${String(h).padStart(2,'0')}h ${String(m).padStart(2,'0')}m`;
}

const UpcomingBanner: React.FC = () => {
  const { data: settings } = usePublicSettings();
  const clubId = settings?.club_id;
  const clubType = settings?.club_type || 'football';
  const theme = useClubTheme();

  const { data } = useQuery({
    queryKey: ['facr-club', clubId, clubType],
    queryFn: () => facrApi.getClub(clubId!, clubType as any),
    enabled: !!clubId,
  });

  const allMatches = (data?.competitions || []).flatMap(c => c.matches || []);
  const upcoming = allMatches
    .map(m => ({ m, t: new Date(m.date_time).getTime() }))
    .filter(x => !isNaN(x.t) && x.t > Date.now())
    .sort((a, b) => a.t - b.t)[0]?.m;

  if (!upcoming) return null;

  return (
    <Box bg={theme.primary} color="white" borderRadius="xl" p={{ base: 4, md: 6 }} shadow="md">
      <Text fontSize="sm" opacity={0.9} fontWeight="600">Nadcházející zápas</Text>
      <Flex align="center" justify="space-between" gap={4} mt={2} direction={{ base: 'column', md: 'row' }}>
        <HStack spacing={4} flex={1} justify="center">
          <HStack>
            <Image src={upcoming.home_logo_url} alt={upcoming.home} boxSize={{ base: '36px', md: '48px' }} objectFit="contain" />
            <Text fontWeight="600">{upcoming.home}</Text>
          </HStack>
          <Heading size="md">vs</Heading>
          <HStack>
            <Image src={upcoming.away_logo_url} alt={upcoming.away} boxSize={{ base: '36px', md: '48px' }} objectFit="contain" />
            <Text fontWeight="600">{upcoming.away}</Text>
          </HStack>
        </HStack>
        <HStack spacing={6}>
          <Box textAlign="center">
            <Text fontSize="xs" opacity={0.8}>KICKOFF</Text>
            <Heading size="sm">{new Date(upcoming.date_time).toLocaleString()}</Heading>
          </Box>
          <Box textAlign="center">
            <Text fontSize="xs" opacity={0.8}>ZAČÍNÁ ZA</Text>
            <Heading size="sm">{formatCountdown(upcoming.date_time)}</Heading>
          </Box>
        </HStack>
        {upcoming.report_url && (
          <Button as="a" href={upcoming.report_url} target="_blank" colorScheme="red" variant="solid">Detail</Button>
        )}
      </Flex>
    </Box>
  );
};

export default UpcomingBanner;
