import React from 'react';
import {
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalCloseButton,
  ModalBody,
  ModalFooter,
  Button,
  VStack,
  HStack,
  Text,
  Badge,
  Icon,
  useColorModeValue,
  Spinner,
} from '@chakra-ui/react';
import { useQuery } from '@tanstack/react-query';
import { getAchievements } from '../../services/engagement';
import { CheckCircle, Circle } from 'lucide-react';

export type AchievementsModalProps = {
  isOpen: boolean;
  onClose: () => void;
  onOpenRewards?: () => void;
};

const AchievementsModal: React.FC<AchievementsModalProps> = ({ isOpen, onClose, onOpenRewards }) => {
  const cardBg = useColorModeValue('gray.50', 'gray.800');
  const q = useQuery({
    queryKey: ['engagement', 'achievements'],
    queryFn: getAchievements,
    enabled: isOpen,
    staleTime: 10000,
  });

  const items = q.data?.achievements || [];
  const counters = q.data?.counters || {} as any;

  return (
    <Modal isOpen={isOpen} onClose={onClose} size="lg">
      <ModalOverlay />
      <ModalContent>
        <ModalHeader>Úspěchy</ModalHeader>
        <ModalCloseButton />
        <ModalBody>
          {q.isLoading ? (
            <HStack><Spinner size="sm" /><Text>Načítám…</Text></HStack>
          ) : (
            <VStack align="stretch" spacing={3}>
              <HStack spacing={3} bg={cardBg} p={3} borderRadius="md">
                <Badge colorScheme="blue">Komentáře: {counters?.comments ?? 0}</Badge>
                <Badge colorScheme="green">Hlasování: {counters?.votes ?? 0}</Badge>
                <Badge colorScheme={counters?.newsletter ? 'purple' : 'gray'}>Newsletter: {counters?.newsletter ? 'ANO' : 'NE'}</Badge>
              </HStack>
              {items.map((a: any) => (
                <HStack key={a.id} spacing={3} p={2} borderWidth="1px" borderRadius="md">
                  <Icon as={a.achieved ? CheckCircle : Circle} color={a.achieved ? 'green.400' : 'gray.400'} />
                  <VStack align="start" spacing={0} flex={1}>
                    <Text fontWeight="600">{a.title}</Text>
                    <Text fontSize="sm" color="gray.500">{a.description}</Text>
                  </VStack>
                  <Badge>{a.points} bodů</Badge>
                </HStack>
              ))}
            </VStack>
          )}
        </ModalBody>
        <ModalFooter>
          {onOpenRewards && (
            <Button mr={3} onClick={() => { onClose(); onOpenRewards(); }} colorScheme="blue">Odměny</Button>
          )}
          <Button variant="ghost" onClick={onClose}>Zavřít</Button>
        </ModalFooter>
      </ModalContent>
    </Modal>
  );
};

export default AchievementsModal;
