import React, { useEffect, useState } from 'react';
import { Box, Heading, Tabs, TabList, TabPanels, Tab, TabPanel, Table, Thead, Tbody, Tr, Th, Td, Skeleton, Text, Badge, HStack, useColorModeValue } from '@chakra-ui/react';
import { useQuery } from '@tanstack/react-query';
import { facrApi } from '../../services/facr/facrApi';
import { FACR_CLUB_ID, FACR_CLUB_TYPE } from '../../config/facr';
import { usePublicSettings } from '../../hooks/usePublicSettings';
import ClubModal from './ClubModal';
import { TeamLogo } from '../common/TeamLogo';

const TableSection: React.FC = () => {
  const { data: settings } = usePublicSettings();
  const clubId = settings?.club_id || FACR_CLUB_ID;
  const clubType = settings?.club_type || FACR_CLUB_TYPE;
  // movement map: compKey -> teamKey -> delta (prevRank - currentRank)
  const [movementMap, setMovementMap] = useState<Record<string, Record<string, number>>>({});
  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);
  };
  // Theme-aware movement colors (softer in dark mode)
  const upColor = useColorModeValue('green.400', 'green.300');
  const downColor = useColorModeValue('red.400', 'red.300');
  const sameColor = useColorModeValue('gray.300', 'gray.600');
  // Badge/background colors to avoid white-on-white
  const badgeBg = useColorModeValue('gray.100', 'gray.700');
  const badgeText = useColorModeValue('gray.800', 'whiteAlpha.900');
  const rankTopBg = useColorModeValue('green.100', 'green.600');
  const rankTopText = useColorModeValue('green.800', 'white');
  const pointsBg = useColorModeValue('blue.600', 'blue.400');
  const pointsText = 'white';
  const { data, isLoading, isError, error } = useQuery({
    queryKey: ['facr-table', clubId, clubType],
    queryFn: () => facrApi.getClubTable(clubId, clubType),
    enabled: Boolean(clubId),
    staleTime: 1000 * 60 * 3, // 3 minutes
    retry: 2,
    retryDelay: attempt => Math.min(1000 * 2 ** attempt, 8000),
  });

  // After data loads, compare with previous snapshot stored in localStorage to compute movement
  useEffect(() => {
    try {
      if (!data?.competitions?.length) return;
      const storageKey = `facr_table_prev_${clubId || 'unknown'}_${clubType || 'football'}`;
      const prevRaw = localStorage.getItem(storageKey);
      const prev = prevRaw ? JSON.parse(prevRaw) : null;
      const map: Record<string, Record<string, number>> = {};

      data.competitions.forEach((c: any) => {
        const compKey = String(c.id ?? c.code ?? c.name ?? 'comp');
        const prevComp = prev?.competitions?.find((pc: any) => String(pc.id ?? pc.code ?? pc.name) === compKey);
        const prevRanks: Record<string, number> = {};
        (prevComp?.table?.overall || []).forEach((r: any, i: number) => {
          const teamKey = String(r.team_id ?? r.team ?? r.team_name ?? i).toLowerCase();
          const rank = Number(r.rank ?? (i + 1));
          prevRanks[teamKey] = rank;
        });
        const compMov: Record<string, number> = {};
        (c.table?.overall || []).forEach((r: any, i: number) => {
          const teamKeyRaw = String(r.team_id ?? r.team ?? r.team_name ?? i);
          const teamKey = teamKeyRaw.toLowerCase();
          const currentRank = Number(r.rank ?? (i + 1));
          const prevRank = prevRanks[teamKey];
          if (typeof prevRank === 'number') {
            compMov[teamKeyRaw] = prevRank - currentRank; // positive => moved up
          }
        });
        map[compKey] = compMov;
      });

      setMovementMap(map);

      // Save current snapshot for next comparison (trim to essentials)
      const snapshot = {
        competitions: (data.competitions || []).map((c: any) => ({
          id: c.id,
          code: c.code,
          name: c.name,
          table: { overall: (c.table?.overall || []).map((r: any, i: number) => ({
            team_id: r.team_id,
            team: r.team,
            team_name: r.team_name,
            rank: Number(r.rank ?? (i + 1)),
          })) },
        })),
      };
      localStorage.setItem(storageKey, JSON.stringify(snapshot));
    } catch {}
  }, [data, clubId, clubType]);

  return (
    <Box>
      <Heading size="lg" mb={4}>Tabulka soutěží</Heading>
      {!clubId && (
        <Text color="orange.500" mb={4}>Nastavte klub v Nastavení (Admin) nebo REACT_APP_FACR_CLUB_ID pro načtení tabulek z FAČR.</Text>
      )}
      {isLoading && <Skeleton height="200px" />}
      {isError && (
        <Text color="red.500" mb={4}>
          Nepodařilo se načíst tabulky z FAČR. Zkuste to prosím znovu později.
          {process.env.NODE_ENV !== 'production' && error instanceof Error ? ` (${error.message})` : ''}
        </Text>
      )}
      {/* Legend for movement */}
      {!isLoading && !isError && (
        <HStack spacing={4} mb={2} color="gray.600" fontSize="sm">
          <HStack spacing={2}>
            <Box w="10px" h="10px" borderRadius="2px" bg={upColor} />
            <Text>Lepší pozice</Text>
          </HStack>
          <HStack spacing={2}>
            <Box w="10px" h="10px" borderRadius="2px" bg={sameColor} />
            <Text>Beze změny</Text>
          </HStack>
          <HStack spacing={2}>
            <Box w="10px" h="10px" borderRadius="2px" bg={downColor} />
            <Text>Horší pozice</Text>
          </HStack>
        </HStack>
      )}
      {!isLoading && !isError && data && data.competitions?.length > 0 && (
        <Tabs variant="enclosed" colorScheme="blue" isFitted>
          <TabList bg={useColorModeValue('white', 'gray.800')} borderRadius="md" borderWidth="1px" borderColor={useColorModeValue('gray.200', 'gray.700')}>
            {data.competitions?.map((c) => (
              <Tab
                key={c.id}
                _selected={{ bg: useColorModeValue('blue.50', 'blue.900'), color: useColorModeValue('blue.700', 'blue.200'), borderColor: useColorModeValue('blue.200', 'blue.600') }}
                color={useColorModeValue('gray.800', 'gray.200')}
              >
                {c.name}
              </Tab>
            ))}
          </TabList>
          <TabPanels>
            {data.competitions?.map((c) => (
              <TabPanel key={c.id} px={0}>
                <Box maxH="420px" overflowY="auto" borderWidth="1px" borderRadius="md" bg={useColorModeValue('white', 'gray.800')} color={useColorModeValue('gray.800', 'gray.100')} borderColor={useColorModeValue('gray.200', 'gray.700')}>
                  <Table size="sm" variant="striped" colorScheme="gray">
                    <Thead position="sticky" top={0} zIndex={1} bg="brand.primary">
                      <Tr>
                        <Th color="text.onPrimary">#</Th>
                        <Th color="text.onPrimary">Tým</Th>
                        <Th isNumeric color="text.onPrimary">Z</Th>
                        <Th isNumeric color="text.onPrimary">V</Th>
                        <Th isNumeric color="text.onPrimary">R</Th>
                        <Th isNumeric color="text.onPrimary">P</Th>
                        <Th isNumeric color="text.onPrimary">Skóre</Th>
                        <Th isNumeric color="text.onPrimary">Body</Th>
                      </Tr>
                    </Thead>
                    <Tbody>
                      {c.table?.overall?.map((row, idx) => {
                        const compKey = String(c.id ?? c.code ?? c.name ?? 'comp');
                        const teamKeyRaw = String((row as any).team_id ?? (row as any).team ?? (row as any).team_name ?? idx);
                        const deltaStored = movementMap?.[compKey]?.[teamKeyRaw];
                        const movement: 'up' | 'same' | 'down' = typeof deltaStored === 'number' ? (deltaStored > 0 ? 'up' : (deltaStored < 0 ? 'down' : 'same')) : 'same';
                        const deltaVal = typeof deltaStored === 'number' ? deltaStored : 0;
                        const borderCol = movement === 'up' ? upColor : movement === 'down' ? downColor : sameColor;

                        const ourClubId = settings?.club_id;
                        const ourClubName = (settings?.club_name || '').toLowerCase();
                        const isOurClub = (ourClubId && row.team_id === ourClubId) || (!!ourClubName && String(row.team || '').toLowerCase() === ourClubName);

                        return (
                          <Tr
                            key={`${row.team_id}-${idx}`}
                            _hover={{ bg: useColorModeValue('gray.50', 'gray.700'), cursor: 'pointer' }}
                            bg={idx % 2 === 0 ? useColorModeValue('white', 'gray.800') : useColorModeValue('gray.50', 'gray.750')}
                            sx={{ borderLeftWidth: '4px', borderLeftStyle: 'solid', borderLeftColor: borderCol }}
                            onClick={() => handleClubClick(row)}
                          >
                          <Td>
                            <Badge
                              variant="subtle"
                              bg={idx <= 2 ? rankTopBg : badgeBg}
                              color={idx <= 2 ? rankTopText : badgeText}
                              borderWidth="1px"
                              borderColor={useColorModeValue('gray.200', 'whiteAlpha.300')}
                            >
                              {row.rank}
                            </Badge>
                          </Td>
                          <Td>
                            <HStack spacing={2} align="center">
                              <TeamLogo
                                teamId={row.team_id}
                                teamName={row.team}
                                facrLogo={row.team_logo_url}
                                size="small"
                                alt={row.team}
                                borderRadius="full"
                                bg="white"
                                borderWidth="1px"
                                borderColor={useColorModeValue('gray.200', 'whiteAlpha.300')}
                              />
                              <Text as="span" color={isOurClub ? 'brand.primary' : useColorModeValue('gray.800', 'gray.100')} fontWeight={isOurClub ? 'bold' : 'normal'}>
                                {row.team}
                              </Text>
                              <Text as="span" fontSize="xs" color={movement === 'up' ? 'green.500' : movement === 'down' ? 'red.500' : 'gray.500'}>
                                {movement === 'up' ? '▲' : movement === 'down' ? '▼' : '•'}
                              </Text>
                            </HStack>
                            {deltaVal !== 0 && (
                              <Badge
                                ml={2}
                                variant="subtle"
                                bg={movement === 'up' ? 'green.100' : movement === 'down' ? 'red.100' : badgeBg}
                                color={movement === 'up' ? 'green.700' : movement === 'down' ? 'red.700' : badgeText}
                                borderWidth="1px"
                                borderColor={useColorModeValue('green.200', movement === 'down' ? 'red.300' : 'whiteAlpha.300')}
                              >
                                {movement === 'up' ? `+${deltaVal}` : `${deltaVal}`}
                              </Badge>
                            )}
                          </Td>
                          <Td isNumeric>{row.played}</Td>
                          <Td isNumeric>{row.wins}</Td>
                          <Td isNumeric>{row.draws}</Td>
                          <Td isNumeric>{row.losses}</Td>
                          <Td isNumeric>{row.score}</Td>
                          <Td isNumeric>
                            <Badge variant="solid" bg={pointsBg} color={pointsText}>{row.points}</Badge>
                          </Td>
                          </Tr>
                        );
                      })}
                    </Tbody>
                  </Table>
                </Box>
              </TabPanel>
            ))}
          </TabPanels>
        </Tabs>
      )}
      {!isLoading && !isError && data && (!data.competitions || data.competitions.length === 0) && (
        <Text color="gray.500">Pro tento klub nejsou dostupné tabulky.</Text>
      )}

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

export default TableSection;

