import React from 'react';
import { Box, HStack, Image, Skeleton, useBreakpointValue, Tooltip } from '@chakra-ui/react';
import { useQuery } from '@tanstack/react-query';
import { getArticles, Article } from '../../services/articles';
import { Link as RouterLink } from 'react-router-dom';
import { assetUrl } from '../../utils/url';

const modulo = (n: number, m: number) => ((n % m) + m) % m;

const BlogThumbStrip: React.FC = () => {
  const { data, isLoading } = useQuery({
    queryKey: ['thumb-articles', { page: 1, page_size: 12, published: true }],
    queryFn: () => getArticles({ page: 1, page_size: 12, published: true }),
  });

  const articles = data?.data?.filter(a => !!a.image_url) || [];
  const visible = useBreakpointValue({ base: 2, md: 3, lg: 5 }) || 5;

  const [index, setIndex] = React.useState(0);
  const [paused, setPaused] = React.useState(false);

  React.useEffect(() => {
    if (articles.length <= visible) return;
    const id = setInterval(() => {
      if (!paused) setIndex((i) => i + 1);
    }, 3000);
    return () => clearInterval(id);
  }, [articles.length, visible, paused]);

  if (isLoading) {
    return (
      <HStack spacing={3}>
        {Array.from({ length: visible }).map((_, i) => (
          <Skeleton key={i} w={{ base: '50%', md: `${100/visible}%` }} h={{ base: '90px', md: '120px', lg: '140px' }} borderRadius="md" />
        ))}
      </HStack>
    );
  }

  if (!articles.length) return null;

  const items = Array.from({ length: visible }).map((_, i) => {
    const idx = modulo(index + i, articles.length);
    return articles[idx];
  });

  return (
    <Box
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
    >
      <HStack spacing={3}>
        {items.map((a: Article) => (
          <Box
            key={a.id}
            as={RouterLink}
            to={a.slug ? `/news/${a.slug}` : `/articles/${a.id}`}
            flex={`0 0 ${100/visible}%`}
            position="relative"
            borderRadius="md"
            overflow="hidden"
            _hover={{ transform: 'translateY(-2px)', boxShadow: 'lg' }}
            transition="all 0.25s ease"
          >
            <Image
              src={assetUrl(a.image_url) || '/stadium-placeholder.jpg'}
              alt={a.title}
              w="100%"
              h={{ base: '90px', md: '120px', lg: '140px' }}
              objectFit="cover"
            />
            <Box position="absolute" bottom={0} left={0} right={0} h="36px" bgGradient="linear(to-t, blackAlpha.700, transparent)" />
            <Tooltip label={a.title} openDelay={300}>
              <Box position="absolute" bottom={1} left={2} right={2} color="white" fontSize="xs" noOfLines={1}>
                {a.title}
              </Box>
            </Tooltip>
          </Box>
        ))}
      </HStack>
    </Box>
  );
};

export default BlogThumbStrip;
