import { Box, Button, Heading, HStack, Image, Link as ChakraLink, Spinner, Stack, Text } from '@chakra-ui/react';
import { useQuery } from '@tanstack/react-query';
import { Link } from 'react-router-dom';
import { getArticles } from '../services/articles';

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

  if (isLoading) return <Spinner />;
  if (isError) return <Text color="red.500">Chyba při načítání článků</Text>;

  return (
    <Stack spacing={6}>
      <HStack justify="space-between">
        <Heading size="lg">Články</Heading>
        <Button as={Link} colorScheme="brand" to="/articles/create">Nový článek</Button>
      </HStack>
      <Stack spacing={4}>
        {data?.data.map((a) => (
          <HStack key={a.id} align="start" spacing={4} borderWidth="1px" borderRadius="md" p={4} bg="white">
            <Image src={a.image_url || '/logo192.png'} alt={a.title} boxSize="100px" objectFit="cover" borderRadius="md" />
            <Box>
              <ChakraLink as={Link} to={`/articles/${a.id}`} fontWeight="bold" fontSize="lg">{a.title}</ChakraLink>
              <Text noOfLines={3} mt={2}>{a.content}</Text>
            </Box>
          </HStack>
        ))}
      </Stack>
    </Stack>
  );
};

export default ArticlesListPage;
