import { useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Box, Button, FormControl, FormLabel, Heading, Input, Switch, Textarea, VStack, Image, Text, HStack } from '@chakra-ui/react';
import { createArticle, uploadFile } from '../services/articles';
import { useNavigate } from 'react-router-dom';

const ArticleCreatePage: React.FC = () => {
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [published, setPublished] = useState(true);
  const [imageUrl, setImageUrl] = useState<string | undefined>(undefined);
  const [uploading, setUploading] = useState(false);
  const navigate = useNavigate();
  const qc = useQueryClient();

  const createMut = useMutation({
    mutationFn: () => createArticle({ title, content, published, image_url: imageUrl }),
    onSuccess: (data) => {
      qc.invalidateQueries({ queryKey: ['articles'] });
      navigate(`/articles/${data.id}`);
    },
  });

  const onUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    try {
      const res = await uploadFile(file);
      setImageUrl(res.url);
    } catch (e) {
      console.error(e);
    } finally {
      setUploading(false);
    }
  };

  const canSubmit = title.trim().length > 0 && content.trim().length > 0 && !createMut.isLoading;

  return (
    <VStack align="stretch" spacing={4}>
      <Heading size="lg">Nový článek</Heading>

      <FormControl isRequired>
        <FormLabel>Nadpis</FormLabel>
        <Input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Zadejte nadpis" />
      </FormControl>

      <FormControl isRequired>
        <FormLabel>Obsah</FormLabel>
        <Textarea value={content} onChange={(e) => setContent(e.target.value)} rows={10} placeholder="Text článku" />
      </FormControl>

      <FormControl>
        <FormLabel>Obrázek</FormLabel>
        <HStack align="start" spacing={4}>
          <Input type="file" accept="image/*,application/pdf" onChange={onUpload} isDisabled={uploading} />
          {uploading && <Text>Uploaduji...</Text>}
        </HStack>
        {imageUrl && (
          <Box mt={2}>
            <Image src={imageUrl} alt="náhled" maxH="160px" objectFit="cover" borderRadius="md" />
            <Text fontSize="sm" color="gray.500">{imageUrl}</Text>
          </Box>
        )}
      </FormControl>

      <FormControl display="flex" alignItems="center">
        <FormLabel htmlFor="published" mb="0">Publikovat</FormLabel>
        <Switch id="published" isChecked={published} onChange={(e) => setPublished(e.target.checked)} />
      </FormControl>

      <Button colorScheme="brand" onClick={() => createMut.mutate()} isDisabled={!canSubmit} isLoading={createMut.isLoading}>
        Uložit
      </Button>
    </VStack>
  );
};

export default ArticleCreatePage;
