import React, { useState, useCallback, useMemo, useEffect } from 'react';
import { Box, Image, Heading, Text, VStack, HStack, Skeleton, Button, IconButton, Flex, Container } from '@chakra-ui/react';
import { useQuery } from '@tanstack/react-query';
import { getArticles, getFeaturedArticles, Article } from '../../services/articles';
import { Link as RouterLink } from 'react-router-dom';
import { assetUrl } from '../../utils/url';
import { ChevronLeftIcon, ChevronRightIcon } from '@chakra-ui/icons';
import { useClubTheme } from '../../contexts/ClubThemeContext';
import { motion, AnimatePresence } from 'framer-motion';
import { wrap } from 'popmotion';

const MotionBox = motion(Box);
const MotionImage = motion(Image);

type FallbackArticle = Partial<Article> & {
  id?: number | string;
  title: string;
  excerpt?: string;
  image?: string;
  date?: string;
};

interface BlogSwiperProps {
  fallbackArticles?: FallbackArticle[];
}

const variants = {
  enter: (direction: number) => ({
    x: direction > 0 ? 1000 : -1000,
    opacity: 0
  }),
  center: {
    zIndex: 1,
    x: 0,
    opacity: 1
  },
  exit: (direction: number) => ({
    zIndex: 0,
    x: direction < 0 ? 1000 : -1000,
    opacity: 0
  })
};

const swipeConfidenceThreshold = 10000;
const swipePower = (offset: number, velocity: number) => {
  return Math.abs(offset) * velocity;
};

const HeroSlide: React.FC<{ article: Article }> = ({ article }) => {
  const theme = useClubTheme();
  const excerpt = (article.content || '').replace(/<[^>]*>/g, '').slice(0, 200) + '...';
  const link = article.slug ? `/news/${article.slug}` : `/articles/${article.id}`;
  
  return (
    <Box
      position="relative"
      w="100%"
      h={{ base: '500px', md: '600px' }}
      overflow="hidden"
      borderRadius={{ base: 'none', md: 'xl' }}
      boxShadow="lg"
    >
      <MotionImage
        src={assetUrl(article.image_url) || '/stadium-placeholder.jpg'}
        alt={article.title}
        w="100%"
        h="100%"
        objectFit="cover"
        initial={{ opacity: 0.7 }}
        animate={{ opacity: 1 }}
        transition={{ duration: 0.5 }}
      />
      <Box
        position="absolute"
        bottom={0}
        left={0}
        right={0}
        p={{ base: 6, md: 10 }}
        bgGradient="linear(to-t, blackAlpha.900, blackAlpha.700, transparent)"
        color="white"
      >
        <Container maxW="7xl" px={{ base: 4, md: 6 }}>
          {/* Top-left BLOG link badge */}
          <HStack spacing={3} mb={4}>
            <Button
              as={RouterLink}
              to="/blog"
              size="sm"
              px={3}
              height="28px"
              borderRadius="full"
              bg={theme.primary}
              color="white"
              _hover={{ bg: theme.accent }}
            >
              BLOG
            </Button>
            <Text fontSize={{ base: 'xs', md: 'sm' }} opacity={0.85}>•</Text>
            <Text fontSize={{ base: 'xs', md: 'sm' }} opacity={0.85}>Klubové aktuality</Text>
          </HStack>

          <Box maxW={{ base: '100%', md: '70%', lg: '55%' }}>
            <Text 
              fontSize={{ base: 'sm', md: 'md' }} 
              fontWeight="bold" 
              color={theme.accent} 
              textTransform="uppercase" 
              letterSpacing="0.1em"
              mb={2}
            >
              Nejnovější aktualita
            </Text>
            <Heading 
              as="h2" 
              size={{ base: 'xl', md: '2xl', lg: '3xl' }} 
              mb={4}
              lineHeight="1.2"
              textShadow="0 2px 4px rgba(0,0,0,0.5)"
            >
              {article.title}
            </Heading>
            <Text 
              fontSize={{ base: 'sm', md: 'md' }} 
              noOfLines={3} 
              mb={6}
              textShadow="0 1px 2px rgba(0,0,0,0.5)"
            >
              {excerpt}
            </Text>
            <HStack spacing={4}>
              <Button 
                as={RouterLink} 
                to={link}
                size="lg"
                bg={theme.primary}
                color="white"
                rightIcon={<ChevronRightIcon />}
                _hover={{
                  bg: theme.accent,
                  transform: 'translateY(-2px)',
                  boxShadow: 'lg',
                }}
              >
                Číst více
              </Button>
              <Button
                as={RouterLink}
                to="/blog"
                size="lg"
                variant="outline"
                borderColor="whiteAlpha.700"
                color="white"
                _hover={{ bg: 'whiteAlpha.200' }}
              >
                Všechny články
              </Button>
            </HStack>
          </Box>
        </Container>
      </Box>
    </Box>
  );
};

