import React from 'react';
import { Box, Image, Heading, Text, VStack, HStack, Badge, Skeleton, useColorModeValue, Button } from '@chakra-ui/react';
import { useQuery } from '@tanstack/react-query';
import { getArticles, Article } from '../../services/articles';
import HorizontalScroller from '../ui/HorizontalScroller';
import { Link as RouterLink } from 'react-router-dom';
import { useClubTheme } from '../../contexts/ClubThemeContext';
import { assetUrl } from '../../utils/url';
import { Eye, Clock } from 'lucide-react';

const Card: React.FC<{ a: Article }> = ({ a }) => {
  const cardBg = useColorModeValue('white', 'gray.800');
  const border = useColorModeValue('gray.200', 'whiteAlpha.300');
  const theme = useClubTheme();
  const link = a.slug ? `/news/${a.slug}` : `/articles/${a.id}`;
  const categoryBadgeColor = useColorModeValue('gray.100', 'whiteAlpha.200');
  const categoryName = (a as any)?.category?.name || '';
  
  return (
    <Box
      as={RouterLink}
      to={link}
      minW={{ base: '85%', md: '60%', lg: '33%' }}
      scrollSnapAlign="start"
      bg={cardBg}
      borderRadius="xl"
      overflow="hidden"
      boxShadow="lg"
      borderWidth="1px"
      borderColor={border}
      _hover={{ transform: 'translateY(-4px)', boxShadow: '2xl' }}
      transition="all 0.3s cubic-bezier(0.4, 0, 0.2, 1)"
      position="relative"
    >
      <Box position="relative" overflow="hidden">
        <Image 
          src={assetUrl(a.image_url) || '/stadium-placeholder.jpg'} 
          alt={a.title} 
          w="100%" 
          h={{ base: '200px', md: '240px' }} 
          objectFit="cover"
          transition="transform 0.3s ease"
          _groupHover={{ transform: 'scale(1.05)' }}
        />
        {categoryName && (
          <Badge 
            position="absolute" 
            top={3} 
            left={3} 
            colorScheme="blue"
            fontSize="xs"
            px={3}
            py={1}
            borderRadius="full"
            textTransform="uppercase"
            fontWeight="bold"
          >
            {categoryName}
          </Badge>
        )}
      </Box>
      <VStack align="stretch" spacing={3} p={5}>
        <Heading size="md" noOfLines={2} lineHeight="1.3">{a.title}</Heading>
        {a.content && (
          <Text fontSize="sm" color="gray.600" noOfLines={3} lineHeight="1.5">
            {a.content.replace(/<[^>]*>/g, '').trim()}
          </Text>
        )}
        <HStack spacing={3} pt={2} borderTopWidth="1px" borderColor={border} flexWrap="wrap">
          {(a.read_time || a.estimated_read_minutes) && (
            <HStack spacing={1}>
              <Clock size={14} color="gray" />
              <Text fontSize="xs" color="gray.500">
                {a.read_time || a.estimated_read_minutes} min
              </Text>
            </HStack>
          )}
          {a.view_count !== undefined && a.view_count > 0 && (
            <HStack spacing={1}>
              <Eye size={14} color="gray" />
              <Text fontSize="xs" color="gray.500">
                {a.view_count}
              </Text>
            </HStack>
          )}
          {a.published_at && (
            <Text fontSize="xs" color="gray.500">
              {new Date(a.published_at).toLocaleDateString('cs-CZ')}
            </Text>
          )}
        </HStack>
      </VStack>
    </Box>
  );
};

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

  const list: Article[] = data?.data || [];

  return (
    <Box>
      <HorizontalScroller
        title="Novinky"
        rightAction={<Button as={RouterLink} to="/blog" variant="link" color="brand.primary">Více</Button>}
      >
        {isLoading && Array.from({ length: 4 }).map((_, i) => (
          <Skeleton key={i} minW={{ base: '85%', md: '60%', lg: '33%' }} h={{ base: '260px', md: '300px' }} borderRadius="xl" />
        ))}
        {!isLoading && list.map((a) => (
          <Card key={a.id} a={a} />
        ))}
      </HorizontalScroller>
    </Box>
  );
};

export default BlogCardsScroller;
