import {Link} from "react-router-dom";
import {useState, useEffect} 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 {useParams} from "react-router-dom";
import AdminApi from "../../api/AdminApi";

import {userToken} from "../../api/TokenApi";
import CmsAPi from "../../api/CmsAPi";

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


export default function EditArticle() {
    const editorRef = useRef(null);
    const [error, setError] = useState(undefined)
    const [loading, setLoading] = useState(false)
    const [article, setArticle] = useState({
        title: '',
        slug: '',
        description: '',
        image: null,
        alt: '',
        content: '',
    })
    const {id} = useParams()
    const getArticles = async () => {
        const fetchedArticles = await CmsAPi.get(`blog/show/${id}?withImages=true`)
        console.log(fetchedArticles);
        setArticle(fetchedArticles)
    }
    useEffect(() => {
        getArticles()
    }, [])
    const onChange = (e) => {
        setArticle({
            ...article,
            [e.target.name]: e.target.value
        })
    }

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

    const handleDelete = async (deleteId) => {
        await AdminApi.delete(`blog/delete/${deleteId}`).then(() => {
            window.location = '/panel/articles'
        })
    }

    const handleChangeGalleryImage = async (e) => {
        console.log("HERE");
        const files = [...e.target.files]
        for (let i = 0; i < files.length; i++) {
            const formData = new FormData();
            formData.append('image', files[i])
            formData.append('title', files[i].name)
            formData.append('alt', files[i].name)
            await AdminApi.imagePost(`images/cms/createOn/Post/${id}`, formData).then(() => getArticles())
        }
    }

    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/update/${id}`, {
            ...article,
            content: editorRef.current ? editorRef.current.getContent() : ""
        })

        if (postArticleRes) {
            window.location = '/panel/articles'
        } else {
            setError('خطا! لطفا از پرکردن فیلد ها مطمئن شوید و دوباره تلاش کنید. در غیر این صورت با پشتیبانی تماس بفرمایید')
        }
        setLoading(false)
    };
    const handleCmsImageDelete = async(id) => {
        await AdminApi.post(`blogimage/delete/${id}`)
        getArticles()
    }
    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 bg-[#CDCDCD] rounded-xl">
                                <img className={'objecct-cover rounded'} alt={'click to upload'} src={article.image_path}/>
                                <input id={'image-input'}
                                       accept={'image/*'} type="file"
                                       className="hidden"
                                       onChange={handleChangeImage}
                                />
                            </label>
                    }
                    <span className="text-sm font-[Vazirmatn] pt-1">برای تعویض عکس روی آن کلیک کنید.</span>
                </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>
                <span onClick={() => handleDelete(article.id)} className="text-4 cursor-pointer hover:opacity-80 underline w-full h-fit text-center items-center justify-center">
                    حذف
                </span>
            </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={article.content}
                    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 className={'py-4 px-4 my-3 flex flex-col bg-white border-1 border-[#E6E6E6] rounded-lg'}>
                    <div className="flex items-start justify-start overflow-x-scroll">
                        <label
                            htmlFor="gallery-image-input"
                            className="flex items-center justify-center rounded-lg ml-3 cursor-pointer bg-[#CDCDCD] hover:bg-[#ABABAB]">
                            <div className="flex items-center justify-center w-[10vw] h-[10vw]">
                                <img alt={'click to upload'} src={PlusIcon}/>
                            </div>
                            <input id="gallery-image-input" accept={'image/*'} multiple type="file" className="hidden" onChange={e => handleChangeGalleryImage(e)}/>
                        </label>
                        {
                            article.images?.map((image, index) => (
                                <div className="flex flex-col items-center">
                                    <div key={index} className="relative flex flex-col items-center justify-center">
                                        <button onClick={() => handleCmsImageDelete(image.id)} className="absolute w-full h-full top-0 right-0 px-3 rounded-lg">
                                            <div className="flex items-center justify-center h-full w-full transition opacity-0 hover:opacity-100 bg-red-500/25 rounded-lg">
                                                <svg className="w-12 h-12 stroke-red-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" >
                                                <path stroke-linecap="round" stroke-linejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0" />
                                                </svg>
                                            </div>
                                        </button>
                                        <img className={'preview-image mx-3 rounded-lg shadow-xl'}  src={image.path} alt={image.title}/>
                                    </div>
                                    <button onClick={() => {navigator.clipboard.writeText(image.path)}} className="bg-blue-200 transition hover:bg-blue-300 active:bg-blue-400 rounded p-3 m-3 w-[10vw] font-[Vazirmatn]">کپی کردن لینک</button>
                                </div>
                            ))
                        }
                    </div>
                </div>
            </div>
        </div>
    )
}