import {Link} from "react-router-dom";
import {useState} from "react";
import InputLabel from "../../Components/common/InputLabel";
import TextInput from "../../Components/common/TextInput";
import {FormControl, MenuItem, Select} from "@mui/material";
import TextArea from "../../Components/common/TextArea";
import InputError from "../../Components/common/InputError";
import Box from "@mui/material/Box";
import LoadingTemplate from "../../Components/common/LoadingTemplate";
import PlusIcon from './../../assets/images/PlusGray.svg';

import AdminApi from "../../api/AdminApi";

import { Editor } from '@tinymce/tinymce-react';
import React, { useRef } from 'react';


export default function AddArticle() {
    const editorRef = useRef(null);
    const [error, setError] = useState(undefined)
    const [loading, setLoading] = useState(false)
    const [article, setArticle] = useState({
        title: '',
        slug: '',
        description: '',
        image: null,
        alt: '',
    })

    const onChange = (e) => {
        setArticle({
            ...article,
            [e.target.name]: e.target.value
        })
    }

    const handleChangeImage = (e) => {
        setArticle({
            ...article,
            image: e.target.files[0]
        })
    }

    const handlePost = async () => {
    let postArticleRes = undefined
    
    setLoading(true)
    const formData = new FormData();
    formData.append('title', article.title);
    formData.append('slug', article.slug);
    formData.append('description', article.description);
    formData.append('image', article.image);
    formData.append('alt', article.alt);
    postArticleRes = await AdminApi.imagePost(`blog/store`, {
        ...article,
        content: editorRef.current ? editorRef.current.getContent() : ""
    })

    if (postArticleRes) {
        window.location = '/panel/articles'
    } else {
        setError('خطا! لطفا از پرکردن فیلد ها مطمئن شوید و دوباره تلاش کنید. در غیر این صورت با پشتیبانی تماس بفرمایید')
    }
    setLoading(false)
    };
    return (
        <div className={'flex w-full h-full'}>
            <div className={'flex flex-col items-start justify-start bg-1 rounded-xl w-1/3'}>
                <div className={'flex flex-col items-start justify-center m-5'}>
                    <InputLabel className={"font-[Vazirmatn] text-[#333333] font-normal mb-2 px-2"} htmlFor="title"
                                value="تصویر مقاله"/>
                    {
                        article.image ?
                            <label
                                htmlFor={'image-input'}
                                className="cursor-pointer hover:opacity-70">
                                <img className={'w-[100vw] h-[40vh] object-cover rounded-xl'}
                                     src={URL.createObjectURL(article.image)} alt={''}
                                     loading={'lazy'}
                                />

                                <input id={'image-input'}
                                       accept={'image/*'} type="file"
                                       className="hidden"
                                       onChange={handleChangeImage}
                                />
                            </label> :
                            <label
                                htmlFor={'image-input'}
                                className="flex justify-center  items-center cursor-pointer hover:opacity-70 h-[40vh] bg-[#CDCDCD] rounded-xl">
                                <img className={'w-[100vw] h-[7vh]'} alt={'click to upload'} src={PlusIcon}/>
                                <input id={'image-input'}
                                       accept={'image/*'} type="file"
                                       className="hidden"
                                       onChange={handleChangeImage}
                                />
                            </label>
                    }
                </div>
                <div className={'w-full mb-5'}>
                    <div className={'flex flex-col mx-5'}>
                        <InputLabel className={"font-[Vazirmatn] text-[#333333] font-normal mb-2 px-2"} htmlFor="title"
                                    value="عنوان مقاله"/>
                        <TextInput
                            id="title"
                            type="text"
                            name="title"
                            className="py-3 font-[Vazirmatn] flex text-right w-full placeholder:text-sm placeholder-[#828282] border-[#B3B3B3] bg-1"
                            placeholder={'مثال: محصولات ورزشی و تاثیر استفاده از آنها'}
                            onChange={onChange}
                            value={article.title}
                        />
                    </div>
                </div>
                <div className={'w-full mb-5'}>
                    <div className={'flex flex-col mx-5'}>
                        <InputLabel className={"font-[Vazirmatn] text-[#333333] font-normal mb-2 px-2"} htmlFor="slug"
                                    value="اسلاگ"/>
                        <TextInput
                            id="slug"
                            type="text"
                            name="slug"
                            className="py-3 font-[Vazirmatn] flex text-right w-full placeholder:text-sm placeholder-[#828282] border-[#B3B3B3] bg-1"
                            placeholder={'مثال: mahsulat-varzeshi-va-tasir-estefade-az-anha'}
                            onChange={onChange}
                            value={article.slug}
                        />
                    </div>
                </div>
                <div className={'w-full mb-5'}>
                    <div className={'flex flex-col mx-5'}>
                        <InputLabel className={"justify-start font-normal font-[Vazirmatn] mb-2 mr-2 "}
                                    htmlFor="description"
                                    value="توضیحات کوتاه مقاله (حداکثر 20 کلمه)"/>
                        <TextArea
                            id="description"
                            type="text"
                            rows={3}
                            maxLength={100}
                            name="description"
                            className="py-3 font-[Vazirmatn] flex text-right w-full placeholder:text-sm placeholder-[#828282] border-[#B3B3B3] bg-1"
                            onChange={onChange}
                            value={article.description}
                        />
                    </div>
                </div>
            </div>
            <div className={'flex flex-col w-2/3 mx-5'}>
                <Editor
                    tinymceScriptSrc={'app.axicon.ir/tinymce/tinymce.min.js'}
                    onInit={(evt, editor) => editorRef.current = editor}
                    initialValue='<p>متن مقاله</p>'
                    init={{
                    height: 500,
                    language: 'fa',
                    promotion: false,
                    branding: false,
                    menubar: true,
                    plugins: [
                        'advlist', 'autolink', 'lists', 'link', 'image', 'charmap',
                        'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
                        'insertdatetime', 'media', 'table', 'preview', 'help', 'wordcount'
                    ],
                    toolbar: 'undo redo | blocks | ' +
                        'bold italic forecolor | alignleft aligncenter ' +
                        'alignright alignjustify | bullist numlist outdent indent | ' +
                        'removeformat | help',
                    content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }'
                    }}
                />
                <div className="w-full rounded-b-xl bg-1 px-3 py-2">
                {
                    error ?
                        <InputError message={error} className="mt-3 mx-3 font-[dana]"/>
                        : null
                }
                    <Box sx={{display: 'flex', flexDirection: 'row', pt: 2}}>
                        <Link
                            to={'/panel/articles'}
                            disabled={loading}
                            className={'font-[Vazirmatn] bg-white text-black border-1 border-black rounded-lg h-full mx-1 ml-4 py-2 px-6 text-center w-full'}
                        >
                            لغو
                        </Link>
                        <LoadingTemplate loading={loading} className={'ml-5'} marginLeft={'-22px'}>
                            <button
                                disabled={loading}
                                className={'font-[Vazirmatn] bg-zinc-900 text-white rounded-lg h-full mx-1 mr-4 py-2 px-6 text-center w-full hover:bg-zinc-700'}
                                onClick={handlePost}>
                                ثبت
                            </button>
                        </LoadingTemplate>
                    </Box>
                </div>
            </div>
        </div>
    )
}