const BlogSwiper: React.FC<BlogSwiperProps> = ({ fallbackArticles = [] }) => {
  const [[slideIndex, direction], setSlideIndex] = useState([0, 0]);
  const { data: featuredData, isLoading: loadingFeatured } = useQuery({
    queryKey: ['featured-articles', { page: 1, page_size: 5 }],
    queryFn: () => getFeaturedArticles({ page: 1, page_size: 5 }),
  });
  // Fallback to latest published if no featured are available
  const { data: latestData } = useQuery({
    queryKey: ['latest-articles', { page: 1, page_size: 5, published: true }],
    queryFn: () => getArticles({ page: 1, page_size: 5, published: true }),
    enabled: Boolean(!loadingFeatured && !(featuredData?.data?.length)),
  });

  const normalizedFallback = useMemo<Article[]>(() => fallbackArticles.map((item, index) => ({
    id: typeof item.id === 'number' ? item.id : index,
    title: item.title,
    content: item.content ?? item.excerpt ?? '',
    image_url: item.image_url ?? item.image ?? undefined,
    author: item.author,
    category: typeof item.category === 'string' ? { id: index, name: item.category } : item.category,
    category_name: typeof item.category === 'string' ? item.category : item.category_name,
    slug: item.slug,
    created_at: item.created_at ?? item.published_at ?? item.date ?? new Date().toISOString(),
    published: item.published ?? true,
  })), [fallbackArticles]);

  const remoteArticles = useMemo<Article[]>(() => {
    if (featuredData?.data?.length) {
      return featuredData.data;
    }
    if (latestData?.data?.length) {
      return latestData.data;
    }
    return [];
  }, [featuredData?.data, latestData?.data]);

  const articles = remoteArticles.length ? remoteArticles : normalizedFallback;
  const articleCount = articles.length;
  const articleIndex = articleCount > 0 ? wrap(0, articleCount, slideIndex) : 0;
  const paginate = useCallback(
    (newDirection: number) => {
      setSlideIndex([slideIndex + newDirection, newDirection]);
    },
    [slideIndex]
  );

  // Auto-advance slides
  useEffect(() => {
    if (articleCount <= 1) return;

    const timer = setInterval(() => {
      paginate(1);
    }, 8000);

    return () => clearInterval(timer);
  }, [articleCount, paginate]);

  useEffect(() => {
    if (articleCount === 0 && slideIndex !== 0) {
      setSlideIndex([0, 0]);
    } else if (articleIndex >= articleCount && articleCount > 0) {
      setSlideIndex([0, 0]);
    }
  }, [articleCount, articleIndex, slideIndex]);

  const isLoading = loadingFeatured && !remoteArticles.length && !normalizedFallback.length;

  if (isLoading) {
    return (
      <Skeleton 
        w="100%" 
        h={{ base: '500px', md: '600px' }} 
        borderRadius={{ base: 'none', md: 'xl' }}
      />
    );
  }

  if (!articleCount) {
    return (
      <Box
        position="relative"
        w="100%"
        h={{ base: '480px', md: '560px' }}
        borderRadius={{ base: 'none', md: 'xl' }}
        bgGradient="linear(to-br, blackAlpha.600, blackAlpha.800)"
        display="flex"
        alignItems="center"
        justifyContent="center"
        color="whiteAlpha.800"
        textAlign="center"
        px={8}
      >
        <VStack spacing={4}>
          <Heading size="lg">Žádné články k zobrazení</Heading>
          <Text maxW="lg">
            Přidejte prosím nové články nebo nastavte vybrané příspěvky, aby se karusel mohl zobrazit.
          </Text>
        </VStack>
      </Box>
    );
  }

  const currentArticle = articles[articleIndex];
  if (!currentArticle) {
    return null;
  }

  return (
    <Box position="relative" w="100%" overflow="hidden">
      <AnimatePresence initial={false} custom={direction}>
        <MotionBox
          key={slideIndex}
          custom={direction}
          variants={variants}
          initial="enter"
          animate="center"
          exit="exit"
          transition={{
            x: { type: 'spring', stiffness: 300, damping: 30 },
            opacity: { duration: 0.2 }
          }}
          drag="x"
          dragConstraints={{ left: 0, right: 0 }}
          dragElastic={1}
          onDragEnd={(e, { offset, velocity }) => {
            const swipe = swipePower(offset.x, velocity.x);
            if (swipe < -swipeConfidenceThreshold) {
              paginate(1);
            } else if (swipe > swipeConfidenceThreshold) {
              paginate(-1);
            }
          }}
          position="relative"
          w="100%"
          h="100%"
        >
          <HeroSlide article={currentArticle} />
        </MotionBox>
      </AnimatePresence>

      {articles.length > 1 && (
        <>
          <IconButton
            aria-label="Předchozí slide"
            icon={<ChevronLeftIcon />}
            position="absolute"
            left={4}
            top="50%"
            transform="translateY(-50%)"
            zIndex={2}
            borderRadius="full"
            colorScheme="blackAlpha"
            onClick={() => paginate(-1)}
            size="lg"
          />
          <IconButton
            aria-label="Další slide"
            icon={<ChevronRightIcon />}
            position="absolute"
            right={4}
            top="50%"
            transform="translateY(-50%)"
            zIndex={2}
            borderRadius="full"
            colorScheme="blackAlpha"
            onClick={() => paginate(1)}
            size="lg"
          />
          <Flex
            position="absolute"
            bottom={8}
            left="50%"
            transform="translateX(-50%)"
            zIndex={2}
            gap={2}
          >
            {articles.map((_, index) => (
              <Box
                key={index}
                as="button"
                px={2}
                h="20px"
                display="flex"
                alignItems="center"
                justifyContent="center"
                fontSize="xs"
                fontWeight="700"
                color={index === articleIndex ? 'black' : 'white'}
                bg={index === articleIndex ? 'white' : 'whiteAlpha.500'}
                borderRadius="sm"
                onClick={() => setSlideIndex([index, index > articleIndex ? 1 : -1])}
                transition="all 0.3s"
                _hover={{
                  bg: 'white',
                  color: 'black',
                }}
              >
                {String(index + 1).padStart(2, '0')}
              </Box>
            ))}
          </Flex>
        </>
      )}
    </Box>
  );
};

export default BlogSwiper;
