import { FC, useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import Button from '../../components/Button'
import { InfoCircle, TickCircle } from 'iconsax-react'
import Input from '../../components/Input'
import Quill from 'quill'
import DatePickerComponent from '../../components/DatePicker'
import CheckBoxComponent from '../../components/CheckBoxComponent'
import { useFormik } from 'formik'
import { AnnoncementCreateType } from './types/AnnoncementTypes'
import * as Yup from 'yup'
import { ErrorType } from '../../helpers/types'
import { toast } from 'react-toastify'
import moment from 'moment-jalaali'
import { useNavigate } from 'react-router-dom'
import { Pages } from '../../config/Pages'
import { useCreateAnnoncement } from './hooks/useAnnoncementData'

const Create: FC = () => {

    const { t } = useTranslation('global')
    const navigate = useNavigate()
    const editorRef = useRef<HTMLDivElement | null>(null);
    const createAnnoncement = useCreateAnnoncement();

    const formik = useFormik<AnnoncementCreateType>({
        initialValues: {
            title: '',
            content: '',
            publishAt: '',
            isPublic: false,
            isImportant: false,
        },
        validationSchema: Yup.object({
            title: Yup.string().required(t('errors.required')),
            content: Yup.string().required(t('errors.required')),
            publishAt: Yup.string().required(t('errors.required')),
        }),
        onSubmit: (values) => {
            createAnnoncement.mutate(values, {
                onSuccess: () => {
                    formik.resetForm()
                    toast.success(t('success'))
                    navigate(Pages.announcement.list)
                },
                onError: (error: ErrorType) => {
                    toast.error(error.response?.data?.error?.message[0])
                }
            })
        }
    })


    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('content', html);
        });
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    return (
        <div className='w-full mt-4'>
            <div className='flex w-full justify-between items-center'>
                <div>
                    {t('announcement.add_announcement')}
                </div>
                <div>
                    <Button
                        className='px-5'
                        onClick={() => formik.handleSubmit()}
                        isLoading={createAnnoncement.isPending}
                    >
                        <div className='flex gap-2'>
                            <TickCircle
                                className='size-5'
                                color='#fff'
                            />
                            <div>{t('announcement.submit_announcement')}</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'>
                        <Input
                            label={t('announcement.title')}
                            name='title'
                            onChange={formik.handleChange}
                            error_text={formik.touched.title && formik.errors.title ? formik.errors.title : ''}
                        />

                        <div className='mt-7 text-sm'>{t('announcement.text')}</div>

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

                <div className='bg-white mt-10 w-sidebar text-xs hidden 2xl:block h-fit px-5 py-7 rounded-3xl'>
                    <DatePickerComponent
                        label={t('announcement.publish_date')}
                        onChange={(d) => formik.setFieldValue('publishAt', moment(d, 'jYYYY-jMM-jDD').format('YYYY-MM-DD'))}
                        placeholder={t('select')}
                    />

                    <div className='flex gap-1 mt-3'>
                        <InfoCircle
                            color='#8C90A3'
                            className='size-4 min-w-4'
                        />
                        <p className='text-[10px] text-description'>
                            {t('announcement.info_publishdata')}
                        </p>
                    </div>

                    <div className='flex items-center mt-5'>
                        <CheckBoxComponent
                            checked={formik.values.isImportant}
                            onChange={(e) => formik.setFieldValue('isImportant', e.target.checked)}
                        />

                        <div className='text-xs'>{t('announcement.label_importance')}</div>

                    </div>

                </div>
            </div>
        </div>
    )
}

export default Create