import React, { useState } from 'react';
import {
  Box,
  Container,
  Heading,
  VStack,
  SimpleGrid,
  Spinner,
  Text,
  Alert,
  AlertIcon,
  Tabs,
  TabList,
  TabPanels,
  Tab,
  TabPanel,
  Badge,
  useColorModeValue,
} from '@chakra-ui/react';
import { useQuery } from '@tanstack/react-query';
import MainLayout from '../components/layout/MainLayout';
import PollCard from '../components/polls/PollCard';
import { getPolls, getPoll } from '../services/polls';

const PollsPage: React.FC = () => {
  const [tabIndex, setTabIndex] = useState(0);
  const bgSection = useColorModeValue('white', 'gray.800');

  // Fetch all active polls
  const { data: polls, isLoading } = useQuery({
    queryKey: ['polls'],
    queryFn: () => getPolls(),
    staleTime: 2 * 60 * 1000,
  });

  // Get full data for each poll
  const { data: pollsData, isLoading: isLoadingPolls } = useQuery({
    queryKey: ['polls-details', polls?.map((p) => p.id)],
    queryFn: async () => {
      if (!polls || polls.length === 0) return [];
      const promises = polls.map((poll) => getPoll(poll.id));
      return await Promise.all(promises);
    },
    enabled: !!polls && polls.length > 0,
  });

  // Filter polls
  const featuredPolls = pollsData?.filter((p) => p.poll.featured) || [];
  const activePolls = pollsData?.filter((p) => p.is_active) || [];
  const allPolls = pollsData || [];

  if (isLoading || isLoadingPolls) {
    return (
      <MainLayout>
        <Container maxW="7xl" py={8}>
          <VStack spacing={4}>
            <Spinner size="xl" />
            <Text>Načítání anket...</Text>
          </VStack>
        </Container>
      </MainLayout>
    );
  }

  if (!polls || polls.length === 0) {
    return (
      <MainLayout>
        <Container maxW="7xl" py={8}>
          <VStack spacing={6} align="stretch">
            <Heading size="xl">Ankety a hlasování</Heading>
            <Alert status="info">
              <AlertIcon />
              Momentálně nejsou k dispozici žádné ankety. Brzy přidáme nové!
            </Alert>
          </VStack>
        </Container>
      </MainLayout>
    );
  }

  return (
    <MainLayout>
      <Box bg={bgSection} minH="100vh">
        <Container maxW="7xl" py={8}>
          <VStack spacing={8} align="stretch">
            <VStack spacing={2} align="start">
              <Heading size="xl">Ankety a hlasování</Heading>
              <Text color="gray.600">
                Hlasujte v anketách a podělte se o svůj názor s ostatními fanoušky!
              </Text>
            </VStack>

            <Tabs index={tabIndex} onChange={setTabIndex} colorScheme="blue">
              <TabList>
                <Tab>
                  Všechny
                  {allPolls.length > 0 && (
                    <Badge ml={2} colorScheme="blue">
                      {allPolls.length}
                    </Badge>
                  )}
                </Tab>
                <Tab>
                  Aktivní
                  {activePolls.length > 0 && (
                    <Badge ml={2} colorScheme="green">
                      {activePolls.length}
                    </Badge>
                  )}
                </Tab>
                {featuredPolls.length > 0 && (
                  <Tab>
                    Zvýrazněné
                    <Badge ml={2} colorScheme="purple">
                      {featuredPolls.length}
                    </Badge>
                  </Tab>
                )}
              </TabList>

              <TabPanels>
                {/* All Polls */}
                <TabPanel>
                  <SimpleGrid columns={{ base: 1, md: 2, lg: 3 }} spacing={6}>
                    {allPolls.map((pollResponse) => (
                      <PollCard
                        key={pollResponse.poll.id}
                        poll={pollResponse.poll}
                        hasVoted={pollResponse.has_voted}
                        isActive={pollResponse.is_active}
                        canShowResults={pollResponse.can_show_results}
                      />
                    ))}
                  </SimpleGrid>
                </TabPanel>

                {/* Active Polls */}
                <TabPanel>
                  {activePolls.length > 0 ? (
                    <SimpleGrid columns={{ base: 1, md: 2, lg: 3 }} spacing={6}>
                      {activePolls.map((pollResponse) => (
                        <PollCard
                          key={pollResponse.poll.id}
                          poll={pollResponse.poll}
                          hasVoted={pollResponse.has_voted}
                          isActive={pollResponse.is_active}
                          canShowResults={pollResponse.can_show_results}
                        />
                      ))}
                    </SimpleGrid>
                  ) : (
                    <Alert status="info">
                      <AlertIcon />
                      Momentálně nejsou k dispozici žádné aktivní ankety.
                    </Alert>
                  )}
                </TabPanel>

                {/* Featured Polls */}
                {featuredPolls.length > 0 && (
                  <TabPanel>
                    <SimpleGrid columns={{ base: 1, md: 2, lg: 3 }} spacing={6}>
                      {featuredPolls.map((pollResponse) => (
                        <PollCard
                          key={pollResponse.poll.id}
                          poll={pollResponse.poll}
                          hasVoted={pollResponse.has_voted}
                          isActive={pollResponse.is_active}
                          canShowResults={pollResponse.can_show_results}
                        />
                      ))}
                    </SimpleGrid>
                  </TabPanel>
                )}
              </TabPanels>
            </Tabs>
          </VStack>
        </Container>
      </Box>
    </MainLayout>
  );
};

export default PollsPage;
