import { FC, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Input from '../../components/Input'
import Select from '../../components/Select'
import Quill from 'quill';
import Button from '../../components/Button';
import { TickCircle } from 'iconsax-react';
import { useFormik } from 'formik';
import { CreateServiceType } from './types/ServiceTypes';
import DatePickerComponent from '../../components/DatePicker';
import * as Yup from 'yup'
import { useGetDetailService, useMultiUpload, useSingleUpload, useUpdateService } from './hooks/useServiceData';
import moment from 'moment-jalaali';
import { ErrorType } from '../../helpers/types';
import { toast } from 'react-toastify';
import { useNavigate, useParams } from 'react-router-dom';
import { Pages } from '../../config/Pages';
import UpdateServiceSidebar from './components/UpdateServiceSidebar';

const UpdateService: FC = () => {

    const { id } = useParams()
    const navigate = useNavigate()
    const { t } = useTranslation('global')
    const singleUpload = useSingleUpload()
    const multiUpload = useMultiUpload()
    const editorRef = useRef<HTMLDivElement | null>(null);
    const createService = useUpdateService(id ? id : '')
    const [iconFile, setIconFile] = useState<File>()
    const [imagesFile, setImagesFile] = useState<File[]>()
    const getDetailService = useGetDetailService(id)

    useEffect(() => {
        const quill = new Quill('#editor', {
            theme: 'snow',
            modules: {
                toolbar: [
                    [{ header: '1' }, { header: '2' }, { font: [] }],
                    [{ list: 'ordered' }, { list: 'bullet' }],
                    ['bold', 'italic', 'underline'],
                    ['link', 'image'],
                    [{ align: [] }],
                    ['clean']
                ]
            }
        });
        quill.on('text-change', () => {
            if (editorRef.current) {
                const html = editorRef.current?.querySelector('.ql-editor')?.innerHTML || '';
                formik.setFieldValue('metaDescription', html);
            }
        });
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const formik = useFormik<CreateServiceType>({
        initialValues: {
            author: '',
            categoryId: '',
            description: '',
            icon: '',
            images: [],
            isDanakSuggest: false,
            link: '',
            metaDescription: '',
            name: '',
            title: '',
            serviceLanguage: '',
            softwareLanguage: '',
            userCount: 0,
            createDate: '',
            coverUrl: '',
            slug: '',
            pageTitle: '',
            pageDescription: ''
        },
        validationSchema: Yup.object({
            name: Yup.string().required(t('errors.required')),
            title: Yup.string().required(t('errors.required')),
            description: Yup.string().required(t('errors.required')),
            author: Yup.string().required(t('errors.required')),
            createDate: Yup.date().required(t('errors.required')),
            userCount: Yup.number().required(t('errors.required')),
            serviceLanguage: Yup.string().required(t('errors.required')),
            metaDescription: Yup.string().required(t('errors.required')),
            link: Yup.string().required(t('errors.required')),
            slug: Yup.string().required(t('errors.required')),
            pageTitle: Yup.string().required(t('errors.required')),
            pageDescription: Yup.string().required(t('errors.required')),
        }),
        onSubmit: async (values) => {


            if (iconFile) {
                const formData = new FormData()
                formData.append('file', iconFile)
                await singleUpload.mutateAsync(formData, {
                    onSuccess: (data) => {
                        values.icon = data?.data?.url
                    },
                    onError: (error: ErrorType) => {
                        toast.error(error.response?.data?.error?.message[0])
                    }
                })
            }

            if (imagesFile && imagesFile.length > 0) {
                const images = new FormData()
                imagesFile.forEach(file => {
                    images.append('files', file)
                })
                await multiUpload.mutateAsync(images, {
                    onSuccess: async (data) => {
                        values.images = [...(values.images || []), ...data.data.map((item: { url: string }) => item?.url)]
                    },
                    onError: (error: ErrorType) => {
                        toast.error(error.response?.data?.error?.message[0])
                    }
                })
            }

            const params = {
                ...values,
                userCount: +values.userCount,
                createDate: moment(values.createDate).format('YYYY-MM-DD'),
            }
            createService.mutate(params, {
                onSuccess: () => {
                    formik.resetForm()
                    toast.success(t('success'))
                    navigate(Pages.services.list)
                },
                onError: (error: ErrorType) => {
                    toast.error(error.response?.data?.error?.message[0])
                }
            })

        },
    })

    useEffect(() => {
        if (getDetailService.data) {
            const data = getDetailService.data?.data?.danakService;
            formik.setValues({
                author: data?.author,
                categoryId: data?.category?.id,
                description: data?.description,
                icon: data?.icon,
                images: data?.images?.map((image: { imageUrl: string }) => image.imageUrl),
                isDanakSuggest: data?.isDanakSuggest,
                link: data?.link,
                metaDescription: data?.metaDescription,
                name: data?.name,
                title: data?.title,
                serviceLanguage: data?.serviceLanguage,
                softwareLanguage: data?.softwareLanguage,
                userCount: data?.userCount || 0,
                createDate: moment(data?.createDate).format('YYYY-MM-DD'),
                coverUrl: data?.coverUrl,
                slug: data?.slug,
                pageTitle: data?.pageTitle,
                pageDescription: data?.pageDescription
            });
            const editorElement = editorRef.current?.querySelector('.ql-editor');
            if (editorElement) {
                editorElement.innerHTML = data?.metaDescription || '';
            }
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [getDetailService.data]);

    return (
        <div className='w-full mt-4'>

            <div className='flex w-full justify-between items-center'>
                <div>
                    {t('service.add_service')}
                </div>
                <div>
                    <Button
                        className='px-5'
                        onClick={() => formik.handleSubmit()}
                        isLoading={createService.isPending || singleUpload.isPending || multiUpload.isPending}
                    >
                        <div className='flex gap-2'>
                            <TickCircle
                                className='size-5'
                                color='#fff'
                            />
                            <div>{t('service.submit_service')}</div>
                        </div>
                    </Button>
                </div>
            </div>
            <div className='flex gap-6'>
                <div className='flex-1'>


                    <div className='flex-1 mt-10 bg-white py-8 xl:px-10 px-4 rounded-3xl'>
                        <div className='rowTwoInput'>
                            <Input
                                label={t('service.service_name')}
                                {...formik.getFieldProps('name')}
                                error_text={formik.touched.name && formik.errors.name ? formik.errors.name : ''}
                            />

                            <Input
                                label={t('service.title')}
                                {...formik.getFieldProps('title')}
                                error_text={formik.touched.title && formik.errors.title ? formik.errors.title : ''}
                            />
                        </div>

                        <div className='mt-8 rowTwoInput'>
                            <Input
                                label={t('service.description_short')}
                                {...formik.getFieldProps('description')}
                                error_text={formik.touched.description && formik.errors.description ? formik.errors.description : ''}
                            />

                            <Input
                                label={t('service.software_langauge')}
                                {...formik.getFieldProps('softwareLanguage')}
                                error_text={formik.touched.softwareLanguage && formik.errors.softwareLanguage ? formik.errors.softwareLanguage : ''}
                            />

                        </div>

                        <div className='mt-8 rowTwoInput'>
                            <Input
                                label={t('service.company_developed')}
                                {...formik.getFieldProps('author')}
                                error_text={formik.touched.author && formik.errors.author ? formik.errors.author : ''}
                            />

                            <DatePickerComponent
                                label={t('service.year_make')}
                                onChange={(d) => formik.setFieldValue('createDate', d)}
                                placeholder={t('select')}
                                error_text={formik.touched.createDate && formik.errors.createDate ? formik.errors.createDate : ''}
                                defaulValue={formik.values.createDate}
                            />
                        </div>

                        <div className='mt-8 rowTwoInput'>
                            <Input
                                label={t('service.user_count')}
                                {...formik.getFieldProps('userCount')}
                                error_text={formik.touched.userCount && formik.errors.userCount ? formik.errors.userCount : ''}
                            />

                            <Select
                                label={t('service.lang_app')}
                                items={[
                                    {
                                        label: 'فارسی',
                                        value: 'fa'
                                    },
                                    {
                                        label: 'انگلیسی',
                                        value: 'en'
                                    },
                                ]}
                                placeholder={t('select')}
                                name='serviceLanguage'
                                onChange={formik.handleChange}
                                error_text={formik.touched.serviceLanguage && formik.errors.serviceLanguage ? formik.errors.serviceLanguage : ''}
                                value={formik.values.serviceLanguage}
                            />
                        </div>

                        <div className='mt-8'>
                            <div ref={editorRef} id='editor' style={{ minHeight: '120px' }}></div>
                        </div>
                    </div>
                </div>

                {
                    getDetailService.data && (
                        <UpdateServiceSidebar
                            formik={formik}
                            onChangeIconFile={(file: File) => setIconFile(file)}
                            onChangeImagesFile={(file: File[]) => setImagesFile(file)}
                        />
                    )
                }
            </div>

        </div>
    )
}

export default UpdateService