import React, { useState, useContext, useEffect } from "react";
import { useNavigate, useLocation, useParams } from 'react-router-dom';
import { useCookies } from "react-cookie";
import classes from "../assets/styles/newArticle.module.scss";
import MyButton from "../components/MyButton.jsx";
import Loading from "../components/Loading.jsx";
import MyInput from "../components/MyInput.jsx";
import TextEditor from "../components/TextEditor.jsx";
import { UserData } from "../context/index.js";
import { getArticleApi, editTagsApi, editTitleArticleApi, editArticleApi, addArticleApi } from "../hooks/api/articleApi.js";

const NewArticle = () => {
    const navigate = useNavigate();
    const location = useLocation();
    const { articleId } = useParams();
    const {user, setUser} = useContext(UserData)

    const [loading, setLoading] = useState(false);

    const [title, setTitle] = useState("");
    const [tags, setTags] = useState([]);
    const [newTag, setNewTag] = useState("")
    const [ownerId, setOwnerId] = useState("");
    const [contentArticle, setContentArticle] = useState('');
    const [blocks, setBlocks] = useState('');

    const [cookies, _, __] = useCookies(["user"]);

    useEffect(() => {
        async function getArticle() {
            const response = await getArticleApi(cookies.token, articleId)

            if (response.status === 200) {
                setTitle(response.data.article.title)
                setTags(response.data.article.tags ? response.data.article.tags : [])
                setOwnerId(response.data.article.owner_id)
                setContentArticle(response.data.blocks ? response.data.blocks[0].data : '')
                setBlocks(response.data.blocks ? response.data.blocks : false)
            }
            else if (
                response.status === 401
            ) {
                // navigate("/enter")
                setUser(false)
            }
            else {
                console.log(response)
            }
        }

        getArticle()
    }, [])

    async function addTag() {
        if (newTag.length > 0 && !tags.find(item => item === newTag)) {
            const response = await editTagsApi(cookies.token, articleId, [newTag], false)

            if (response.status === 200) {
                setTags([...tags, newTag])
                setNewTag("")
            }
            else if (
                response.status === 401
            ) {
                // navigate("/enter")
                setUser(false)
            }
            else {
                console.log(response)
            }  
        }
    }

    async function removeTag(item, index) {
        const response = await editTagsApi(cookies.token, articleId, [item], true)

        if (response.status === 200) {
            const cTags = [...tags]
            cTags.splice(index, 1)
            setTags(cTags)
        }
        else if (
            response.status === 401
        ) {
            // navigate("/enter")
            setUser(false)
        }
        else {
            console.log(response)
        }
    }

    async function saveArticle() {
        const responseTitle = await editTitleArticleApi(cookies.token, articleId, title)
        const responseContentArticle = blocks ? 
            await editArticleApi(cookies.token, articleId, contentArticle) : 
            await addArticleApi(cookies.token, articleId, contentArticle)
        
        if (responseTitle.status === 200 && responseContentArticle.status === 200) {
            navigate("/articles")
        }
        else if (
            responseTitle.status === 401 || responseContentArticle.status === 401
        ) {
            // navigate("/enter")
            setUser(false)
        }
        else {
            console.log(responseTitle)
            console.log(responseContentArticle)
        }
    }

    return (
        <div className={classes.main}>
            <div className={classes.wrapper}>
                <div className={classes.header}>
                    <div className={classes.header__listInput}>
                        <div className={classes.header__listInput__date}>
                            <span>Дата создания</span>
                            <MyInput type={"datetime-local"}/>
                        </div>
                        <div className={classes.header__listInput__title}>
                            <span>Название статьи</span>
                            <MyInput type={"text"} value={title} change={setTitle}/>
                        </div>
                    </div>
                    <div className={classes.header__listBtn}>
                        {/* <MyButton text={'Предпросмотр'} class={"main__white"}/> */}
                        <MyButton text={'Опубликовать'} class={"main__green"} click={() => saveArticle()}/>
                    </div>                   
                </div>
                <div className={classes.tags}>
                    <div className={classes.tags__wrapper}>
                        <div className={classes.tags__wrapper__input}>
                            <span className={classes.tags__wrapper__input__title}>Добавить тэг</span>
                            <MyInput 
                                type={"text"} 
                                otherMainStyle={{border: "1px solid rgb(180, 180, 180)", borderRadius: "5px"}}
                                otherInputStyle={{border: "0px solid rgb(180, 180, 180)", width: "85%"}}
                                value={newTag}
                                change={setNewTag}
                            />
                            <MyButton 
                                type={"button"} 
                                text={<i class="fa-solid fa-arrow-right"></i>}
                                class={"main__transparent"}
                                mainStyle={
                                    {
                                        position: "absolute", 
                                        right: "0", 
                                        top: "0", 
                                        height: "100%", 
                                    }
                                }
                                otherStyle={{borderRadius: "0 5px 5px 0", padding: "3px 7px 0 7px"}}
                                click={() => addTag()}
                            />
                        </div>
                        <div className={classes.tags__wrapper__list}>
                            {tags ? tags.map((item, i) => 
                                <div className={classes.tags__wrapper__list__item} key={i}>
                                    <span>#{item}</span>
                                    <i class="fa-solid fa-circle-xmark" onClick={() => removeTag(item, i)}></i>
                                </div>
                            ) : <></>}
                        </div>
                    </div>
                </div>
                <div className={classes.content}>
                    <TextEditor data={contentArticle} setData={setContentArticle}/>
                </div>                  
            </div>
        </div>
    )
}

export default NewArticle;