import { Box, Text, VStack, HStack, Avatar, Skeleton, Icon, Alert, AlertIcon } from '@chakra-ui/react';
import { FaUsers, FaFutbol } from 'react-icons/fa';
import { useQuery } from '@tanstack/react-query';
import { Widget } from './Widget';
import { getFacrTablesCache } from '../../services/facr/cache';
import { getPublicSettings, PublicSettings } from '../../services/settings';

export const TeamsWidget = () => {
  // Load settings for primary club name (for exclusion)
  const { data: settings, isLoading: settingsLoading } = useQuery<PublicSettings>({
    queryKey: ['public-settings'],
    queryFn: getPublicSettings as any,
    staleTime: 5 * 60 * 1000,
  });

  // Load FACR tables cache
  const { data: facrTables, isLoading, error } = useQuery<any>({
    queryKey: ['facr-tables-cache'],
    queryFn: getFacrTablesCache,
    staleTime: 5 * 60 * 1000,
  });

  const normalize = (s?: string) => {
    let out = String(s || '');
    // Normalize diacritics and case
    out = out
      .normalize('NFD')
      .replace(/[\u0300-\u036f]/g, '')
      .toLowerCase();
    // Unify various dash characters to a simple hyphen
    out = out.replace(/[\u2012\u2013\u2014\u2015\u2212]/g, '-');
    // Remove legal suffixes like ", z.s." / ", z. s." / " z.s." / "o.s." at end
    out = out.replace(/[,\s]*(z\.?\s*s\.?|o\.?\s*s\.?)\s*$/g, '');
    // Remove organization phrases/prefixes anywhere (keep core locality/name)
    const orgPhrases = [
      'fotbalovy klub',
      'sportovni klub',
      'telovychovna jednota',
      'skolni sportovni klub',
      'fotbal',
      'futsal',
    ];
    for (const phrase of orgPhrases) {
      const re = new RegExp(`(^|\\b)${phrase}(\\b|$)`, 'g');
      out = out.replace(re, ' ');
    }
    // Remove common short prefixes (tokens) like FC, FK, MFK, TJ, SK, SFC, AFK at word boundaries
    out = out.replace(/\b(1\.)?\s*(sfc|afc|fc|fk|mfk|tj|sk|afk)\b\.?/g, ' ');
    // Remove punctuation except hyphen
    out = out.replace(/[\.,!;:()\[\]{}]/g, ' ');
    // Collapse multiple spaces and trim
    out = out.replace(/\s+/g, ' ').trim();
    return out;
  };

  const primaryKey = normalize((settings as any)?.club_name);
  const teams = (() => {
    const map: Record<string, { id: string; name: string; logoUrl?: string }> = {};
    const comps = Array.isArray(facrTables?.competitions) ? facrTables.competitions : [];
    for (const c of comps) {
      const rows = Array.isArray(c?.table?.overall) ? c.table.overall : [];
      for (const r of rows) {
        const name = (r?.team || '').trim();
        if (!name) continue;
        const key = normalize(name);
        if (key && key === primaryKey) continue; // exclude primary club from listing
        if (!map[key]) {
          map[key] = { id: key, name, logoUrl: r?.team_logo_url };
        }
      }
    }
    return Object.values(map).slice(0, 8); // show up to 8
  })();

  // If application settings are still loading, show skeletons
  if (settingsLoading || isLoading) {
    return (
      <Widget title="Týmy klubu" icon={FaUsers}>
        <VStack spacing={3} align="stretch">
          {[1, 2, 3].map((i) => (
            <HStack key={i} p={2} spacing={3}>
              <Skeleton boxSize="40px" borderRadius="md" />
              <Box flex={1}>
                <Skeleton height="16px" width="80%" mb={1} />
                <Skeleton height="12px" width="60%" />
              </Box>
            </HStack>
          ))}
        </VStack>
      </Widget>
    );
  }

  if (error) {
    return (
      <Widget title="Týmy klubu" icon={FaUsers}>
        <Alert status="info" variant="left-accent">
          <AlertIcon />
          Nepodařilo se načíst seznam týmů z cache.
        </Alert>
      </Widget>
    );
  }

  if (teams.length === 0) {
    return (
      <Widget title="Týmy klubu" icon={FaUsers}>
        <VStack p={4} spacing={4}>
          <Box p={4} bg="gray.50" borderRadius="md" textAlign="center" w="full">
            <Icon as={FaFutbol} boxSize={6} color="gray.400" mb={2} />
            <Text color="gray.500">Žádné týmy nebyly nalezeny</Text>
          </Box>
        </VStack>
      </Widget>
    );
  }

  return (
    <Widget title="Týmy klubu" icon={FaUsers}>
      <VStack spacing={3} align="stretch" divider={<Box borderBottomWidth="1px" borderColor="gray.100" />}>
        {teams.map((team) => (
          <Box
            key={team.id}
            p={3}
            _hover={{ bg: 'gray.50', cursor: 'pointer' }}
            borderRadius="md"
          >
            <HStack spacing={3}>
              <Avatar
                name={team.name}
                src={team.logoUrl}
                size="sm"
                bg="blue.100"
                color="blue.700"
                icon={<FaFutbol />}
              />
              <Box flex={1} minW={0}>
                <Text fontWeight="medium" isTruncated>{team.name}</Text>
              </Box>
            </HStack>
          </Box>
        ))}
      </VStack>
    </Widget>
  );
};
