import { Box, Container, Heading, Image, SimpleGrid, Spinner, Stack, Text, VStack, useColorModeValue } from '@chakra-ui/react';
import { useQuery } from '@tanstack/react-query';
import { getPlayers } from '../services/public';
import { assetUrl } from '../utils/url';
import { Link as RouterLink } from 'react-router-dom';
import MainLayout from '../components/layout/MainLayout';
import SponsorsSection from '../components/common/SponsorsSection';
import NewsletterCTA from '../components/common/NewsletterCTA';

const PlayersPage: React.FC = () => {
  const { data, isLoading, isError } = useQuery({ queryKey: ['players'], queryFn: getPlayers });
  const cardBg = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.700');
  const textSecondary = useColorModeValue('gray.600', 'gray.400');

  if (isLoading) {
    return (
      <MainLayout>
        <Container maxW="7xl" py={8}>
          <Spinner />
        </Container>
      </MainLayout>
    );
  }

  if (isError) {
    return (
      <MainLayout>
        <Container maxW="7xl" py={8}>
          <Text color="red.500">Chyba při načítání hráčů</Text>
        </Container>
      </MainLayout>
    );
  }

  return (
    <MainLayout>
      <Box>
        <Container maxW="7xl" py={{ base: 6, md: 10 }}>
          <VStack align="stretch" spacing={6}>
            <Heading as="h1" size={{ base: 'xl', md: '2xl' }}>Hráči</Heading>
            <SimpleGrid columns={{ base: 1, sm: 2, md: 3, lg: 4 }} spacing={6}>
              {data?.map((p) => (
                <Stack
                  key={p.id}
                  as={RouterLink}
                  to={`/hraci/${p.id}`}
                  borderWidth="1px"
                  borderColor={borderColor}
                  borderRadius="lg"
                  p={4}
                  bg={cardBg}
                  _hover={{ boxShadow: 'lg', transform: 'translateY(-4px)' }}
                  transition="all 0.2s ease"
                  spacing={3}
                >
                  <Image 
                    src={assetUrl(p.image_url) || '/logo512.png'} 
                    alt={`${p.first_name} ${p.last_name}`} 
                    objectFit="cover" 
                    borderRadius="md"
                    w="100%"
                    h="240px"
                  />
                  <Text fontWeight="bold" fontSize="lg">{p.first_name} {p.last_name}</Text>
                  <Text color={textSecondary}>{p.position}</Text>
                  {p.jersey_number ? (
                    <Text color="brand.primary" fontWeight="600">#{p.jersey_number}</Text>
                  ) : null}
                </Stack>
              ))}
            </SimpleGrid>
          </VStack>
        </Container>
        
        {/* Newsletter CTA */}
        <NewsletterCTA />
        
        {/* Sponsors Section */}
        <SponsorsSection />
      </Box>
    </MainLayout>
  );
}

export default PlayersPage;
