import React from 'react';
import {
  Box,
  VStack,
  Heading,
  Text,
  Spinner,
  Alert,
  AlertIcon,
  useColorModeValue,
} from '@chakra-ui/react';
import { useQuery } from '@tanstack/react-query';
import { getPolls, getPoll } from '../../services/polls';
import PollCard from '../polls/PollCard';

interface PollsWidgetProps {
  featuredOnly?: boolean;
  maxPolls?: number;
  title?: string;
}

const PollsWidget: React.FC<PollsWidgetProps> = ({
  featuredOnly = true,
  maxPolls = 1,
  title = 'Hlasování',
}) => {
  const bgSection = useColorModeValue('gray.50', 'gray.900');

  // Fetch polls list
  const { data: polls, isLoading } = useQuery({
    queryKey: ['polls', { featured: featuredOnly }],
    queryFn: () => getPolls(featuredOnly ? { featured: true } : undefined),
    staleTime: 2 * 60 * 1000, // 2 minutes
  });

  // Get full poll data for each featured poll
  const pollsToDisplay = polls?.slice(0, maxPolls) || [];

  const { data: pollsData, isLoading: isLoadingPolls } = useQuery({
    queryKey: ['polls-details', pollsToDisplay.map((p) => p.id)],
    queryFn: async () => {
      const promises = pollsToDisplay.map((poll) => getPoll(poll.id));
      return await Promise.all(promises);
    },
    enabled: pollsToDisplay.length > 0,
  });

  if (isLoading || isLoadingPolls) {
    return (
      <Box bg={bgSection} py={12} px={4}>
        <VStack spacing={4}>
          <Spinner size="lg" />
          <Text>Načítání ankety...</Text>
        </VStack>
      </Box>
    );
  }

  if (!pollsData || pollsData.length === 0) {
    return null; // Don't show widget if no polls
  }

  return (
    <Box bg={bgSection} py={12} px={4}>
      <VStack spacing={8} maxW="4xl" mx="auto">
        <Heading size="lg" textAlign="center">
          {title}
        </Heading>

        <VStack spacing={6} w="full">
          {pollsData.map((pollResponse) => (
            <Box key={pollResponse.poll.id} w="full" maxW="600px">
              <PollCard
                poll={pollResponse.poll}
                hasVoted={pollResponse.has_voted}
                isActive={pollResponse.is_active}
                canShowResults={pollResponse.can_show_results}
              />
            </Box>
          ))}
        </VStack>
      </VStack>
    </Box>
  );
};

export default PollsWidget;
