import { batchFetchLogosFromSportLogosAPI } from '../../utils/sportLogosAPI';
import { 
  Heading, 
  Text, 
  Box, 
  Spinner, 
  Alert, 
  AlertIcon, 
  Table, 
  Thead, 
  Tbody, 
  Tr, 
  Th, 
  Td, 
  VStack, 
  Button, 
  HStack, 
  Drawer, 
  DrawerOverlay, 
  DrawerContent, 
  DrawerHeader, 
  DrawerBody, 
  DrawerFooter, 
  FormControl, 
  FormLabel, 
  Input, 
  InputGroup, 
  InputRightElement, 
  List, 
  ListItem, 
  Badge, 
  useToast,
  SimpleGrid,
  useColorModeValue,
  ButtonGroup,
  Tag,
  TagLabel,
  Tooltip,
  Image,
  Tabs,
  TabList,
  Tab,
  TabPanels,
  TabPanel,
  Flex,
  Wrap
} from '@chakra-ui/react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import AdminLayout from '../../layouts/AdminLayout';
import { searchClubs, uploadImage, putTeamLogoOverride, fetchTeamLogoOverrides, fetchLogoAsBlob, uploadToLogaSportcreative } from '../../services/adminMatches';
import { getFacrTablesCache } from '../../services/facr/cache';
import { assetUrl } from '../../utils/url';
import { useEffect, useMemo, useRef, useState } from 'react';
import { TeamLogo } from '../../components/common/TeamLogo';

type TableRow = {
  rank?: string;
  team?: string;
  team_id?: string;
  team_logo_url?: string;
  played?: string;
  wins?: string;
  draws?: string;
  losses?: string;
  score?: string;
  points?: string;
};

