import {
  Box,
  Button,
  Heading,
  HStack,
  IconButton,
  Image,
  Input,
  InputGroup,
  InputLeftElement,
  Modal,
  ModalBody,
  ModalCloseButton,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalOverlay,
  Table,
  Tbody,
  Td,
  Th,
  Thead,
  Tr,
  useDisclosure,
  useToast,
  VStack,
  Text,
  Badge,
  Tabs,
  TabList,
  Tab,
  TabPanels,
  TabPanel,
  useColorModeValue,
  Tooltip,
  Select,
  Flex,
  Spacer,
  Alert,
  AlertIcon,
  AlertTitle,
  AlertDescription,
  Stack,
  Link as ChakraLink,
  Divider,
  Code,
  Icon,
} from '@chakra-ui/react';
import { useState, useMemo } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { FiTrash2, FiSearch, FiRefreshCw, FiCopy, FiAlertTriangle, FiExternalLink } from 'react-icons/fi';
import AdminLayout from '../../layouts/AdminLayout';
import {
  FileInfo,
  FileUsage,
  DuplicateFiles,
  getAllFiles,
  getUnusedFiles,
  getDuplicateFiles,
  deleteFile,
  scanAndSyncFiles,
  refreshFileTracking,
  formatFileSize,
  getFileIcon,
} from '../../services/files';

