import { Box, SimpleGrid, Heading, Text, useColorModeValue, HStack, Button, Link, Badge } from '@chakra-ui/react';
import { useEffect, useState } from 'react';
import { getClothing, ClothingItem } from '../../services/clothing';
import { Link as RouterLink } from 'react-router-dom';

const MerchSection: React.FC = () => {
  const [items, setItems] = useState<ClothingItem[]>([]);
  const [loading, setLoading] = useState(true);
  const cardBg = useColorModeValue('white', 'gray.800');

  useEffect(() => {
    const fetchItems = async () => {
      try {
        const data = await getClothing();
        // Show only 5 newest items on homepage
        setItems(data.slice(0, 5));
      } catch (e) {
        console.error('Failed to fetch clothing items:', e);
      } finally {
        setLoading(false);
      }
    };

    fetchItems();
  }, []);

  if (loading || items.length === 0) return null;

  return (
    <Box>
      <HStack justify="space-between" mb={3}>
        <Heading as="h3" size="md">Oblečení týmu</Heading>
        <Link as={RouterLink} to="/obleceni">
          <Button size="sm" variant="outline" colorScheme="blue">Zobrazit vše</Button>
        </Link>
      </HStack>
      <SimpleGrid columns={{ base: 2, md: 3, lg: 5 }} spacing={4}>
        {items.map((it) => (
          <a 
            key={it.id} 
            href={it.url || '/obleceni'} 
            target={it.url ? "_blank" : undefined}
            rel={it.url ? "noreferrer noopener" : undefined}
          >
            <Box 
              bg={cardBg} 
              borderRadius="xl" 
              overflow="hidden" 
              boxShadow="sm" 
              borderWidth="1px"
              transition="all 0.2s"
              _hover={{ transform: 'translateY(-4px)', boxShadow: 'md' }}
            >
              <Box
                aria-hidden
                height={{ base: 140, md: 180 }}
                bgSize="cover"
                bgPos="center"
                style={{ backgroundImage: `url(${it.image_url})` }}
              />
              <Box p={3} borderTopWidth="1px">
                <Text noOfLines={1} fontWeight="semibold" fontSize="sm">{it.title}</Text>
                {it.price && it.price > 0 && (
                  <Badge colorScheme="blue" mt={1} fontSize="xs">
                    {it.price} {it.currency || 'Kč'}
                  </Badge>
                )}
              </Box>
            </Box>
          </a>
        ))}
      </SimpleGrid>
    </Box>
  );
};

export default MerchSection;
