import React from 'react';
import { Box, HStack, VStack, Text, Heading, Tabs, TabList, TabPanels, Tab, TabPanel, 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) {
  if (!dt) return '';
  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 UpcomingSwitch: React.FC = () => {
  const { data: settings } = usePublicSettings();
  const clubId = settings?.club_id;
  const clubType = (settings?.club_type || 'football') as any;
  const theme = useClubTheme();

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

  const comps = data?.competitions || [];

  if (!comps.length) return null;

  return (
    <Tabs variant="unstyled" colorScheme="whiteAlpha">
      <TabList gap={2} flexWrap={{ base: 'wrap', md: 'nowrap' }}>
        {comps.map((c) => (
          <Tab
            key={c.id}
            px={3}
            py={2}
            borderRadius="full"
            bg="whiteAlpha.200"
            color="white"
            _selected={{ bg: 'white', color: 'black' }}
          >
            {c.name}
          </Tab>
        ))}
      </TabList>
      <TabPanels>
        {comps.map((c) => {
          const upcoming = (c.matches || [])
            .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 (
              <TabPanel key={c.id} px={0}>
                <Box py={6} textAlign="center" color="whiteAlpha.800">Žádný nadcházející zápas.</Box>
              </TabPanel>
            );
          }

          return (
            <TabPanel key={c.id} px={0}>
              <HStack spacing={6} align="center" justify="space-between" flexWrap={{ base: 'wrap', md: 'nowrap' }}>
                <HStack spacing={4} flex={1} minW={0} justify="center">
                  <HStack minW={0}>
                    <Image src={upcoming.home_logo_url} alt={upcoming.home} boxSize={{ base: '32px', md: '44px' }} objectFit="contain" />
                    <Text fontWeight={700} color="white" noOfLines={1}>{upcoming.home}</Text>
                  </HStack>
                  <Heading size="sm" color="white">vs</Heading>
                  <HStack minW={0}>
                    <Image src={upcoming.away_logo_url} alt={upcoming.away} boxSize={{ base: '32px', md: '44px' }} objectFit="contain" />
                    <Text fontWeight={700} color="white" noOfLines={1}>{upcoming.away}</Text>
                  </HStack>
                </HStack>
                <HStack spacing={6}>
                  <Box textAlign="center" color="white">
                    <Text fontSize="xs" opacity={0.85}>KICKOFF</Text>
                    <Heading size="sm">{new Date(upcoming.date_time).toLocaleString()}</Heading>
                  </Box>
                  <Box textAlign="center" color="white">
                    <Text fontSize="xs" opacity={0.85}>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" bg={theme.primary} color="white" _hover={{ bg: theme.accent }}>
                    Detail zápasu
                  </Button>
                )}
              </HStack>
            </TabPanel>
          );
        })}
      </TabPanels>
    </Tabs>
  );
};

export default UpcomingSwitch;