const FilesAdminPage: React.FC = () => {
  const toast = useToast();
  const qc = useQueryClient();
  const [search, setSearch] = useState('');
  const [mimeFilter, setMimeFilter] = useState('');
  const [selectedFile, setSelectedFile] = useState<FileInfo | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<FileInfo | null>(null);
  const [forceDelete, setForceDelete] = useState(false);
  const [scanResult, setScanResult] = useState<any>(null);
  const [refreshResult, setRefreshResult] = useState<any>(null);
  
  const { isOpen: isUsagesOpen, onOpen: onUsagesOpen, onClose: onUsagesClose } = useDisclosure();
  const { isOpen: isDeleteOpen, onOpen: onDeleteOpen, onClose: onDeleteClose } = useDisclosure();
  const { isOpen: isScanResultOpen, onOpen: onScanResultOpen, onClose: onScanResultClose } = useDisclosure();
  const { isOpen: isRefreshResultOpen, onOpen: onRefreshResultOpen, onClose: onRefreshResultClose } = useDisclosure();

  const borderColor = useColorModeValue('gray.200', 'gray.600');
  const bgHover = useColorModeValue('gray.50', 'gray.700');

  // Fetch all files
  const { data: allFiles = [], isLoading, refetch } = useQuery({
    queryKey: ['admin-files', search, mimeFilter],
    queryFn: () => getAllFiles({ search, mime_type: mimeFilter }),
  });

  // Fetch unused files
  const { data: unusedFiles = [] } = useQuery({
    queryKey: ['admin-files-unused'],
    queryFn: getUnusedFiles,
  });

  // Fetch duplicate files
  const { data: duplicateFiles = {} } = useQuery({
    queryKey: ['admin-files-duplicates'],
    queryFn: getDuplicateFiles,
  });

  // Delete mutation
  const deleteMutation = useMutation({
    mutationFn: ({ id, force }: { id: number; force: boolean }) => deleteFile(id, force),
    onSuccess: () => {
      toast({ title: 'Soubor smazán', status: 'success' });
      qc.invalidateQueries({ queryKey: ['admin-files'] });
      qc.invalidateQueries({ queryKey: ['admin-files-unused'] });
      qc.invalidateQueries({ queryKey: ['admin-files-duplicates'] });
      onDeleteClose();
      setDeleteTarget(null);
      setForceDelete(false);
    },
    onError: (error: any) => {
      if (error.response?.status === 409) {
        // File is in use - show warning
        setForceDelete(false);
        toast({
          title: 'Soubor je používán',
          description: 'Soubor je používán. Zkontrolujte použití a potvrďte smazání.',
          status: 'warning',
          duration: 5000,
        });
      } else {
        toast({
          title: 'Chyba při mazání',
          description: error?.response?.data?.error || 'Nepodařilo se smazat soubor',
          status: 'error',
        });
      }
    },
  });

  // Scan mutation
  const scanMutation = useMutation({
    mutationFn: scanAndSyncFiles,
    onSuccess: (data) => {
      setScanResult(data);
      onScanResultOpen();
      qc.invalidateQueries({ queryKey: ['admin-files'] });
      qc.invalidateQueries({ queryKey: ['admin-files-unused'] });
      qc.invalidateQueries({ queryKey: ['admin-files-duplicates'] });
    },
    onError: () => {
      toast({ title: 'Chyba při skenování', status: 'error' });
    },
  });

  // Refresh tracking mutation
  const refreshTrackingMutation = useMutation({
    mutationFn: refreshFileTracking,
    onSuccess: (data) => {
      setRefreshResult(data);
      onRefreshResultOpen();
      qc.invalidateQueries({ queryKey: ['admin-files'] });
      qc.invalidateQueries({ queryKey: ['admin-files-unused'] });
      qc.invalidateQueries({ queryKey: ['admin-files-duplicates'] });
    },
    onError: () => {
      toast({ title: 'Chyba při aktualizaci sledování', status: 'error' });
    },
  });

  const handleDelete = (file: FileInfo) => {
    setDeleteTarget(file);
    setForceDelete(false);
    onDeleteOpen();
  };

  const confirmDelete = () => {
    if (deleteTarget) {
      deleteMutation.mutate({ id: deleteTarget.id, force: forceDelete });
    }
  };

  const handleViewUsages = (file: FileInfo) => {
    setSelectedFile(file);
    onUsagesOpen();
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    toast({ title: 'Zkopírováno', status: 'success', duration: 2000 });
  };

  const getImageUrl = (url: string) => {
    if (url.startsWith('http')) return url;
    const apiUrl = process.env.REACT_APP_API_URL || 'http://localhost:8080/api/v1';
    const origin = new URL(apiUrl).origin;
    return `${origin}${url}`;
  };

  // Mime type options
  const mimeTypes = useMemo(() => {
    const types = new Set<string>();
    allFiles.forEach(file => {
      if (file.mime_type) {
        const baseType = file.mime_type.split('/')[0];
        types.add(baseType);
      }
    });
    return Array.from(types);
  }, [allFiles]);

  const FileRow: React.FC<{ file: FileInfo; showUsageCount?: boolean }> = ({ file, showUsageCount = true }) => (
    <Tr _hover={{ bg: bgHover }}>
      <Td>
        <HStack>
          {file.mime_type?.startsWith('image/') ? (
            <Image
              src={getImageUrl(file.file_url)}
              alt={file.filename}
              boxSize="40px"
              objectFit="cover"
              borderRadius="md"
              fallbackSrc="/logo192.png"
            />
          ) : (
            <Icon as={getFileIcon(file.mime_type || '')} boxSize={6} color="blue.500" />
          )}
          <VStack align="start" spacing={0}>
            <Text fontWeight="medium" fontSize="sm">{file.filename}</Text>
            <Text fontSize="xs" color="gray.500">{file.file_path}</Text>
          </VStack>
        </HStack>
      </Td>
      <Td fontSize="sm">{formatFileSize(file.file_size)}</Td>
      <Td fontSize="sm">
        <Badge colorScheme={file.mime_type?.startsWith('image/') ? 'blue' : 'gray'}>
          {file.mime_type}
        </Badge>
      </Td>
      {showUsageCount && (
        <Td>
          <HStack>
            <Badge colorScheme={file.usage_count > 0 ? 'green' : 'red'}>
              {file.usage_count}
            </Badge>
            {file.usage_count > 0 && (
              <IconButton
                aria-label="Zobrazit použití"
                icon={<FiExternalLink />}
                size="xs"
                variant="ghost"
                onClick={() => handleViewUsages(file)}
              />
            )}
          </HStack>
        </Td>
      )}
      <Td fontSize="sm">{new Date(file.created_at).toLocaleDateString('cs-CZ')}</Td>
      <Td>
        <HStack spacing={1}>
          <Tooltip label="Kopírovat URL">
            <IconButton
              aria-label="Kopírovat URL"
              icon={<FiCopy />}
              size="sm"
              variant="ghost"
              onClick={() => copyToClipboard(file.file_url)}
            />
          </Tooltip>
          <Tooltip label="Smazat">
            <IconButton
              aria-label="Smazat"
              icon={<FiTrash2 />}
              size="sm"
              variant="ghost"
              colorScheme="red"
              onClick={() => handleDelete(file)}
            />
          </Tooltip>
        </HStack>
      </Td>
    </Tr>
  );

  const duplicateGroups = Object.entries(duplicateFiles);

  return (
    <AdminLayout requireAdmin={true}>
      <VStack align="stretch" spacing={6}>
        <HStack justify="space-between">
          <Heading size="lg">Správa souborů</Heading>
          <HStack spacing={2}>
            <Button
              leftIcon={<FiRefreshCw />}
              onClick={() => refreshTrackingMutation.mutate(undefined)}
              isLoading={refreshTrackingMutation.isPending}
              colorScheme="green"
              size="sm"
              variant="outline"
            >
              Aktualizovat sledování
            </Button>
            <Button
              leftIcon={<FiRefreshCw />}
              onClick={() => scanMutation.mutate()}
              isLoading={scanMutation.isPending}
              colorScheme="blue"
              size="sm"
            >
              Skenovat soubory
            </Button>
          </HStack>
        </HStack>

        <Tabs colorScheme="blue" variant="enclosed">
          <TabList>
            <Tab>Všechny soubory ({allFiles.length})</Tab>
            <Tab>Nepoužívané ({unusedFiles.length})</Tab>
            <Tab>Duplicity ({duplicateGroups.length})</Tab>
          </TabList>

          <TabPanels>
            {/* All Files Tab */}
            <TabPanel>
              <VStack align="stretch" spacing={4}>
                {allFiles.length === 0 && !isLoading && (
                  <Alert status="info" borderRadius="md">
                    <AlertIcon />
                    <Box flex="1">
                      <AlertTitle>Žádné soubory v databázi</AlertTitle>
                      <AlertDescription>
                        Klikněte na tlačítko "Skenovat soubory" pro načtení souborů z uploads složky do databáze.
                      </AlertDescription>
                    </Box>
                  </Alert>
                )}
                <HStack spacing={4}>
                  <InputGroup maxW="400px">
                    <InputLeftElement pointerEvents="none">
                      <FiSearch />
                    </InputLeftElement>
                    <Input
                      placeholder="Hledat soubory..."
                      value={search}
                      onChange={(e) => setSearch(e.target.value)}
                    />
                  </InputGroup>
                  <Select
                    placeholder="Všechny typy"
                    maxW="200px"
                    value={mimeFilter}
                    onChange={(e) => setMimeFilter(e.target.value)}
                  >
                    {mimeTypes.map(type => (
                      <option key={type} value={type}>{type}</option>
                    ))}
                  </Select>
                  <Spacer />
                  <Text fontSize="sm" color="gray.500">
                    Celkem: {allFiles.length} souborů
                  </Text>
                </HStack>

                <Box overflowX="auto" borderWidth="1px" borderRadius="md" borderColor={borderColor}>
                  <Table size="sm">
                    <Thead>
                      <Tr>
                        <Th>Soubor</Th>
                        <Th>Velikost</Th>
                        <Th>Typ</Th>
                        <Th>Použití</Th>
                        <Th>Vytvořeno</Th>
                        <Th>Akce</Th>
                      </Tr>
                    </Thead>
                    <Tbody>
                      {isLoading ? (
                        <Tr>
                          <Td colSpan={6} textAlign="center" py={8}>
                            Načítání...
                          </Td>
                        </Tr>
                      ) : allFiles.length === 0 ? (
                        <Tr>
                          <Td colSpan={6} textAlign="center" py={8}>
                            Žádné soubory nenalezeny
                          </Td>
                        </Tr>
                      ) : (
                        allFiles.map(file => <FileRow key={file.id} file={file} />)
                      )}
                    </Tbody>
                  </Table>
                </Box>
              </VStack>
            </TabPanel>

            {/* Unused Files Tab */}
            <TabPanel>
              <VStack align="stretch" spacing={4}>
                <Alert status="info" borderRadius="md">
                  <AlertIcon />
                  <Box>
                    <AlertTitle>Nepoužívané soubory</AlertTitle>
                    <AlertDescription>
                      Tyto soubory nejsou použity v žádném článku, hráči, sponzorovi nebo jiné entitě.
                    </AlertDescription>
                  </Box>
                </Alert>

                <Box overflowX="auto" borderWidth="1px" borderRadius="md" borderColor={borderColor}>
                  <Table size="sm">
                    <Thead>
                      <Tr>
                        <Th>Soubor</Th>
                        <Th>Velikost</Th>
                        <Th>Typ</Th>
                        <Th>Vytvořeno</Th>
                        <Th>Akce</Th>
                      </Tr>
                    </Thead>
                    <Tbody>
                      {unusedFiles.length === 0 ? (
                        <Tr>
                          <Td colSpan={5} textAlign="center" py={8}>
                            Všechny soubory jsou používány
                          </Td>
                        </Tr>
                      ) : (
                        unusedFiles.map(file => <FileRow key={file.id} file={file} showUsageCount={false} />)
                      )}
                    </Tbody>
                  </Table>
                </Box>
              </VStack>
            </TabPanel>

            {/* Duplicates Tab */}
            <TabPanel>
              <VStack align="stretch" spacing={4}>
                <Alert status="warning" borderRadius="md">
                  <AlertIcon />
                  <Box>
                    <AlertTitle>Duplicitní soubory</AlertTitle>
                    <AlertDescription>
                      Tyto soubory mají identický obsah (MD5 hash). Můžete je smazat a aktualizovat odkazy.
                    </AlertDescription>
                  </Box>
                </Alert>

                {duplicateGroups.length === 0 ? (
                  <Box textAlign="center" py={8}>
                    <Text color="gray.500">Žádné duplicity nenalezeny</Text>
                  </Box>
                ) : (
                  duplicateGroups.map(([hash, files]) => (
                    <Box key={hash} borderWidth="1px" borderRadius="md" p={4} borderColor={borderColor}>
                      <VStack align="stretch" spacing={2}>
                        <HStack>
                          <FiAlertTriangle color="orange" />
                          <Text fontWeight="bold" fontSize="sm">
                            Duplicitní skupina ({files.length} souborů)
                          </Text>
                          <Code fontSize="xs">{hash.substring(0, 12)}...</Code>
                        </HStack>
                        <Divider />
                        <Table size="sm" variant="simple">
                          <Thead>
                            <Tr>
                              <Th>Soubor</Th>
                              <Th>Velikost</Th>
                              <Th>Použití</Th>
                              <Th>Vytvořeno</Th>
                              <Th>Akce</Th>
                            </Tr>
                          </Thead>
                          <Tbody>
                            {files.map(file => (
                              <FileRow key={file.id} file={file} />
                            ))}
                          </Tbody>
                        </Table>
                      </VStack>
                    </Box>
                  ))
                )}
              </VStack>
            </TabPanel>
          </TabPanels>
        </Tabs>
      </VStack>

      {/* File Usages Modal */}
      <Modal isOpen={isUsagesOpen} onClose={onUsagesClose} size="xl">
        <ModalOverlay />
        <ModalContent>
          <ModalHeader>Použití souboru</ModalHeader>
          <ModalCloseButton />
          <ModalBody>
            {selectedFile && (
              <VStack align="stretch" spacing={4}>
                <HStack>
                  {selectedFile.mime_type?.startsWith('image/') && (
                    <Image
                      src={getImageUrl(selectedFile.file_url)}
                      alt={selectedFile.filename}
                      maxH="100px"
                      borderRadius="md"
                    />
                  )}
                  <VStack align="start" flex={1}>
                    <Text fontWeight="bold">{selectedFile.filename}</Text>
                    <Text fontSize="sm" color="gray.500">{selectedFile.file_path}</Text>
                  </VStack>
                </HStack>

                <Divider />

                <VStack align="stretch" spacing={2}>
                  <Text fontWeight="bold">Používáno v ({selectedFile.usage_count}):</Text>
                  {selectedFile.usages && selectedFile.usages.length > 0 ? (
                    selectedFile.usages.map((usage) => (
                      <Box key={usage.id} p={3} borderWidth="1px" borderRadius="md">
                        <HStack justify="space-between">
                          <VStack align="start" spacing={0}>
                            <Badge colorScheme="purple">{usage.entity_type}</Badge>
                            <Text fontSize="sm" mt={1}>
                              {usage.entity_info?.title || usage.entity_info?.name || `ID: ${usage.entity_id}`}
                            </Text>
                            {usage.field_name && (
                              <Text fontSize="xs" color="gray.500">Pole: {usage.field_name}</Text>
                            )}
                          </VStack>
                          {usage.entity_info?.url && (
                            <ChakraLink href={usage.entity_info.url} isExternal>
                              <IconButton
                                aria-label="Otevřít"
                                icon={<FiExternalLink />}
                                size="sm"
                                variant="ghost"
                              />
                            </ChakraLink>
                          )}
                        </HStack>
                      </Box>
                    ))
                  ) : (
                    <Text color="gray.500" fontSize="sm">Soubor není nikde použit</Text>
                  )}
                </VStack>
              </VStack>
            )}
          </ModalBody>
          <ModalFooter>
            <Button onClick={onUsagesClose}>Zavřít</Button>
          </ModalFooter>
        </ModalContent>
      </Modal>

      {/* Delete Confirmation Modal */}
      <Modal isOpen={isDeleteOpen} onClose={onDeleteClose}>
        <ModalOverlay />
        <ModalContent>
          <ModalHeader>Smazat soubor</ModalHeader>
          <ModalCloseButton />
          <ModalBody>
            {deleteTarget && (
              <VStack align="stretch" spacing={4}>
                <Text>
                  Opravdu chcete smazat soubor <strong>{deleteTarget.filename}</strong>?
                </Text>
                
                {deleteTarget.usage_count > 0 && (
                  <Alert status="warning">
                    <AlertIcon />
                    <Box>
                      <AlertTitle>Pozor!</AlertTitle>
                      <AlertDescription>
                        Tento soubor je použit na {deleteTarget.usage_count} místech.
                        Smazáním může dojít k nefunkčnosti odkazů.
                      </AlertDescription>
                    </Box>
                  </Alert>
                )}
              </VStack>
            )}
          </ModalBody>
          <ModalFooter>
            <HStack spacing={3}>
              <Button variant="ghost" onClick={onDeleteClose}>
                Zrušit
              </Button>
              <Button
                colorScheme="red"
                onClick={confirmDelete}
                isLoading={deleteMutation.isPending}
              >
                {(deleteTarget?.usage_count ?? 0) > 0 ? 'Přesto smazat' : 'Smazat'}
              </Button>
            </HStack>
          </ModalFooter>
        </ModalContent>
      </Modal>

      {/* Scan Results Modal */}
      <Modal isOpen={isScanResultOpen} onClose={onScanResultClose} size="lg">
        <ModalOverlay />
        <ModalContent>
          <ModalHeader>Výsledky skenování souborů</ModalHeader>
          <ModalCloseButton />
          <ModalBody>
            {scanResult && (
              <VStack align="stretch" spacing={4}>
                <Alert status="success" borderRadius="md">
                  <AlertIcon />
                  <Box flex="1">
                    <AlertTitle>Skenování dokončeno</AlertTitle>
                    <AlertDescription>{scanResult.message}</AlertDescription>
                  </Box>
                </Alert>

                <Stack spacing={3}>
                  <HStack justify="space-between" p={3} borderWidth="1px" borderRadius="md">
                    <Text fontWeight="medium">Nalezených souborů:</Text>
                    <Badge colorScheme="blue" fontSize="md" px={3} py={1}>
                      {scanResult.found_files}
                    </Badge>
                  </HStack>

                  <HStack justify="space-between" p={3} borderWidth="1px" borderRadius="md">
                    <Text fontWeight="medium">Nově přidaných:</Text>
                    <Badge colorScheme="green" fontSize="md" px={3} py={1}>
                      {scanResult.new_files}
                    </Badge>
                  </HStack>

                  {scanResult.skipped_files !== undefined && scanResult.skipped_files > 0 && (
                    <HStack justify="space-between" p={3} borderWidth="1px" borderRadius="md">
                      <Text fontWeight="medium">Přeskočených (.gitkeep, atd.):</Text>
                      <Badge colorScheme="gray" fontSize="md" px={3} py={1}>
                        {scanResult.skipped_files}
                      </Badge>
                    </HStack>
                  )}

                  {scanResult.orphaned_files > 0 && (
                    <HStack justify="space-between" p={3} borderWidth="1px" borderRadius="md" borderColor="orange.300">
                      <Text fontWeight="medium">Osiřelých záznamů:</Text>
                      <Badge colorScheme="orange" fontSize="md" px={3} py={1}>
                        {scanResult.orphaned_files}
                      </Badge>
                    </HStack>
                  )}
                </Stack>

                {scanResult.new_files_list && scanResult.new_files_list.length > 0 && (
                  <Box>
                    <Text fontWeight="bold" mb={2}>Nově přidané soubory:</Text>
                    <Box maxH="200px" overflowY="auto" borderWidth="1px" borderRadius="md" p={3}>
                      <VStack align="stretch" spacing={1}>
                        {scanResult.new_files_list.map((filename: string, idx: number) => (
                          <Text key={idx} fontSize="sm" fontFamily="monospace">
                            ✓ {filename}
                          </Text>
                        ))}
                      </VStack>
                    </Box>
                  </Box>
                )}

                {scanResult.orphaned_list && scanResult.orphaned_list.length > 0 && (
                  <Box>
                    <Text fontWeight="bold" mb={2} color="orange.500">Osiřelé záznamy (soubory v DB, ale ne na disku):</Text>
                    <Box maxH="200px" overflowY="auto" borderWidth="1px" borderRadius="md" p={3} borderColor="orange.300">
                      <VStack align="stretch" spacing={1}>
                        {scanResult.orphaned_list.map((filename: string, idx: number) => (
                          <Text key={idx} fontSize="sm" fontFamily="monospace" color="orange.600">
                            ⚠ {filename}
                          </Text>
                        ))}
                      </VStack>
                    </Box>
                  </Box>
                )}
              </VStack>
            )}
          </ModalBody>
          <ModalFooter>
            <Button colorScheme="blue" onClick={onScanResultClose}>
              Zavřít
            </Button>
          </ModalFooter>
        </ModalContent>
      </Modal>

      {/* Refresh Tracking Result Modal */}
      <Modal isOpen={isRefreshResultOpen} onClose={onRefreshResultClose} size="lg">
        <ModalOverlay />
        <ModalContent>
          <ModalHeader>Výsledky aktualizace sledování</ModalHeader>
          <ModalCloseButton />
          <ModalBody>
            {refreshResult && (
              <VStack align="stretch" spacing={4}>
                <Alert status="success">
                  <AlertIcon />
                  <Box>
                    <AlertTitle>Sledování aktualizováno!</AlertTitle>
                    <AlertDescription>
                      {refreshResult.message}
                    </AlertDescription>
                  </Box>
                </Alert>

                <Stack spacing={3}>
                  <Text fontWeight="bold" fontSize="lg" mb={2}>Statistiky:</Text>
                  
                  <HStack justify="space-between" p={3} borderWidth="1px" borderRadius="md">
                    <Text fontWeight="medium">Články:</Text>
                    <Badge colorScheme="blue" fontSize="md" px={3} py={1}>
                      {refreshResult.stats.articles_scanned}
                    </Badge>
                  </HStack>

                  <HStack justify="space-between" p={3} borderWidth="1px" borderRadius="md">
                    <Text fontWeight="medium">Aktivity:</Text>
                    <Badge colorScheme="blue" fontSize="md" px={3} py={1}>
                      {refreshResult.stats.events_scanned}
                    </Badge>
                  </HStack>

                  <HStack justify="space-between" p={3} borderWidth="1px" borderRadius="md">
                    <Text fontWeight="medium">Hráči:</Text>
                    <Badge colorScheme="blue" fontSize="md" px={3} py={1}>
                      {refreshResult.stats.players_scanned}
                    </Badge>
                  </HStack>

                  <HStack justify="space-between" p={3} borderWidth="1px" borderRadius="md">
                    <Text fontWeight="medium">Sponzoři:</Text>
                    <Badge colorScheme="blue" fontSize="md" px={3} py={1}>
                      {refreshResult.stats.sponsors_scanned}
                    </Badge>
                  </HStack>

                  <HStack justify="space-between" p={3} borderWidth="1px" borderRadius="md">
                    <Text fontWeight="medium">Kontakty:</Text>
                    <Badge colorScheme="blue" fontSize="md" px={3} py={1}>
                      {refreshResult.stats.contacts_scanned}
                    </Badge>
                  </HStack>

                  <HStack justify="space-between" p={3} borderWidth="1px" borderRadius="md">
                    <Text fontWeight="medium">Týmy:</Text>
                    <Badge colorScheme="blue" fontSize="md" px={3} py={1}>
                      {refreshResult.stats.teams_scanned}
                    </Badge>
                  </HStack>
                </Stack>
              </VStack>
            )}
          </ModalBody>
          <ModalFooter>
            <Button colorScheme="blue" onClick={onRefreshResultClose}>
              Zavřít
            </Button>
          </ModalFooter>
        </ModalContent>
      </Modal>
    </AdminLayout>
  );
};

export default FilesAdminPage;
