import { Box, Heading, Tabs, TabList, TabPanels, Tab, TabPanel, VStack, HStack, Image, Text, Link, Skeleton, Badge } 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 { TeamLogo } from '../common/TeamLogo';
import '../../styles/logos.css';

const MatchRow: React.FC<{
  date: string;
  home: { name: string; logo?: string; id?: string };
  away: { name: string; logo?: string; id?: string };
  score?: string;
  clubName?: string;
  clubId?: string;
}> = ({ date, home, away, score, clubName, clubId }) => (
  <HStack justify="space-between" borderWidth="1px" borderRadius="md" p={3} bg="white">
    <Text w="140px" fontSize="sm" color="gray.600">{date}</Text>
    <HStack flex={1} justify="flex-end">
      <HStack minW="40%" justify="flex-end" spacing={2}>
        <Text noOfLines={1} textAlign="right" flex={1} fontSize="sm" lineHeight="1.2em" height="1.2em" overflow="hidden">{home.name}</Text>
        <Box className="logo-container" w="28px" h="28px">
          <TeamLogo
            teamId={home.id}
            teamName={home.name}
            facrLogo={home.logo}
            size="custom"
            boxSize="28px"
          />
        </Box>
      </HStack>
      <HStack w="auto" minW="60px" justify="center" spacing={2}>
        <Text fontWeight="bold" textAlign="center">{score || '-:-'}</Text>
        {(() => {
          const sent = (() => {
            if (!score) return null;
            const m = score.match(/^(\d+)\s*[:\-]\s*(\d+)$/);
            if (!m) return null;
            const h = parseInt(m[1], 10), a = parseInt(m[2], 10);
            
            // First try ID-based matching (most reliable)
            let ourIsHome = false;
            let ourIsAway = false;
            if (clubId && home.id && away.id) {
              ourIsHome = home.id === clubId;
              ourIsAway = away.id === clubId;
            }
            
            // Fallback to name matching if IDs not available or no match
            if (!ourIsHome && !ourIsAway && clubName) {
              const norm = (s: string) => String(s||'').normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/\s+/g,' ').trim().toLowerCase();
              const strip = (s: string) => norm(s).replace(/\b(mestsky|m\.?f\.?k\.?|mfk|tj|sk|sokol|fotbalovy|fotbalový|fotbalovy\s+klub|fotbalovy\s+klub)\b/g,'').replace(/\s+/g,' ').trim();
              const aName = strip(home.name); 
              const bName = strip(clubName);
              ourIsHome = Boolean(aName && bName && (aName===bName || aName.endsWith(bName) || bName.endsWith(aName)));
              const cName = strip(away.name);
              ourIsAway = Boolean(cName && bName && (cName===bName || cName.endsWith(bName) || bName.endsWith(cName)));
            }
            
            if (!ourIsHome && !ourIsAway) return null;
            if (h === a) return { label: 'Remíza', color: 'blue' } as const;
            const our = ourIsHome ? h : a; const opp = ourIsHome ? a : h;
            return our > opp ? ({ label: 'Výhra', color: 'green' } as const) : ({ label: 'Prohra', color: 'red' } as const);
          })();
          return sent ? <Badge colorScheme={sent.color} variant="subtle">{sent.label}</Badge> : null;
        })()}
      </HStack>
      <HStack minW="40%" spacing={2}>
        <Box className="logo-container" w="28px" h="28px">
          <TeamLogo
            teamId={away.id}
            teamName={away.name}
            facrLogo={away.logo}
            size="custom"
            boxSize="28px"
          />
        </Box>
        <Text noOfLines={1} flex={1} fontSize="sm" lineHeight="1.2em" height="1.2em" overflow="hidden">{away.name}</Text>
      </HStack>
    </HStack>
  </HStack>
);

const MatchesSection: React.FC = () => {
  const { data: settings } = usePublicSettings();
  const clubId = settings?.club_id || FACR_CLUB_ID;
  const clubType = settings?.club_type || FACR_CLUB_TYPE;
  const { data, isLoading, isError } = useQuery({
    queryKey: ['facr-club', clubId, clubType],
    queryFn: () => facrApi.getClub(clubId, clubType),
    enabled: Boolean(clubId),
  });

  return (
    <Box>
      <Heading size="lg" mb={4}>Zápasy</Heading>
      {!clubId && (
        <Text color="orange.500" mb={4}>Nastavte klub v Nastavení (Admin) nebo REACT_APP_FACR_CLUB_ID pro načtení zápasů z FAČR.</Text>
      )}
      {isLoading && <Skeleton height="200px" />}
      {!isLoading && data && (
        <Tabs variant="enclosed-colored" isFitted>
          <TabList>
            {data.competitions?.map((c) => (
              <Tab key={c.id}>{c.name}</Tab>
            ))}
          </TabList>
          <TabPanels>
            {data.competitions?.map((c) => (
              <TabPanel key={c.id} px={0}>
                <VStack align="stretch" spacing={3}>
                  {(c.matches || []).slice(0, 5).map((m, idx) => (
                    <MatchRow
                      key={m.match_id || idx}
                      date={m.date_time}
                      home={{ name: m.home, logo: m.home_logo_url, id: m.home_id }}
                      away={{ name: m.away, logo: m.away_logo_url, id: m.away_id }}
                      score={m.score}
                      clubName={data.name}
                      clubId={data.club_internal_id}
                    />
                  ))}
                  {(c.matches || []).length === 0 && (
                    <Text color="gray.500">Žádné zápasy k dispozici.</Text>
                  )}
                </VStack>
              </TabPanel>
            ))}
          </TabPanels>
        </Tabs>
      )}
    </Box>
  );
};

export default MatchesSection;
