import { Box, Tabs, TabList, TabPanels, Tab, TabPanel, Table, Thead, Tbody, Tr, Th, Td, Text, Badge, Heading, Flex, Tooltip } from '@chakra-ui/react';
import { useQuery } from '@tanstack/react-query';
import { facrApi } from '../../services/facr/facrApi';
import { usePublicSettings } from '../../hooks/usePublicSettings';
import { useClubTheme } from '../../contexts/ClubThemeContext';
import { useState } from 'react';
import ClubModal from './ClubModal';
import { TeamLogo } from '../common/TeamLogo';

const LeagueTablePro: 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-table', clubId, clubType],
    queryFn: () => facrApi.getClubTable(clubId!, clubType as any),
    enabled: !!clubId,
  });

  const [selectedClub, setSelectedClub] = useState<any>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);

  const handleClubClick = (row: any) => {
    // Transform row data to match ClubModal interface
    const clubData = {
      team: row.team || row.team_name || '-',
      team_id: row.team_id || '',
      team_logo_url: row.team_logo_url,
      rank: row.rank,
      played: row.played,
      wins: row.wins,
      draws: row.draws,
      losses: row.losses,
      score: row.score,
      points: row.points,
    };
    setSelectedClub(clubData);
    setIsModalOpen(true);
  };

  if (!data) return null;

  return (
    <Box borderRadius="lg" overflow="hidden" bg="white" boxShadow="sm" borderWidth="1px" borderColor="gray.100">
      <Box bg="primary.600" px={4} py={2} borderBottomWidth="1px" borderColor="primary.700">
        <Heading size="md" color="white">Tabulka</Heading>
      </Box>
      
      <Tabs variant="enclosed" colorScheme="gray" size="sm">
        <TabList px={2} pt={2} overflowX="auto" overflowY="hidden" css={{
          '&::-webkit-scrollbar': { height: '4px' },
          '&::-webkit-scrollbar-track': { background: 'transparent' },
          '&::-webkit-scrollbar-thumb': { background: 'gray.300', borderRadius: '4px' },
        }}>
          {data.competitions?.map((c) => (
            <Tab 
              key={c.id} 
              _selected={{ 
                color: 'primary.600', 
                borderBottom: '2px solid',
                borderColor: 'primary.600',
                fontWeight: 'bold'
              }}
              _focus={{ boxShadow: 'none' }}
              fontSize="sm"
              px={3}
              py={3}
            >
              {c.name}
            </Tab>
          ))}
        </TabList>
        <TabPanels>
          {data.competitions?.map((c) => (
            <TabPanel key={c.id} px={0}>
              <Box maxH="420px" overflowY="auto">
                <Table size="sm" variant="simple">
                  <Thead position="sticky" top={0} zIndex={1} bg="gray.50">
                    <Tr borderBottomWidth="1px" borderColor="gray.200">
                      <Th width="8" px={2} textAlign="center" color="gray.600" fontWeight="bold" fontSize="xs" textTransform="uppercase">#</Th>
                      <Th px={3} color="gray.600" fontWeight="bold" fontSize="xs" textTransform="uppercase">Tým</Th>
                      <Th width="8" px={1} textAlign="center" color="gray.600" fontWeight="bold" fontSize="xs" textTransform="uppercase">Z</Th>
                      <Th width="8" px={1} textAlign="center" color="gray.600" fontWeight="bold" fontSize="xs" textTransform="uppercase">V</Th>
                      <Th width="8" px={1} textAlign="center" color="gray.600" fontWeight="bold" fontSize="xs" textTransform="uppercase">R</Th>
                      <Th width="8" px={1} textAlign="center" color="gray.600" fontWeight="bold" fontSize="xs" textTransform="uppercase">P</Th>
                      <Th width="16" px={1} textAlign="center" color="gray.600" fontWeight="bold" fontSize="xs" textTransform="uppercase">Skóre</Th>
                      <Th width="14" px={1} textAlign="center" color="gray.600" fontWeight="bold" fontSize="xs" textTransform="uppercase">Body</Th>
                    </Tr>
                  </Thead>
                  <Tbody>
                    {c.table?.overall?.map((row, idx) => {
                      const isHighlighted = row.team_id === clubId;
                      return (
                        <Tr 
                          key={`${row.team_id}-${idx}`} 
                          bg={isHighlighted ? 'primary.50' : idx % 2 === 0 ? 'white' : 'gray.50'}
                          borderLeft={isHighlighted ? '3px solid' : '3px solid transparent'}
                          borderLeftColor={isHighlighted ? 'primary.500' : 'transparent'}
                          _hover={{ bg: isHighlighted ? 'primary.100' : 'gray.100', cursor: 'pointer' }}
                          onClick={() => handleClubClick(row)}
                        >
                          <Td px={2} textAlign="center" color={isHighlighted ? 'primary.700' : 'gray.700'} fontWeight={isHighlighted ? 'bold' : 'normal'}>
                            <Flex align="center" justify="center">
                              {row.rank}
                              {idx < 3 && (
                                <Box as="span" ml={1} color={idx === 0 ? 'yellow.400' : idx === 1 ? 'gray.400' : 'yellow.700'}>
                                  {idx === 0 ? '🥇' : idx === 1 ? '🥈' : '🥉'}
                                </Box>
                              )}
                            </Flex>
                          </Td>
                          <Td px={3} py={2}>
                            <Flex align="center" minW="180px">
                              <TeamLogo
                                teamId={row.team_id}
                                teamName={row.team}
                                facrLogo={row.team_logo_url}
                                size="small"
                                alt={row.team}
                                mr={2}
                                fallbackIcon={
                                  <Box 
                                    w="20px" 
                                    h="20px" 
                                    bg="gray.200" 
                                    borderRadius="md" 
                                    display="flex" 
                                    alignItems="center" 
                                    justifyContent="center"
                                    color="gray.400"
                                    fontSize="xs"
                                    fontWeight="bold"
                                  >
                                    {row.team.substring(0, 2).toUpperCase()}
                                  </Box>
                                }
                              />
                              <Text 
                                as="span" 
                                fontWeight={isHighlighted ? 'bold' : 'normal'}
                                color={isHighlighted ? 'primary.700' : 'gray.800'}
                                isTruncated
                              >
                                {row.team}
                              </Text>
                            </Flex>
                          </Td>
                          <Td isNumeric px={1} textAlign="center" color={isHighlighted ? 'primary.700' : 'gray.700'} fontWeight={isHighlighted ? 'bold' : 'normal'}>
                            {row.played}
                          </Td>
                          <Td isNumeric px={1} textAlign="center" color={isHighlighted ? 'primary.700' : 'gray.700'} fontWeight={isHighlighted ? 'bold' : 'normal'}>
                            {row.wins}
                          </Td>
                          <Td isNumeric px={1} textAlign="center" color={isHighlighted ? 'primary.700' : 'gray.700'} fontWeight={isHighlighted ? 'bold' : 'normal'}>
                            {row.draws}
                          </Td>
                          <Td isNumeric px={1} textAlign="center" color={isHighlighted ? 'primary.700' : 'gray.700'} fontWeight={isHighlighted ? 'bold' : 'normal'}>
                            {row.losses}
                          </Td>
                          <Td isNumeric px={1} textAlign="center" fontFamily="mono" color={isHighlighted ? 'primary.700' : 'gray.700'} fontWeight={isHighlighted ? 'bold' : 'normal'}>
                            {row.score}
                          </Td>
                          <Td 
                            isNumeric 
                            px={1} 
                            textAlign="center"
                            fontWeight="bold"
                            color={isHighlighted ? 'white' : 'gray.800'}
                            bg={isHighlighted ? 'primary.500' : 'gray.100'}
                            borderLeftWidth="1px"
                            borderLeftColor="white"
                          >
                            {row.points}
                          </Td>
                        </Tr>
                      );
                    })}
                  </Tbody>
                </Table>
              </Box>
              
              {/* League Info Footer */}
              <Box px={4} py={3} borderTopWidth="1px" borderColor="gray.100" bg="gray.50">
                <Flex justify="space-between" fontSize="xs" color="gray.600">
                  <Box>
                    <Text as="span" mr={4} display="inline-flex" alignItems="center">
                      <Box as="span" display="inline-block" w="8px" h="8px" bg="green.500" borderRadius="full" mr={1} />
                      Postup
                    </Text>
                    <Text as="span" mr={4} display="inline-flex" alignItems="center">
                      <Box as="span" display="inline-block" w="8px" h="8px" bg="blue.500" borderRadius="full" mr={1} />
                      Evropské poháry
                    </Text>
                    <Text as="span" display="inline-flex" alignItems="center">
                      <Box as="span" display="inline-block" w="8px" h="8px" bg="red.500" borderRadius="full" mr={1} />
                      Sestup
                    </Text>
                  </Box>
                  <Box>
                    <Text as="span" display="inline-flex" alignItems="center">
                      <Box as="span" fontWeight="bold" mr={1}>Aktualizováno:</Box>
                      {new Date().toLocaleDateString('cs-CZ', { 
                        day: '2-digit',
                        month: 'long',
                        year: 'numeric'
                      })}
                    </Text>
                  </Box>
                </Flex>
              </Box>
            </TabPanel>
          ))}
        </TabPanels>
      </Tabs>

      <ClubModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        club={selectedClub}
        clubType={clubType as 'football' | 'futsal'}
      />
    </Box>
  );
};

export default LeagueTablePro;
