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 AddServiceSidebar from './components/AddServiceSidebar';
import * as Yup from 'yup'
import { useCreateService, useMultiUpload, useSingleUpload } from './hooks/useServiceData';
import moment from 'moment-jalaali';
import { ErrorType } from '../../helpers/types';
import { toast } from '../../components/Toast';
import { useNavigate } from 'react-router-dom';
import { Pages } from '../../config/Pages';


const AddService: FC = () => {

    const navigate = useNavigate()
    const { t } = useTranslation('global')
    const singleUpload = useSingleUpload()
    const multiUpload = useMultiUpload()
    const editorRef = useRef<HTMLDivElement | null>(null);
    const createService = useCreateService()
    const [iconFile, setIconFile] = useState<File>()
    const [imagesFile, setImagesFile] = useState<File[]>()
    const [audioFiles, setAudioFiles] = useState<File[]>()
    const [videoFiles, setVideoFiles] = useState<File[]>()

    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', () => {
            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: '',
            slug: '',
            pageTitle: '',
            pageDescription: '',
            audios: [],
            videos: []
        },
        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 && imagesFile) {

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

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

                // آپلود فایل‌های صوتی
                if (audioFiles && audioFiles.length > 0) {
                    const audios = new FormData()
                    audioFiles.forEach((file: File) => {
                        audios.append('files', file)
                    })
                    await multiUpload.mutateAsync(audios, {
                        onSuccess: async (data) => {
                            values.audios = await data.data.map((item: { url: string }) => item?.url)
                        },
                        onError: (error: ErrorType) => {
                            toast(error.response?.data?.error?.message[0], 'error')
                        }
                    })
                } else {
                    values.audios = undefined
                }

                // آپلود فایل‌های ویدیویی
                if (videoFiles && videoFiles.length > 0) {
                    const videos = new FormData()
                    videoFiles.forEach((file: File) => {
                        videos.append('files', file)
                    })
                    await multiUpload.mutateAsync(videos, {
                        onSuccess: async (data) => {
                            values.videos = await data.data.map((item: { url: string }) => item?.url)
                        },
                        onError: (error: ErrorType) => {
                            toast(error.response?.data?.error?.message[0], 'error')
                        }
                    })
                } else {
                    values.videos = undefined
                }

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


    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')}
                                name='name'
                                onChange={formik.handleChange}
                                error_text={formik.touched.name && formik.errors.name ? formik.errors.name : ''}
                            />

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

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

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

                        </div>

                        <div className='mt-8 rowTwoInput'>
                            <Input
                                label={t('service.company_developed')}
                                name='author'
                                onChange={formik.handleChange}
                                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 : ''}
                            />
                        </div>

                        <div className='mt-8 rowTwoInput'>
                            <Input
                                label={t('service.user_count')}
                                name='userCount'
                                onChange={formik.handleChange}
                                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 : ''}
                            />
                        </div>

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

                    </div>
                </div>

                <AddServiceSidebar
                    formik={formik}
                    onChangeIconFile={(file: File) => setIconFile(file)}
                    onChangeImagesFile={(file: File[]) => setImagesFile(file)}
                    onChangeAudioFile={(file: File[]) => setAudioFiles(file)}
                    onChangeVideoFile={(file: File[]) => setVideoFiles(file)}
                />
            </div>
        </div>
    )
}

export default AddService