import React, { useEffect, useMemo, useState } from 'react';
import {
  Box,
  Button,
  Flex,
  FormControl,
  FormLabel,
  Heading,
  HStack,
  IconButton,
  Input,
  Select,
  Spinner,
  Table,
  Tbody,
  Td,
  Text,
  Th,
  Thead,
  Tr,
  useDisclosure,
  useToast,
  VStack,
  Badge,
  Tooltip,
  Alert,
  AlertIcon,
  useColorModeValue,
  Divider,
} from '@chakra-ui/react';
import { FiPlus, FiTrash2, FiSave, FiRefreshCcw, FiDownload, FiEdit3, FiMove } from 'react-icons/fi';
import {
  CompetitionAlias,
  getCompetitionAliasesAdmin,
  upsertCompetitionAlias,
  deleteCompetitionAlias,
  reorderCompetitionAliases,
} from '../../services/competitionAliases';
import AdminLayout from '../../layouts/AdminLayout';
import { PageHeader } from '../../components/admin/PageHeader';

const CompetitionAliasesAdminPage: React.FC = () => {
  const cardBg = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.700');
  const inputBg = useColorModeValue('white', 'gray.700');
  const toast = useToast();
  const [items, setItems] = useState<CompetitionAlias[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [newCode, setNewCode] = useState('');
  const [newAlias, setNewAlias] = useState('');
  const [editing, setEditing] = useState<Record<string, { alias: string }>>({});
  const [draggedIndex, setDraggedIndex] = useState<number | null>(null);
  const [reorderMode, setReorderMode] = useState<boolean>(false);

  const load = async () => {
    setLoading(true);
    try {
      const data = await getCompetitionAliasesAdmin();
      setItems(data || []);
    } catch (e: any) {
      toast({ title: 'Chyba při načítání', description: e?.message || 'Nelze načíst aliasy', status: 'error' });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    // Load current aliases, then silently try to import missing ones from FACR cache
    load().then(async () => {
      await importFromFacrAuto();
    });
  }, []);

  const importFromFacr = async () => {
    setLoading(true);
    try {
      // Attempt to fetch cache JSON served by backend/static
      const resolveBackendUrl = (path: string) => {
        try {
          if (/^https?:\/\//i.test(path)) return path;
          if (path.startsWith('/cache') || path.startsWith('/uploads')) {
            const base = (process.env.REACT_APP_API_BASE_URL || process.env.REACT_APP_API_URL || 'http://localhost:8080/api/v1');
            const u = new URL(base);
            u.pathname = path;
            return u.toString();
          }
          return path;
        } catch {
          return path;
        }
      };

      const url = resolveBackendUrl('/cache/prefetch/facr_club_info.json');
      const res = await fetch(url, { cache: 'no-cache' });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const data = await res.json();
      const comps: Array<{ id?: string; code?: string; name?: string }> = Array.isArray(data?.competitions) ? data.competitions : [];
      // Fetch fresh aliases to avoid using potentially stale state
      const latest = await getCompetitionAliasesAdmin();
      const existing = new Set((latest || []).map(i => i.code));
      const missing = comps
        .map(c => ({ code: String(c.code || c.id || '').trim(), name: String(c.name || '').trim() }))
        .filter(c => c.code);
      const newOnes = missing.filter(c => !existing.has(c.code));
      if (!newOnes.length) {
        toast({ title: 'Žádné nové soutěže', description: 'Všechny soutěže již mají alias.', status: 'info' });
        return;
      }
      // Bulk upsert with alias defaulting to competition name
      await Promise.all(newOnes.map(c => upsertCompetitionAlias(c.code, { alias: c.name || c.code, original_name: c.name || undefined })));
      await load();
      toast({ title: 'Import dokončen', description: `Přidáno: ${newOnes.length}`, status: 'success' });
    } catch (e: any) {
      toast({ title: 'Import selhal', description: e?.message || 'Nelze načíst FACR soutěže', status: 'error' });
    } finally {
      setLoading(false);
    }
  };

  // Silent auto-import on mount: upserts only when missing; minimal toast
  const importFromFacrAuto = async () => {
    try {
      const resolveBackendUrl = (path: string) => {
        try {
          if (/^https?:\/\//i.test(path)) return path;
          if (path.startsWith('/cache') || path.startsWith('/uploads')) {
            const base = (process.env.REACT_APP_API_BASE_URL || process.env.REACT_APP_API_URL || 'http://localhost:8080/api/v1');
            const u = new URL(base);
            u.pathname = path;
            return u.toString();
          }
          return path;
        } catch {
          return path;
        }
      };

      const url = resolveBackendUrl('/cache/prefetch/facr_club_info.json');
      const res = await fetch(url, { cache: 'no-cache' });
      if (!res.ok) return; // silent
      const data = await res.json();
      const comps: Array<{ id?: string; code?: string; name?: string }> = Array.isArray(data?.competitions) ? data.competitions : [];
      const latest = await getCompetitionAliasesAdmin();
      const existing = new Set((latest || []).map(i => i.code));
      const missing = comps
        .map(c => ({ code: String(c.code || c.id || '').trim(), name: String(c.name || '').trim() }))
        .filter(c => c.code);
      const newOnes = missing.filter(c => !existing.has(c.code));
      if (!newOnes.length) return;
      await Promise.all(newOnes.map(c => upsertCompetitionAlias(c.code, { alias: c.name || c.code, original_name: c.name || undefined })));
      await load();
      toast({ title: 'Alias soutěží doplněny', description: `Přidáno: ${newOnes.length}`, status: 'success', duration: 3000 });
    } catch {
      // silent on auto
    }
  };

  const onAdd = async () => {
    const code = newCode.trim();
    const alias = newAlias.trim();
    if (!code || !alias) {
      toast({ title: 'Vyplňte code a alias', status: 'warning' });
      return;
    }
    try {
      const saved = await upsertCompetitionAlias(code, { alias });
      setItems((prev) => {
        const filtered = prev.filter((i) => i.code !== saved.code);
        return [...filtered, saved].sort((a, b) => a.code.localeCompare(b.code));
      });
      setNewCode(''); setNewAlias('');
      toast({ title: 'Alias uložen', status: 'success' });
    } catch (e: any) {
      toast({ title: 'Uložení selhalo', description: e?.message || 'Zkuste znovu', status: 'error' });
    }
  };

  const onSave = async (code: string) => {
    const data = editing[code];
    if (!data) return;
    if (!data.alias?.trim()) {
      toast({ title: 'Alias je povinný', status: 'warning' });
      return;
    }
    try {
  // Preserve original_name if present on the existing item to avoid losing it on edit
  const existing = items.find((i) => i.code === code);
  const payload: { alias: string; original_name?: string } = { alias: data.alias.trim() };
  if (existing?.original_name) payload.original_name = existing.original_name;
  const saved = await upsertCompetitionAlias(code, payload);
      setItems((prev) => prev.map((i) => (i.code === code ? saved : i)));
      setEditing((prev) => { const n = { ...prev }; delete n[code]; return n; });
      toast({ title: 'Uloženo', status: 'success' });
    } catch (e: any) {
      toast({ title: 'Uložení selhalo', description: e?.message || 'Zkuste znovu', status: 'error' });
    }
  };

  const onDelete = async (code: string) => {
    if (!window.confirm(`Smazat alias pro soutěž ${code}?`)) return;
    try {
      await deleteCompetitionAlias(code);
      setItems((prev) => prev.filter((i) => i.code !== code));
      setEditing((prev) => { const n = { ...prev }; delete n[code]; return n; });
      toast({ title: 'Smazáno', status: 'success' });
    } catch (e: any) {
      toast({ title: 'Smazání selhalo', description: e?.message || 'Zkuste znovu', status: 'error' });
    }
  };

  // In reorder mode, show items as-is (ordered by display_order from backend)
  // In normal mode, sort by code for editing
  const sorted = useMemo(() => {
    if (!items) return [];
    if (reorderMode) return items;

    const normalizeOrder = (value?: number) => {
      if (!value || value <= 0) return Number.MAX_SAFE_INTEGER;
      return value;
    };

    return [...items].sort((a, b) => {
      const orderA = normalizeOrder(a.display_order);
      const orderB = normalizeOrder(b.display_order);
      if (orderA !== orderB) return orderA - orderB;
      return a.code.localeCompare(b.code);
    });
  }, [items, reorderMode]);

  const onSaveAll = async () => {
    const entries = Object.entries(editing);
    if (!entries.length) {
      toast({ title: 'Nic k uložení', status: 'info' });
      return;
    }
    setLoading(true);
    try {
      // Validate
      for (const [code, data] of entries) {
        if (!data?.alias?.trim()) {
          throw new Error(`Alias je povinný pro ${code}`);
        }
      }
      // Save all in parallel
      // When saving multiple edits, preserve original_name from existing items where available
      const savedList = await Promise.all(
        entries.map(([code, data]) => {
          const existing = items.find((i) => i.code === code);
          const payload: { alias: string; original_name?: string } = { alias: data.alias.trim() };
          if (existing?.original_name) payload.original_name = existing.original_name;
          return upsertCompetitionAlias(code, payload);
        })
      );
      // Merge into items
      setItems((prev) => {
        const map = new Map(prev.map((i) => [i.code, i] as const));
        for (const s of savedList) map.set(s.code, s);
        return Array.from(map.values()).sort((a, b) => a.code.localeCompare(b.code));
      });
      setEditing({});
      toast({ title: 'Vše uloženo', status: 'success' });
    } catch (e: any) {
      toast({ title: 'Hromadné uložení selhalo', description: e?.message || 'Zkuste znovu', status: 'error' });
    } finally {
      setLoading(false);
    }
  };

  const hasChanges = Object.keys(editing).length > 0;

  // Drag-and-drop handlers
  const handleDragStart = (e: React.DragEvent<HTMLTableRowElement>, index: number) => {
    setDraggedIndex(index);
    e.dataTransfer.effectAllowed = 'move';
  };

  const handleDragOver = (e: React.DragEvent<HTMLTableRowElement>, index: number) => {
    e.preventDefault();
    if (draggedIndex === null || draggedIndex === index) return;
    
    // Reorder items array
    const newItems = [...items];
    const draggedItem = newItems[draggedIndex];
    newItems.splice(draggedIndex, 1);
    newItems.splice(index, 0, draggedItem);
    
    setItems(newItems);
    setDraggedIndex(index);
  };

  const handleDragEnd = () => {
    setDraggedIndex(null);
  };

  const saveReorder = async () => {
    setLoading(true);
    try {
      // Assign display_order based on current position (1-indexed)
      const reordered = items.map((item, idx) => ({
        code: item.code,
        display_order: idx + 1,
      }));
      await reorderCompetitionAliases(reordered);
      toast({ title: 'Pořadí uloženo', status: 'success' });
      setReorderMode(false);
      await load();
    } catch (e: any) {
      toast({ title: 'Chyba při ukládání pořadí', description: e?.message || 'Zkuste znovu', status: 'error' });
    } finally {
      setLoading(false);
    }
  };

  const cancelReorder = () => {
    setReorderMode(false);
    load(); // Reload to reset order
  };

  return (
    <AdminLayout>
      <Box maxW="1400px" mx="auto">
        <PageHeader
          title="Alias soutěží"
          description="Spravujte zobrazované názvy soutěží. Můžete je importovat z cache (FACR) a upravit aliasy."
        />

        {/* Action Bar */}
        <Flex 
          align="center" 
          justify="space-between" 
          mb={6} 
          wrap="wrap" 
          gap={3}
          bg={cardBg}
          p={4}
          borderRadius="lg"
          shadow="sm"
          borderWidth="1px"
          borderColor="gray.200"
        >
          <HStack spacing={3}>
            {!reorderMode ? (
              <>
                <Button 
                  leftIcon={<FiRefreshCcw />} 
                  onClick={load} 
                  isLoading={loading} 
                  variant="outline"
                  size="md"
                  _hover={{ bg: 'gray.50', borderColor: 'gray.400' }}
                >
                  Obnovit
                </Button>
                <Button 
                  leftIcon={<FiSave />} 
                  onClick={onSaveAll} 
                  isDisabled={!hasChanges} 
                  isLoading={loading} 
                  colorScheme="green"
                  size="md"
                  variant={hasChanges ? 'solid' : 'outline'}
                  _hover={hasChanges ? { bg: 'green.600' } : {}}
                >
                  Uložit vše {hasChanges && <Badge ml={2} colorScheme="green" variant="solid">{Object.keys(editing).length}</Badge>}
                </Button>
                <Button 
                  leftIcon={<FiMove />} 
                  onClick={() => setReorderMode(true)} 
                  isLoading={loading} 
                  colorScheme="purple"
                  size="md"
                  variant="outline"
                  _hover={{ bg: 'purple.50', borderColor: 'purple.400' }}
                >
                  Změnit pořadí
                </Button>
              </>
            ) : (
              <>
                <Button 
                  leftIcon={<FiSave />} 
                  onClick={saveReorder} 
                  isLoading={loading} 
                  colorScheme="green"
                  size="md"
                >
                  Uložit pořadí
                </Button>
                <Button 
                  onClick={cancelReorder} 
                  isDisabled={loading} 
                  variant="outline"
                  size="md"
                >
                  Zrušit
                </Button>
              </>
            )}
          </HStack>
          {!reorderMode && (
            <Button 
              leftIcon={<FiDownload />} 
              onClick={importFromFacr} 
              isLoading={loading} 
              colorScheme="blue"
              size="md"
              shadow="sm"
            >
              Importovat ze soutěží
            </Button>
          )}
        </Flex>

        {/* Add New Section - Hidden in reorder mode */}
        {!reorderMode && (
          <Box 
            bg={cardBg} 
            borderWidth="1px" 
            borderColor="gray.200"
            borderRadius="lg" 
            p={6} 
            mb={6}
            shadow="sm"
            _hover={{ shadow: 'md' }}
            transition="all 0.2s"
          >
          <HStack mb={4} spacing={2}>
            <Box bg="blue.500" p={2} borderRadius="md">
              <FiPlus color="white" size={18} />
            </Box>
            <Heading size="md" color="gray.700">Přidat nový alias</Heading>
          </HStack>
          <Divider mb={4} />
          <Flex gap={3} wrap="wrap" align="flex-end">
            <VStack align="flex-start" spacing={2} flex="0 0 240px">
              <Text fontSize="sm" fontWeight="medium" color="gray.600">Kód soutěže</Text>
              <Input 
                placeholder="např. A1A" 
                value={newCode} 
                onChange={(e) => setNewCode(e.target.value.toUpperCase())} 
                size="md"
                bg={useColorModeValue('gray.50', 'gray.900')}
                borderColor="gray.300"
                _hover={{ borderColor: 'blue.400', bg: 'white' }}
                _focus={{ borderColor: 'blue.500', bg: 'white', shadow: 'sm' }}
                fontFamily="mono"
                fontWeight="semibold"
              />
            </VStack>
            <VStack align="flex-start" spacing={2} flex="1" minW="300px">
              <Text fontSize="sm" fontWeight="medium" color="gray.600">Zobrazovaný název (alias)</Text>
              <Input 
                placeholder="např. Krajský přebor" 
                value={newAlias} 
                onChange={(e) => setNewAlias(e.target.value)} 
                size="md"
                bg={useColorModeValue('gray.50', 'gray.900')}
                borderColor="gray.300"
                _hover={{ borderColor: 'blue.400', bg: 'white' }}
                _focus={{ borderColor: 'blue.500', bg: 'white', shadow: 'sm' }}
              />
            </VStack>
            <Button 
              leftIcon={<FiPlus />} 
              onClick={onAdd} 
              colorScheme="blue"
              size="md"
              px={8}
              shadow="sm"
              _hover={{ shadow: 'md', transform: 'translateY(-1px)' }}
              transition="all 0.2s"
            >
              Přidat
            </Button>
          </Flex>
        </Box>
        )}

        {/* Table Section */}
        <Box 
          bg={cardBg} 
          borderWidth="1px" 
          borderColor="gray.200"
          borderRadius="lg" 
          overflow="hidden"
          shadow="sm"
        >
          <Box overflowX="auto">
            <Table variant="simple" size="md">
              <Thead bg={useColorModeValue('gray.50', 'gray.900')}>
                <Tr>
                  {reorderMode && (
                    <Th width="60px" textTransform="uppercase" fontSize="xs" fontWeight="bold" color="gray.600" letterSpacing="wide">
                      Pořadí
                    </Th>
                  )}
                  <Th 
                    width="200px" 
                    textTransform="uppercase" 
                    fontSize="xs" 
                    fontWeight="bold" 
                    color="gray.600"
                    letterSpacing="wide"
                  >
                    Kód
                  </Th>
                  {!reorderMode && (
                    <>
                      <Th 
                        textTransform="uppercase" 
                        fontSize="xs" 
                        fontWeight="bold" 
                        color="gray.600"
                        letterSpacing="wide"
                      >
                        Původní název
                      </Th>
                      <Th 
                        textTransform="uppercase" 
                        fontSize="xs" 
                        fontWeight="bold" 
                        color="gray.600"
                        letterSpacing="wide"
                      >
                        Alias
                      </Th>
                      <Th 
                        isNumeric
                        textTransform="uppercase" 
                        fontSize="xs" 
                        fontWeight="bold" 
                        color="gray.600"
                        letterSpacing="wide"
                      >
                        Akce
                      </Th>
                    </>
                  )}
                  {reorderMode && (
                    <Th 
                      textTransform="uppercase" 
                      fontSize="xs" 
                      fontWeight="bold" 
                      color="gray.600"
                      letterSpacing="wide"
                    >
                      Alias
                    </Th>
                  )}
                </Tr>
              </Thead>
              <Tbody>
                {sorted.map((it, idx) => {
                  const ed = editing[it.code] ?? { alias: it.alias };
                  const isEdited = editing[it.code] !== undefined;
                  
                  if (reorderMode) {
                    // Reorder mode: simplified draggable row
                    return (
                      <Tr 
                        key={it.code}
                        draggable
                        onDragStart={(e) => handleDragStart(e, idx)}
                        onDragOver={(e) => handleDragOver(e, idx)}
                        onDragEnd={handleDragEnd}
                        cursor="move"
                        bg={draggedIndex === idx ? 'blue.50' : undefined}
                        _hover={{ bg: 'gray.100' }}
                        transition="background 0.15s"
                        opacity={draggedIndex === idx ? 0.5 : 1}
                      >
                        <Td>
                          <HStack spacing={2}>
                            <Box as={FiMove} color="gray.500" />
                            <Text fontWeight="bold" color="gray.700">{idx + 1}</Text>
                          </HStack>
                        </Td>
                        <Td>
                          <Badge 
                            colorScheme="blue" 
                            variant="subtle" 
                            fontFamily="mono" 
                            fontSize="sm"
                            px={2}
                            py={1}
                          >
                            {it.code}
                          </Badge>
                        </Td>
                        <Td>
                          <Text fontSize="sm" fontWeight="medium">{it.alias}</Text>
                        </Td>
                      </Tr>
                    );
                  }
                  
                  // Edit mode: full editing capabilities
                  return (
                    <Tr 
                      key={it.code}
                      _hover={{ bg: 'gray.50' }}
                      transition="background 0.15s"
                    >
                      <Td>
                        <HStack>
                          <Badge 
                            colorScheme="blue" 
                            variant="subtle" 
                            fontFamily="mono" 
                            fontSize="sm"
                            px={2}
                            py={1}
                          >
                            {it.code}
                          </Badge>
                          {isEdited && (
                            <Box as={FiEdit3} color="orange.500" size={14} />
                          )}
                        </HStack>
                      </Td>
                      <Td>
                        <Text fontSize="sm" color="gray.600" fontWeight="medium">
                          {it.original_name || <Text as="span" color="gray.400">—</Text>}
                        </Text>
                      </Td>
                      <Td>
                        <Input 
                          size="md" 
                          value={ed.alias} 
                          onChange={(e) => setEditing((prev) => ({ ...prev, [it.code]: { alias: e.target.value } }))} 
                          bg={isEdited ? 'orange.50' : 'white'}
                          borderColor={isEdited ? 'orange.300' : 'gray.200'}
                          _hover={{ borderColor: isEdited ? 'orange.400' : 'blue.300', bg: 'white' }}
                          _focus={{ borderColor: 'blue.500', bg: 'white', shadow: 'sm' }}
                          fontWeight="medium"
                        />
                      </Td>
                      <Td isNumeric>
                        <HStack justify="flex-end" spacing={2}>
                          <IconButton 
                            aria-label="Uložit" 
                            icon={<FiSave />} 
                            size="sm" 
                            onClick={() => onSave(it.code)}
                            colorScheme="green"
                            variant="ghost"
                            _hover={{ bg: 'green.50' }}
                          />
                          <IconButton 
                            aria-label="Smazat" 
                            icon={<FiTrash2 />} 
                            size="sm" 
                            colorScheme="red" 
                            variant="ghost"
                            _hover={{ bg: 'red.50' }}
                            onClick={() => onDelete(it.code)} 
                          />
                        </HStack>
                      </Td>
                    </Tr>
                  );
                })}
                {sorted.length === 0 && (
                  <Tr>
                    <Td colSpan={4}>
                      <VStack py={12} spacing={3}>
                        <Box color="gray.300" fontSize="4xl">
                          <FiEdit3 />
                        </Box>
                        <Text color="gray.500" fontSize="md" fontWeight="medium">
                          Žádné aliasy zatím nejsou
                        </Text>
                        <Text color="gray.400" fontSize="sm">
                          Přidejte nový alias nebo importujte ze soutěží
                        </Text>
                      </VStack>
                    </Td>
                  </Tr>
                )}
              </Tbody>
            </Table>
          </Box>
        </Box>

        {/* Summary Footer */}
        {sorted.length > 0 && (
          <Box 
            mt={4} 
            p={4} 
            bg={useColorModeValue('gray.50', 'gray.900')} 
            borderRadius="md" 
            borderWidth="1px"
            borderColor="gray.200"
          >
            <HStack justify="space-between" wrap="wrap">
              <Text fontSize="sm" color="gray.600">
                Celkem aliasů: <Badge colorScheme="blue" ml={1}>{sorted.length}</Badge>
              </Text>
              {hasChanges && (
                <HStack spacing={2}>
                  <Badge colorScheme="orange" variant="subtle">
                    {Object.keys(editing).length} neuložených změn
                  </Badge>
                  <Button 
                    size="sm" 
                    colorScheme="green" 
                    onClick={onSaveAll}
                    leftIcon={<FiSave />}
                  >
                    Uložit vše
                  </Button>
                </HStack>
              )}
            </HStack>
          </Box>
        )}
      </Box>
    </AdminLayout>
  );
};

export default CompetitionAliasesAdminPage;
