import {
  Box,
  Button,
  Heading,
  HStack,
  IconButton,
  Input,
  Table,
  Tbody,
  Td,
  Th,
  Thead,
  Tr,
  useDisclosure,
  useToast,
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalCloseButton,
  ModalBody,
  ModalFooter,
  FormControl,
  FormLabel,
  VStack,
  Text,
  useColorModeValue,
  Skeleton,
  Alert,
  AlertIcon,
  Badge,
  Textarea,
} from '@chakra-ui/react';
import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { FiEdit2, FiPlus, FiTrash2, FiTag } from 'react-icons/fi';
import AdminLayout from '../../layouts/AdminLayout';
import { PageHeader } from '../../components/admin/PageHeader';
import {
  CategoryItem,
  getCategories,
  createCategory,
  updateCategory,
  deleteCategory,
} from '../../services/categories';

const CategoriesAdminPage = () => {
  const toast = useToast();
  const qc = useQueryClient();
  const { data: categories, isLoading } = useQuery({ queryKey: ['admin-categories'], queryFn: getCategories });
  const [editing, setEditing] = useState<Partial<CategoryItem> | null>(null);
  const { isOpen, onOpen, onClose } = useDisclosure();
  const bgCard = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.700');

  const openCreate = () => {
    setEditing({ name: '', description: '' });
    onOpen();
  };

  const openEdit = (cat: CategoryItem) => {
    setEditing({ ...cat });
    onOpen();
  };

  const closeModal = () => {
    setEditing(null);
    onClose();
  };

  const createMut = useMutation({
    mutationFn: (payload: any) => createCategory(payload),
    onSuccess: () => {
      toast({ title: 'Kategorie vytvořena', status: 'success', duration: 3000 });
      qc.invalidateQueries({ queryKey: ['admin-categories'] });
      closeModal();
    },
    onError: (e: any) =>
      toast({
        title: 'Vytvoření selhalo',
        description: e?.response?.data?.chyba || e?.message || 'Chyba',
        status: 'error',
        duration: 5000,
      }),
  });

  const updateMut = useMutation({
    mutationFn: ({ id, payload }: { id: number | string; payload: any }) => updateCategory(id, payload),
    onSuccess: () => {
      toast({ title: 'Kategorie aktualizována', status: 'success', duration: 3000 });
      qc.invalidateQueries({ queryKey: ['admin-categories'] });
      closeModal();
    },
    onError: (e: any) =>
      toast({
        title: 'Aktualizace selhala',
        description: e?.response?.data?.chyba || e?.message || 'Chyba',
        status: 'error',
        duration: 5000,
      }),
  });

  const deleteMut = useMutation({
    mutationFn: (id: number | string) => deleteCategory(id),
    onSuccess: () => {
      toast({ title: 'Kategorie smazána', status: 'success', duration: 3000 });
      qc.invalidateQueries({ queryKey: ['admin-categories'] });
    },
    onError: (e: any) =>
      toast({
        title: 'Smazání selhalo',
        description: e?.response?.data?.chyba || e?.response?.data?.detail || e?.message || 'Chyba',
        status: 'error',
        duration: 5000,
      }),
  });

  const onSubmit = async () => {
    if (!editing) return;
    if (!editing.name?.trim()) {
      toast({ title: 'Název je povinný', status: 'warning' });
      return;
    }

    const payload = {
      name: editing.name.trim(),
      description: editing.description?.trim() || '',
    };

    if (editing.id != null) {
      await updateMut.mutateAsync({ id: editing.id, payload });
    } else {
      await createMut.mutateAsync(payload);
    }
  };

  const onDelete = async (cat: CategoryItem) => {
    if (!window.confirm(`Opravdu chcete smazat kategorii "${cat.name}"?`)) return;
    await deleteMut.mutateAsync(cat.id);
  };

  return (
    <AdminLayout requireAdmin={false}>
      <Box maxW="1200px" mx="auto">
        <PageHeader
          title="Kategorie článků"
          description="Spravujte kategorie pro články. Kategorie lze přiřadit při vytváření nebo úpravě článku."
          icon={FiTag}
          action={{
            label: 'Přidat kategorii',
            icon: <FiPlus />,
            onClick: openCreate,
            colorScheme: 'blue',
          }}
        />

        {isLoading ? (
          <VStack spacing={3}>
            {[1, 2, 3].map((i) => (
              <Skeleton key={i} height="60px" w="100%" borderRadius="md" />
            ))}
          </VStack>
        ) : !categories || categories.length === 0 ? (
          <Alert status="info" borderRadius="lg">
            <AlertIcon />
            <Box>
              <Text fontWeight="semibold">Zatím nejsou žádné kategorie</Text>
              <Text fontSize="sm">
                Kategorie se vytvoří automaticky při psaní článků, nebo je můžete vytvořit ručně.
              </Text>
            </Box>
          </Alert>
        ) : (
          <Box
            bg={bgCard}
            borderWidth="1px"
            borderColor={borderColor}
            borderRadius="xl"
            overflow="hidden"
            shadow="md"
          >
            <Table variant="simple" size="md">
              <Thead bg={useColorModeValue('gray.50', 'gray.700')}>
                <Tr>
                  <Th width="40%">Název</Th>
                  <Th width="50%">Popis</Th>
                  <Th isNumeric>Akce</Th>
                </Tr>
              </Thead>
              <Tbody>
                {categories.map((cat) => (
                  <Tr
                    key={cat.id}
                    _hover={{ bg: useColorModeValue('gray.50', 'gray.700') }}
                    transition="background 0.2s"
                  >
                    <Td>
                      <HStack>
                        <Badge colorScheme="blue" fontSize="sm" px={3} py={1} borderRadius="full">
                          {cat.name}
                        </Badge>
                      </HStack>
                    </Td>
                    <Td>
                      <Text fontSize="sm" color="gray.600" noOfLines={2}>
                        {cat.description || <Text as="span" fontStyle="italic" color="gray.400">Bez popisu</Text>}
                      </Text>
                    </Td>
                    <Td isNumeric>
                      <HStack justify="flex-end" spacing={2}>
                        <IconButton
                          aria-label="Upravit"
                          icon={<FiEdit2 />}
                          size="sm"
                          colorScheme="blue"
                          variant="ghost"
                          onClick={() => openEdit(cat)}
                        />
                        <IconButton
                          aria-label="Smazat"
                          icon={<FiTrash2 />}
                          size="sm"
                          colorScheme="red"
                          variant="ghost"
                          onClick={() => onDelete(cat)}
                          isLoading={deleteMut.isPending}
                        />
                      </HStack>
                    </Td>
                  </Tr>
                ))}
              </Tbody>
            </Table>
          </Box>
        )}

        {/* Create/Edit Modal */}
        <Modal isOpen={isOpen} onClose={closeModal} size="lg">
          <ModalOverlay />
          <ModalContent>
            <ModalHeader>
              {editing?.id ? 'Upravit kategorii' : 'Nová kategorie'}
            </ModalHeader>
            <ModalCloseButton />
            <ModalBody>
              <VStack spacing={4}>
                <FormControl isRequired>
                  <FormLabel>Název kategorie</FormLabel>
                  <Input
                    placeholder="např. Novinky, A-tým, Mládež..."
                    value={editing?.name || ''}
                    onChange={(e) => setEditing((prev) => ({ ...prev, name: e.target.value }))}
                    autoFocus
                  />
                </FormControl>
                <FormControl>
                  <FormLabel>Popis (volitelné)</FormLabel>
                  <Textarea
                    placeholder="Krátký popis kategorie..."
                    value={editing?.description || ''}
                    onChange={(e) => setEditing((prev) => ({ ...prev, description: e.target.value }))}
                    rows={3}
                  />
                </FormControl>
              </VStack>
            </ModalBody>
            <ModalFooter>
              <Button variant="ghost" mr={3} onClick={closeModal}>
                Zrušit
              </Button>
              <Button
                colorScheme="blue"
                onClick={onSubmit}
                isLoading={createMut.isPending || updateMut.isPending}
              >
                {editing?.id ? 'Uložit' : 'Vytvořit'}
              </Button>
            </ModalFooter>
          </ModalContent>
        </Modal>
      </Box>
    </AdminLayout>
  );
};

export default CategoriesAdminPage;
