import { FC, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Input from '../../components/Input'
import Button from '../../components/Button'
import SwitchComponent from '../../components/Switch'
import { TickCircle } from 'iconsax-react'
import "quill/dist/quill.snow.css";
// import Quill from 'quill';
import { useFormik } from 'formik'
import { BlogCategoryType, CreateBlogType } from './types/BlogTypes'
import { useGetBlogCategories, useGetBlogDetail, useUpdateBlog } from './hooks/useBlogData'
import * as Yup from 'yup'
import CheckBoxComponent from '../../components/CheckBoxComponent'
import UploadBoxDraggble from '../../components/UploadBoxDraggble'
import Quill from 'quill'
import { useSingleUpload } from '../service/hooks/useServiceData'
import { toast } from 'react-toastify'
import { ErrorType } from '../../helpers/types'
import { Pages } from '../../config/Pages'
import { useNavigate, useParams } from 'react-router-dom'
const UpdateBlog: FC = () => {

    const { id } = useParams()
    const { t } = useTranslation('global')
    const [file, setFile] = useState<File>()
    const singleSlug = useSingleUpload()
    const editorRef = useRef<HTMLDivElement>(null)
    const editorRef2 = useRef<HTMLDivElement>(null)
    const getBlogDetail = useGetBlogDetail(id || '')
    useEffect(() => {
        const quill = new Quill('#editor', {
            theme: 'snow',
        });

        quill.on('text-change', () => {
            const html = editorRef.current?.querySelector('.ql-editor')?.innerHTML || '';
            formik.setFieldValue('previewContent', html);
        });
        const quill2 = new Quill('#editor2', {
            theme: 'snow',
        });

        quill2.on('text-change', () => {
            const html = editorRef2.current?.querySelector('.ql-editor')?.innerHTML || '';
            formik.setFieldValue('content', html);
        });


        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const navigate = useNavigate()
    const updateBlog = useUpdateBlog()
    const getBlogCategories = useGetBlogCategories()
    const formik = useFormik<CreateBlogType>({
        initialValues: {
            categoryId: '',
            title: '',
            previewContent: '',
            content: '',
            imageUrl: '',
            isActive: false,
            isPinned: false,
            metaDescription: '',
            metaTitle: '',
            tags: [],
            tagInput: '',
            slug: '',
        },
        validationSchema: Yup.object({
            title: Yup.string().required(t('errors.required')),
            previewContent: Yup.string().required(t('errors.required')),
            content: Yup.string().required(t('errors.required')),
            categoryId: Yup.string().required(t('errors.required')),
            metaDescription: Yup.string().required(t('errors.required')),
            metaTitle: Yup.string().required(t('errors.required')),
            tags: Yup.array().of(Yup.string()).required(t('errors.required')),
            slug: Yup.string().required(t('errors.required')),
        }),
        onSubmit: async (values) => {
            if (file) {
                const formData = new FormData()
                formData.append('file', file)
                await singleSlug.mutateAsync(formData, {
                    onSuccess(data) {
                        values.imageUrl = data.data.url
                    },
                })
            }


            updateBlog.mutate({ id: id || '', params: values }, {
                onSuccess() {
                    toast.success(t('success'))
                    navigate(Pages.blog.list)
                },
                onError(error: ErrorType) {
                    toast.error(error.response?.data?.error.message[0])
                }
            })
        },
    })

    useEffect(() => {
        if (getBlogDetail.data) {
            formik.setValues(getBlogDetail.data?.data?.blog)
            formik.setFieldValue('categoryId', getBlogDetail.data?.data?.blog.category.id)

            const editorElement = editorRef.current?.querySelector('.ql-editor');
            if (editorElement) {
                editorElement.innerHTML = getBlogDetail.data?.data?.blog?.previewContent || '';
            }

            const editorElement2 = editorRef2.current?.querySelector('.ql-editor');
            if (editorElement2) {
                editorElement2.innerHTML = getBlogDetail.data?.data?.blog?.content || '';
            }
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [getBlogDetail.data])


    return (
        <div className='mt-4'>
            <div className='flex justify-between items-center'>
                <div>
                    {t('blog.add_blog')}
                </div>
                <Button
                    className='w-[172px]'
                    onClick={() => formik.handleSubmit()}
                    isLoading={updateBlog.isPending || singleSlug.isPending}
                >
                    <div className='flex gap-2 items-center'>
                        <TickCircle size={20} color='white' />
                        <div>
                            {t('blog.submit')}
                        </div>
                    </div>
                </Button>
            </div>
            <div className='flex flex-col-reverse xl:flex-row gap-6 xl:mt-8 mt-4'>
                <div className='flex-1 min-h-[calc(100vh-201px)] bg-white py-8 xl:px-10 px-4 rounded-3xl'>
                    <div className='mt-6'>
                        <Input
                            label={t('blog.blog_title')}
                            placeholder={t('blog.enter_your_title')}
                            {...formik.getFieldProps('title')}
                            error_text={formik.touched.title && formik.errors.title ? formik.errors.title : undefined}
                        />
                    </div>
                    <div className='mt-6'>
                        <Input
                            label={t('blog.slug')}
                            placeholder={t('blog.enter_your_slug')}
                            {...formik.getFieldProps('slug')}
                            error_text={formik.touched.slug && formik.errors.slug ? formik.errors.slug : undefined}
                        />
                    </div>

                    <p className='mt-6 text-sm'>{t('blog.blog_summary')}</p>
                    <div className='mt-1'>
                        <div className='min-h-[120px]' ref={editorRef} id='editor'></div>
                    </div>

                    {
                        formik.touched.previewContent && formik.errors.previewContent && (
                            <p className='text-red-500 text-xs mt-1'>{formik.errors.previewContent}</p>
                        )
                    }

                    <p className='mt-6 text-sm'>{t('blog.content')}</p>
                    <div className='mt-1'>
                        <div className='min-h-[200px]' ref={editorRef2} id='editor2'></div>
                    </div>

                    {
                        formik.touched.content && formik.errors.content && (
                            <p className='text-red-500 text-xs mt-1'>{formik.errors.content}</p>
                        )
                    }

                    <div className='mt-6'>
                        <Input
                            label={t('blog.meta_title')}
                            placeholder={t('blog.enter_your_meta_title')}
                            {...formik.getFieldProps('metaTitle')}
                            error_text={formik.touched.metaTitle && formik.errors.metaTitle ? formik.errors.metaTitle : undefined}
                        />
                    </div>

                    <div className='mt-6'>
                        <Input
                            label={t('blog.meta_description')}
                            placeholder={t('blog.enter_your_meta_description')}
                            {...formik.getFieldProps('metaDescription')}
                            error_text={formik.touched.metaDescription && formik.errors.metaDescription ? formik.errors.metaDescription : undefined}
                        />
                    </div>


                </div>


                <div className='min-h-[calc(100vh-201px)] bg-white w-full xl:w-sidebar py-10 px-5 h-fit rounded-3xl'>
                    <div className='text-sm flex items-center justify-between'>
                        <p>
                            {t('blog.blog_status')}
                        </p>
                        <div className='flex gap-1 text-xs items-center text-description'>
                            <SwitchComponent
                                active={formik.values.isActive}
                                onChange={(value) => formik.setFieldValue('isActive', value)}
                            />
                        </div>
                    </div>
                    <div className='text-sm mt-3 flex items-center justify-between'>
                        <p>
                            پین
                        </p>
                        <div className='flex gap-1 text-xs items-center text-description'>
                            <SwitchComponent
                                active={formik.values.isPinned}
                                onChange={(value) => formik.setFieldValue('isPinned', value)}
                            />
                        </div>
                    </div>
                    <p className='mt-6 text-sm'>{t('blog.category')}</p>
                    <div className='p-2 border border-[##D0D0D0] rounded-lg mt-1'>
                        {
                            getBlogCategories.data?.data?.categories?.map((item: BlogCategoryType) => {
                                return (
                                    <div key={item.id} className='flex items-center'>
                                        <CheckBoxComponent
                                            checked={formik.values.categoryId === item.id}
                                            onChange={(e) => formik.setFieldValue('categoryId', e.target.checked ? item.id : '')}
                                        />
                                        <div>{item.title}</div>
                                    </div>
                                )
                            })
                        }
                    </div>
                    <div className='mt-8'>
                        <p className='text-sm'>{t('blog.featured_image')}</p>
                        <div className='mt-4'>
                            <UploadBoxDraggble
                                label={t('blog.featured_image')}
                                onChange={(files) => setFile(files[0])}
                            />
                        </div>
                    </div>
                    <p className='mt-6 text-sm'>{t('blog.tags')}</p>
                    <div className='mt-6'>
                        <Input
                            className='-mt-4'
                            placeholder={t('blog.enter_tags')}
                            value={formik.values.tagInput || ''}
                            onChange={(e) => {
                                formik.setFieldValue('tagInput', e.target.value);
                                formik.setFieldError('tags', undefined);
                            }}
                            onKeyDown={(e) => {
                                if (e.key === 'Enter') {
                                    e.preventDefault();
                                    const newTag = formik.values.tagInput?.trim();
                                    if (newTag) {
                                        if (formik.values.tags.includes(newTag)) {
                                            formik.setFieldError('tags', t('blog.duplicate_tag_error'));
                                        } else {
                                            formik.setFieldValue('tags', [...formik.values.tags, newTag]);
                                            formik.setFieldValue('tagInput', '');
                                        }
                                    }
                                }
                            }}
                            error_text={typeof formik.errors.tags === 'string' ? formik.errors.tags : undefined}
                        />
                        <div className='flex flex-wrap gap-2 mt-2'>
                            {formik.values.tags.map((tag, index) => (
                                <div key={index} className='flex items-center gap-1 bg-gray-100 px-2 py-1 rounded-full'>
                                    <span className='text-sm'>{tag}</span>
                                    <button
                                        type='button'
                                        onClick={() => {
                                            const newTags = formik.values.tags.filter((_, i) => i !== index);
                                            formik.setFieldValue('tags', newTags);
                                        }}
                                        className='text-gray-500 text-xs hover:text-gray-700'
                                    >
                                        ×
                                    </button>
                                </div>
                            ))}
                        </div>
                        <p className='text-description text-xs mt-2'>
                            {t('blog.tag_hint')}
                        </p>
                    </div>

                </div>
            </div>

        </div>
    )
}

export default UpdateBlog