const TeamsAdminPage = () => {
  const toast = useToast();
  const queryClient = useQueryClient();
  const { data, isLoading, error } = useQuery<any>({
    queryKey: ['facr-tables-cache'],
    queryFn: () => getFacrTablesCache(),
    staleTime: 5 * 60 * 1000,
  });

  const competitions: any[] = Array.isArray(data?.competitions) ? data!.competitions : [];
  // Backend origin (used to resolve relative URLs like /uploads/...)
  const apiUrl = process.env.REACT_APP_API_URL || 'http://localhost:8080/api/v1';
  const backendOrigin = new URL(apiUrl).origin;

  // Load public/admin overrides map to apply on cache-fed view
  const { data: overrides = {} } = useQuery({
    queryKey: ['teamLogoOverrides'],
    queryFn: fetchTeamLogoOverrides,
    staleTime: 5 * 60 * 1000,
  });
  
  // Fetch logos from logoapi.sportcreative.eu for all teams
  const [sportLogosMap, setSportLogosMap] = useState<Record<string, string>>({});
  const [sportLogosLoading, setSportLogosLoading] = useState(false);
  
  useEffect(() => {
    if (!competitions || competitions.length === 0) return;
    
    // Extract all unique team IDs from all competitions
    const teamIds = new Set<string>();
    for (const comp of competitions) {
      const rows: TableRow[] = comp?.table?.overall || [];
      for (const r of rows) {
        if (r.team_id) teamIds.add(r.team_id);
      }
    }
    
    if (teamIds.size === 0) return;
    
    // Fetch logos from logoapi.sportcreative.eu
    setSportLogosLoading(true);
    batchFetchLogosFromSportLogosAPI(Array.from(teamIds))
      .then((map) => setSportLogosMap(map))
      .catch((err) => console.error('Failed to fetch sport logos:', err))
      .finally(() => setSportLogosLoading(false));
  }, [competitions]);
  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 byName: Record<string, string> = (overrides as any)?.by_name || {};
  const byNameNormalized = useMemo(() => {
    const idx: Record<string, string> = {};
    for (const k of Object.keys(byName)) {
      idx[normalize(k)] = byName[k];
    }
    return idx;
  }, [byName]);
  const getLogo = (teamName?: string, teamId?: string, original?: string) => {
    if (!teamName) return assetUrl('/dist/img/logo-club-empty.svg') as string;
    
    // Priority 1: Try logoapi.sportcreative.eu if we have a team ID
    if (teamId && sportLogosMap[teamId]) {
      return sportLogosMap[teamId];
    }
    
    // Priority 2: Try exact match from local overrides
    let overrideUrl = byName[teamName];
    if (!overrideUrl) {
      // Fallback: diacritics-insensitive + case-insensitive + trimmed match
      const norm = normalize(teamName);
      overrideUrl = byNameNormalized[norm];
    }
    
    // Priority 3: Use override if found
    if (overrideUrl) {
      // Resolve against backend for relative assets
      if (typeof overrideUrl === 'string' && overrideUrl.startsWith('/')) {
        return assetUrl(overrideUrl) as string;
      }
      return overrideUrl;
    }
    
    // Priority 4: Use FACR original
    if (original) {
      return original;
    }
    
    // Final fallback: empty logo
    return '/dist/img/logo-club-empty.svg';
  };

  // View mode: 'table' per competition, or 'grid' of unique teams across competitions
  const [viewMode, setViewMode] = useState<'table' | 'grid'>('table');
  // Selected competition for quick switching (only applies in table mode)
  const [selectedCompIndex, setSelectedCompIndex] = useState<number>(0);
  // Text filter for club/team name
  const [filter, setFilter] = useState('');
  const [filterDebounced, setFilterDebounced] = useState('');
  useEffect(() => {
    const t = setTimeout(() => setFilterDebounced(filter), 250);
    return () => clearTimeout(t);
  }, [filter]);

  // Build a deduplicated list of teams across all competitions
  type TeamAggregate = {
    key: string; // normalized key
    name: string; // representative name
    logo: string;
    variants: string[]; // all raw names found
  };
  const allTeamsUnique: TeamAggregate[] = useMemo(() => {
    const map: Record<string, TeamAggregate> = {};
    for (const comp of competitions) {
      const rows: TableRow[] = comp?.table?.overall || [];
      for (const r of rows) {
        const teamName = (r.team || '').trim();
        if (!teamName) continue;
        const key = normalize(teamName);
        const logo = getLogo(teamName, r.team_id, r.team_logo_url);
        if (!map[key]) {
          map[key] = { key, name: teamName, logo, variants: [teamName] };
        } else {
          map[key].variants.push(teamName);
          // Update logo - prefer non-empty logos
          const currentIsEmpty = !map[key].logo || /logo-club-empty\.svg$/.test(String(map[key].logo));
          const newIsNotEmpty = logo && !/logo-club-empty\.svg$/.test(String(logo));
          if (currentIsEmpty && newIsNotEmpty) {
            map[key].logo = logo as string;
          }
        }
      }
    }
    // Sort by representative name
    return Object.values(map).sort((a, b) => a.name.localeCompare(b.name, 'cs', { sensitivity: 'base' }));
  }, [competitions, getLogo]);

  // Fast lookup from normalized name to variant list
  const variantsByKey = useMemo(() => {
    const m: Record<string, string[]> = {};
    for (const t of allTeamsUnique) {
      m[t.key] = Array.from(new Set(t.variants));
    }
    return m;
  }, [allTeamsUnique]);

  // Drawer state for editing a team's logo/name
  const [isOpen, setIsOpen] = useState(false);
  const [selected, setSelected] = useState<{ compId?: string; teamName: string; teamLogoUrl?: string; variantNames?: string[] } | null>(null);
  const [form, setForm] = useState({
    external_team_id: '',
    team_name: '',
    logo_url: '',
  });
  const fileRef = useRef<HTMLInputElement | null>(null);
  const [uploadedFile, setUploadedFile] = useState<File | null>(null);
  const [externalUploadStatus, setExternalUploadStatus] = useState<'idle' | 'uploading' | 'success' | 'error'>('idle');
  const [externalUploadError, setExternalUploadError] = useState<string | null>(null);

  // Club search
  const [query, setQuery] = useState('');
  const [debounced, setDebounced] = useState('');
  useEffect(() => {
    const t = setTimeout(() => setDebounced(query), 300);
    return () => clearTimeout(t);
  }, [query]);
  const { data: searchResults = [] } = useQuery({
    queryKey: ['club-search', debounced],
    queryFn: () => searchClubs(debounced),
    enabled: debounced.trim().length >= 2,
  });

  const onOpenEdit = (teamName: string, teamLogoUrl?: string, variantNames?: string[]) => {
    // If variants not explicitly provided (e.g., from table view), compute from normalized key
    let v = variantNames;
    if (!v || v.length === 0) {
      const key = normalize(teamName || '');
      v = variantsByKey[key] || [];
    }
    setSelected({ teamName, teamLogoUrl, variantNames: v });
    setForm({ external_team_id: '', team_name: teamName || '', logo_url: teamLogoUrl || '' });
    setQuery(teamName || '');
    setIsOpen(true);
  };

  const onSave = useMutation({
    mutationFn: async () => {
      if (!form.external_team_id) {
        throw new Error('Vyberte tým ze seznamu vyhledávání (chybí ID).');
      }
      let logoUrl = (form.logo_url || '').trim();
      const primaryName = (selected?.teamName || form.team_name || '').trim();
      // All variants to update (deduped), always include the primary name
      const names = Array.from(new Set([primaryName, ...((selected?.variantNames || []) as string[])]))
        .map((s) => s.trim())
        .filter(Boolean);
      
      // Save override for each variant name so editing one updates all duplicates
      await Promise.all(
        names.map((n) => putTeamLogoOverride(form.external_team_id, n, logoUrl))
      );

      // Also upload to logoapi.sportcreative.eu (non-blocking, best-effort)
      if (logoUrl) {
        setExternalUploadStatus('uploading');
        setExternalUploadError(null);
        
        try {
          let logoFileToUpload: File | Blob | null = uploadedFile;
          
          // If no file was uploaded but we have a logo URL, fetch it as blob
          if (!logoFileToUpload && logoUrl) {
            logoFileToUpload = await fetchLogoAsBlob(logoUrl);
          }

          if (logoFileToUpload) {
            // Upload to the logo service (loga.sportcreative.eu)
            const logaResult = await uploadToLogaSportcreative(
              form.external_team_id,
              logoFileToUpload,
              { 
                filename: `${form.external_team_id}.${logoFileToUpload instanceof File ? logoFileToUpload.name.split('.').pop() : 'png'}`,
                clubName: form.team_name || selected?.teamName || 'Neznámý klub'
              }
            );
            
            if (logaResult.success) {
              setExternalUploadStatus('success');
              // Use the URL from loga.sportcreative.eu
              if (logaResult.url) {
                logoUrl = logaResult.url;
              }
            } else {
              setExternalUploadStatus('error');
              setExternalUploadError(logaResult.error || 'Nepodařilo se nahrát logo');
            }
          } else {
            setExternalUploadStatus('error');
            setExternalUploadError('Could not fetch logo file');
          }
        } catch (error: any) {
          setExternalUploadStatus('error');
          setExternalUploadError(error?.message || 'Upload failed');
        }
      }
      
      return true;
    },
    onSuccess: () => {
      let description = 'Změna byla aplikována na všechny duplicitní varianty.';
      if (externalUploadStatus === 'success') {
        description += ' Logo bylo úspěšně nahráno.';
      } else if (externalUploadStatus === 'error') {
        description += ` ⚠️ ${externalUploadError || 'Nepodařilo se nahrát logo'}`;
      }
      
      toast({ 
        title: 'Uloženo', 
        description, 
        status: externalUploadStatus === 'error' ? 'warning' : 'success',
        duration: 6000,
        isClosable: true,
      });
      
      setIsOpen(false);
      setSelected(null);
      setUploadedFile(null);
      setExternalUploadStatus('idle');
      setExternalUploadError(null);
      queryClient.invalidateQueries({ queryKey: ['facr-tables-cache'] });
      queryClient.invalidateQueries({ queryKey: ['teamLogoOverrides'] });
    },
    onError: (e: any) => {
      toast({ title: 'Uložení selhalo', description: e?.message || 'Zkuste to znovu', status: 'error' });
    },
  });

  return (
    <AdminLayout requireAdmin={false}>
      <Box>
        <HStack justify="space-between" mb={4}>
          <Heading size="lg">Správa týmů</Heading>
        </HStack>
        <Text color="gray.500" mb={4} fontSize="sm">
          Přehled tabulek z FAČR. Kompaktní zobrazení s rychlým přepínáním soutěží.
        </Text>
        <Flex mb={4} gap={3} align="center" wrap="wrap">
          <ButtonGroup isAttached size="sm" variant="outline">
            <Button 
              colorScheme={viewMode === 'table' ? 'blue' : 'gray'}
              variant={viewMode === 'table' ? 'solid' : 'outline'}
              onClick={() => setViewMode('table')}
              size="sm"
            >
              Tabulky
            </Button>
            <Button 
              colorScheme={viewMode === 'grid' ? 'blue' : 'gray'}
              variant={viewMode === 'grid' ? 'solid' : 'outline'}
              onClick={() => setViewMode('grid')}
              size="sm"
            >
              Mřížka
            </Button>
          </ButtonGroup>
          <InputGroup maxW={{ base: '100%', md: '300px' }} size="sm">
            <Input placeholder="Filtrovat podle názvu týmu…" value={filter} onChange={(e) => setFilter(e.target.value)} />
            {filter && (
              <InputRightElement width="3rem">
                <Button size="xs" variant="ghost" onClick={() => setFilter('')}>Vymazat</Button>
              </InputRightElement>
            )}
          </InputGroup>
          {sportLogosLoading && (
            <Badge colorScheme="blue" fontSize="xs">
              <HStack spacing={1}>
                <Spinner size="xs" />
                <Text>Načítám loga z logoapi.sportcreative.eu...</Text>
              </HStack>
            </Badge>
          )}
          {!sportLogosLoading && Object.keys(sportLogosMap).length > 0 && (
            <Badge colorScheme="green" fontSize="xs">
              ✓ {Object.keys(sportLogosMap).length} log z logoapi.sportcreative.eu
            </Badge>
          )}
        </Flex>

      {isLoading && (
        <VStack align="start" spacing={3} mb={6}>
          <Spinner />
          <Text>Načítám tabulky…</Text>
        </VStack>
      )}

      {Boolean(error) && (
        <Alert status="error" variant="left-accent" mb={4}>
          <AlertIcon />
          Nepodařilo se načíst data z cache.
        </Alert>
      )}

      {!isLoading && !error && viewMode === 'table' && (
        <Box>
          <Tabs 
            index={selectedCompIndex} 
            onChange={setSelectedCompIndex}
            variant="soft-rounded"
            colorScheme="blue"
            size="sm"
          >
            <TabList mb={4} overflowX="auto" overflowY="hidden" flexWrap="nowrap" pb={2}>
              {competitions.map((comp, idx) => (
                <Tab 
                  key={comp.id} 
                  fontSize="xs"
                  px={3}
                  py={1.5}
                  minW="fit-content"
                  whiteSpace="nowrap"
                >
                  {comp.name}
                </Tab>
              ))}
            </TabList>
            <TabPanels>
              {competitions.map((comp) => {
                const rows: TableRow[] = comp?.table?.overall || [];
                const f = normalize(filterDebounced);
                const rowsFiltered = f ? rows.filter((r) => normalize(r.team || '').includes(f)) : rows;
                return (
                  <TabPanel key={comp.id} p={0}>
                    <Box
                      overflowX="auto"
                      borderWidth="1px"
                      borderRadius="md"
                      w="full"
                      sx={{
                        WebkitOverflowScrolling: 'touch',
                      }}
                    >
                      <Table size="sm" variant="simple">
                        <Thead bg={useColorModeValue('gray.50', 'gray.700')}>
                          <Tr>
                            <Th w="40px" fontSize="xs" py={2}>#</Th>
                            <Th fontSize="xs" py={2}>Tým</Th>
                            <Th isNumeric w="45px" fontSize="xs" py={2}>Z</Th>
                            <Th isNumeric w="45px" fontSize="xs" py={2}>V</Th>
                            <Th isNumeric w="45px" fontSize="xs" py={2}>R</Th>
                            <Th isNumeric w="45px" fontSize="xs" py={2}>P</Th>
                            <Th isNumeric w="70px" fontSize="xs" py={2}>Skóre</Th>
                            <Th isNumeric w="50px" fontSize="xs" py={2}>Body</Th>
                            <Th w="90px" fontSize="xs" py={2}>Akce</Th>
                          </Tr>
                        </Thead>
                        <Tbody>
                          {rowsFiltered.map((r, idx) => (
                            <Tr key={`${comp.id}-${idx}`} _hover={{ bg: useColorModeValue('gray.50', 'gray.700') }}>
                              <Td py={1.5} fontSize="xs">{r.rank}</Td>
                              <Td py={1.5}>
                                <HStack spacing={2} align="center">
                                  <TeamLogo
                                    teamId={(r as any).team_id}
                                    teamName={r.team}
                                    facrLogo={r.team_logo_url}
                                    size="small"
                                    alt={r.team}
                                    objectFit="contain"
                                  />
                                  <Text fontSize="xs" noOfLines={1}>{r.team}</Text>
                                </HStack>
                              </Td>
                              <Td isNumeric py={1.5} fontSize="xs">{r.played}</Td>
                              <Td isNumeric py={1.5} fontSize="xs">{r.wins}</Td>
                              <Td isNumeric py={1.5} fontSize="xs">{r.draws}</Td>
                              <Td isNumeric py={1.5} fontSize="xs">{r.losses}</Td>
                              <Td isNumeric py={1.5} fontSize="xs">{r.score}</Td>
                              <Td isNumeric py={1.5} fontSize="xs" fontWeight="bold">{r.points}</Td>
                              <Td py={1.5}>
                                <Button size="xs" fontSize="xs" onClick={() => onOpenEdit(r.team || '', r.team_logo_url)}>Upravit</Button>
                              </Td>
                            </Tr>
                          ))}
                          {rowsFiltered.length === 0 && (
                            <Tr>
                              <Td colSpan={9} py={4}>
                                <Text color="gray.500" fontSize="sm" textAlign="center">Žádný tým neodpovídá filtru.</Text>
                              </Td>
                            </Tr>
                          )}
                        </Tbody>
                      </Table>
                    </Box>
                  </TabPanel>
                );
              })}
            </TabPanels>
          </Tabs>
        </Box>
      )}

      {!isLoading && !error && viewMode === 'grid' && (
        <Box>
          {(() => {
            const f = normalize(filterDebounced);
            const source = f
              ? allTeamsUnique.filter((t) => normalize(t.name).includes(f) || (t.variants || []).some(v => normalize(v).includes(f)))
              : allTeamsUnique;
            return (
              <SimpleGrid columns={{ base: 2, sm: 3, md: 4, lg: 6 }} spacing={3}>
                {source.map((t) => (
                  <Box 
                    key={t.key} 
                    borderWidth="1px" 
                    borderRadius="md" 
                    p={2.5} 
                    _hover={{ boxShadow: 'md', borderColor: 'blue.300' }}
                    transition="all 0.2s"
                  >
                    <VStack align="stretch" spacing={2}>
                      <HStack justify="space-between" align="start">
                        <HStack spacing={2} flex={1} minW={0}>
                          <Image src={t.logo} alt={t.name} boxSize="24px" objectFit="contain" flexShrink={0} />
                          <Text fontSize="xs" noOfLines={2} fontWeight="medium">{t.name}</Text>
                        </HStack>
                        {t.variants.length > 1 && (
                          <Tooltip label={`Varianty: ${Array.from(new Set(t.variants)).join(', ')}`} hasArrow>
                            <Tag size="sm" colorScheme="purple" variant="subtle" fontSize="xs">
                              <TagLabel>{t.variants.length}</TagLabel>
                            </Tag>
                          </Tooltip>
                        )}
                      </HStack>
                      <Button size="xs" fontSize="xs" onClick={() => onOpenEdit(t.name, t.logo, t.variants)} w="full">Upravit</Button>
                    </VStack>
                  </Box>
                ))}
                {source.length === 0 && (
                  <Box gridColumn={{ base: 'span 2', sm: 'span 3', md: 'span 4', lg: 'span 6' }}>
                    <Text color="gray.500" fontSize="sm" textAlign="center" py={8}>Žádný tým neodpovídá filtru.</Text>
                  </Box>
                )}
              </SimpleGrid>
            );
          })()}
        </Box>
      )}

      <Drawer isOpen={isOpen} placement="right" onClose={() => { setIsOpen(false); setSelected(null); }} size="md">
        <DrawerOverlay />
        <DrawerContent>
          <DrawerHeader>Upravit logo týmu</DrawerHeader>
          <DrawerBody>
            <VStack align="stretch" spacing={4}>
              <FormControl>
                <FormLabel>Hledat tým (FAČR)</FormLabel>
                <InputGroup>
                  <Input value={query} onChange={(e) => { setQuery(e.target.value); }} placeholder="Zadejte název týmu" />
                  <InputRightElement width="8rem">
                    <Button size="xs" onClick={() => fileRef.current?.click()}>Nahrát logo</Button>
                  </InputRightElement>
                </InputGroup>
                {searchResults.length > 0 && (
                  <Box 
                    mt={4} 
                    bg={useColorModeValue('white', 'gray.800')}
                    borderWidth="1px" 
                    borderRadius="lg" 
                    overflowX="auto"
                    boxShadow="sm"
                    mb={6}
                  >
                    <List spacing={0}>
                      {searchResults.map((r: any) => (
                        <ListItem
                          key={r.id}
                          px={3}
                          py={2}
                          _hover={{ bg: 'gray.50', cursor: 'pointer' }}
                          onClick={() => {
                            setForm((f) => ({ ...f, external_team_id: r.id, team_name: r.name, logo_url: r.logo_url || f.logo_url }));
                            setQuery(r.name);
                          }}
                        >
                          <HStack justify="space-between" spacing={3}>
                            <HStack spacing={3} maxW="80%">
                              {r.logo_url ? (
                                <Image src={r.logo_url} alt={r.name} boxSize="20px" objectFit="contain" />
                              ) : (
                                <Badge colorScheme="gray">bez loga</Badge>
                              )}
                              <Text noOfLines={1}>{r.name}</Text>
                            </HStack>
                            {r.logo_url && <Badge colorScheme="green">logo</Badge>}
                          </HStack>
                        </ListItem>
                      ))}
                    </List>
                  </Box>
                )}
                <input ref={fileRef} type="file" accept="image/png,image/svg+xml,image/jpeg,application/pdf" style={{ display: 'none' }} onChange={async (e) => {
                  const file = e.target.files?.[0];
                  if (!file) return;
                  try {
                    const { url } = await uploadImage(file);
                    setForm((f) => ({ ...f, logo_url: url }));
                    setUploadedFile(file); // Store for later upload to external API
                    toast({ title: 'Logo nahráno', status: 'success' });
                  } catch (err: any) {
                    toast({ title: 'Nahrávání selhalo', description: err?.message || 'Zkuste to znovu', status: 'error' });
                  } finally {
                    if (fileRef.current) fileRef.current.value = '' as any;
                  }
                }} />
              </FormControl>

              <FormControl>
                <FormLabel>Název týmu</FormLabel>
                <Input value={form.team_name} onChange={(e) => setForm({ ...form, team_name: e.target.value })} />
              </FormControl>

              <FormControl>
                <FormLabel>Logo URL</FormLabel>
                <Input value={form.logo_url} onChange={(e) => setForm({ ...form, logo_url: e.target.value })} />
              </FormControl>
              {selected?.variantNames && selected.variantNames.length > 1 && (
                <Alert status="info">
                  <AlertIcon />
                  Upravíte také duplicitní názvy: {Array.from(new Set(selected.variantNames)).join(', ')}
                </Alert>
              )}
              {form.logo_url && (
                <Alert status="info" variant="left-accent">
                  <AlertIcon />
                  <VStack align="start" spacing={1}>
                    <Text fontSize="sm" fontWeight="medium">Logo bude automaticky nahráno na logoapi.sportcreative.eu</Text>
                    <Text fontSize="xs" color="gray.600">Toto poskytuje zálohu a sdílení log mezi aplikacemi.</Text>
                  </VStack>
                </Alert>
              )}
            </VStack>
          </DrawerBody>
          <DrawerFooter>
            <HStack>
              <Button variant="outline" onClick={() => { setIsOpen(false); setSelected(null); }}>Zrušit</Button>
              <Button colorScheme="blue" isLoading={onSave.isPending} onClick={() => onSave.mutate()}>Uložit</Button>
            </HStack>
          </DrawerFooter>
        </DrawerContent>
      </Drawer>
      </Box>
    </AdminLayout>
  );
};

export default TeamsAdminPage;
