import React, {useEffect, useState} from "react";
import "../../index.css";
import {Button, FormControl, HStack, Input, Select, Stack, Text, useToast,} from "@chakra-ui/react";
import TextBoxBlog from "./TextBoxBlog";
import {gql, useMutation, useQuery} from "@apollo/client";
import {convertToRaw, EditorState} from "draft-js";
import draftToHtml from 'draftjs-to-html';
import {stateFromHTML} from 'draft-js-import-html';
import {GET_POSTS} from "./BlogsTable";
import TopBar from "./TopBar";

interface inputProps {
    title: string;
    OnChange: any;
}

export const GET_POST_CATEGORY = gql`query {
  post_category {
    id
    name
  }
}
`;
export const ADD_POST = gql`mutation ($object: posts_insert_input!) {
  insert_posts_one(object: $object) {
    id
    title
    category_id
    body
    date
  }
}`;
export const UPDATE_POST = gql`mutation ($object: posts_set_input!, $id: Int!) {
  update_posts_by_pk(pk_columns: {id: $id}, _set: $object) {
    id
    date
    title
    post_category {
      id
      name
    }
    body
    category_id
  }
}`;

const initValues = {
    title: "",
    body: "",
    category_id: "",
    date: "",
    isUpdate: false,
};

const CreateBlog = (props: any) => {
    const {goBack, post} = props;
    const [state, setState] = useState(initValues);
    const [isLoading, setIsLoading] = useState(false);
    const toast = useToast();
    const [editorState, setEditorState] = useState(EditorState.createEmpty());
    useEffect(() => {
        if (post) {
            setState({
                title: post.title,
                body: post.body,
                category_id: post.category_id,
                date: post.date,
                isUpdate: true,
            });
            let contentState = stateFromHTML(post.body);
            setEditorState(EditorState.createWithContent(contentState));
        }
    }, [post]);

    const {
        data: categoryData
    } = useQuery(GET_POST_CATEGORY);

    let options: any = [];
    if (categoryData) {
        options = categoryData?.post_category.map((cat: any) => {
            return {
                value: cat.id,
                name: cat.name
            }
        });
    }
    const [addPost] = useMutation(ADD_POST);
    const [updatePost] = useMutation(UPDATE_POST);
    const handleInputChange = (e: any) => {
        const {name, value} = e.target;
        const post_values: any = state;
        post_values[name] = value;
        setState((prevState) => {
            return {...prevState, ...post_values};
        });
    };
    const handleRTEChange = (editorState: any) => {
        setEditorState(editorState);
        const post_values: any = state;
        post_values.body = draftToHtml(convertToRaw(editorState.getCurrentContent()));
        setState((prevState) => {
            return {...prevState, ...post_values};
        });
    };
    const handleSubmit = () => {
        if (state.body === "") {
            return toast({
                title: "Post body can not be empty!",
                status: "error",
                isClosable: true,
            });
        }
        setIsLoading(true);
        const options: any = {
            variables: {
                object: {
                    title: state.title,
                    body: state.body,
                    category_id: parseInt(state.category_id),
                    date: state.date,
                }
            },
        };
        options["refetchQueries"] = [
            {query: GET_POSTS},
        ];
        if (state.isUpdate) {
            options.variables["id"] = post.id;
            options["optimisticResponse"] = true;
            updatePost(options).then(data => {
                toast({
                    title: `Post updated`,
                    status: "success",
                    isClosable: true,
                });
                setIsLoading(false);
            }).catch(error => {
                toast({
                    title: error,
                    status: "error",
                    isClosable: true,
                });
                setIsLoading(false);
            });
        } else {
            addPost(options).then(data => {
                toast({
                    title: `Post published`,
                    status: "success",
                    isClosable: true,
                });
                setIsLoading(false);
                setState(initValues);
            }).catch(error => {
                toast({
                    title: error,
                    status: "error",
                    isClosable: true,
                });
                setIsLoading(false);
            });
        }
    };
    let buttonText = "Publish Post";
    if (state.isUpdate) {
        buttonText = "Update Post";
    }

    return (
        <Stack m="0 40px" p="20px 0" spacing="50px">
            <TopBar isEditPage={true} goBack={goBack} title={buttonText}/>
            <Stack
                w="100%"
                bg="rgba(247, 248, 252, 1)"
                h="auto"
                spacing="48px"
                alignItems={"center"}
            >
                {/*<Header title="Create Blog" goBack={goBack}/>*/}
                <Stack w="100%" alignItems={"center"} pb="80px">
                    <form onSubmit={(e) => {
                        e.preventDefault();
                        handleSubmit();
                    }}>
                        <Stack spacing={"32px"} minWidth={"545px"}>
                            <Stack w="100%" spacing={"12px"}>
                                <Text
                                    fontFamily="MaisonBook"
                                    color="#9FA2B4"
                                    fontSize="12px"
                                    fontStyle="normal"
                                    fontWeight="400"
                                    lineHeight="16px"
                                    letterSpacing="0.20000001192092896px"
                                    textAlign="left"
                                >
                                    Category
                                </Text>
                                <FormControl isRequired>
                                    <Select placeholder='Select option' name="category_id"
                                            onChange={handleInputChange} value={state.category_id}>
                                        {options.map((option: any, index: number) => {
                                            return <option key={index} value={option.value}>
                                                {option.name}</option>
                                        })}
                                    </Select>
                                </FormControl>
                            </Stack>
                            <Stack w="100%" spacing={"12px"}>
                                <Text
                                    fontFamily="MaisonBook"
                                    color="#9FA2B4"
                                    fontSize="12px"
                                    fontStyle="normal"
                                    fontWeight="400"
                                    lineHeight="16px"
                                    letterSpacing="0.20000001192092896px"
                                    textAlign="left"
                                >
                                    Title
                                </Text>
                                <FormControl isRequired>
                                    <Input
                                        type="text"
                                        placeholder="Enter post title"
                                        name="title"
                                        onChange={handleInputChange}
                                        value={state.title}
                                    />
                                </FormControl>
                            </Stack>

                            <TextBoxBlog handleOnChange={handleRTEChange}
                                         editorState={editorState}
                                         defaultEditorContent={state.body}/>

                            <Stack w="100%" spacing={"12px"}>
                                <Text
                                    fontFamily="MaisonBook"
                                    color="#9FA2B4"
                                    fontSize="12px"
                                    fontStyle="normal"
                                    fontWeight="400"
                                    lineHeight="16px"
                                    letterSpacing="0.20000001192092896px"
                                    textAlign="left"
                                >
                                    Date
                                </Text>
                                <FormControl isRequired>
                                    <Input
                                        type="date"
                                        placeholder="Enter post date"
                                        name="date"
                                        onChange={handleInputChange}
                                        value={state.date}
                                    />
                                </FormControl>
                            </Stack>
                        </Stack>
                        <HStack py="32px" justifyContent="right" w="545px">
                            <Button
                                type="submit"
                                isLoading={isLoading}
                                w="112px"
                                h="46px"
                                color="white"
                                bg="#051E61"
                                fontFamily="MaisonBold"
                                fontSize="14px"
                                fontStyle="normal"
                                fontWeight="700"
                                lineHeight="14px"
                                letterSpacing="0.20000001192092896px"
                            >
                                {buttonText}
                            </Button>
                        </HStack>
                    </form>
                </Stack>
            </Stack>
        </Stack>
    );
};

export default CreateBlog;