import { FC, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Button from '../../components/Button'
import { useFormik } from 'formik'
import { CategoryLearningType, CreateLearningType } from './types/LearningTypes'
import * as Yup from 'yup'
import { useCreateLearning, useGetCategory } from './hooks/useLearningData'
import { useSingleUpload } from '../service/hooks/useServiceData'
import { TickCircle } from 'iconsax-react'
import Input from '../../components/Input'
import Select from '../../components/Select'
import Textarea from '../../components/Textarea'
import PageLoading from '../../components/PageLoading'
import CreateLearningSidebar from './components/CreateLearningSidebar'
import { ErrorType } from '../../helpers/types'
import { toast } from 'react-toastify'
import { useNavigate } from 'react-router-dom'
import { Pages } from '../../config/Pages'

const CreateLearning: FC = () => {

    const navigate = useNavigate()
    const { t } = useTranslation('global')
    const singleUpload = useSingleUpload()
    const createLearning = useCreateLearning()
    const getCategory = useGetCategory()
    const [videoFile, setVideoFile] = useState<File>()
    const [coverFile, setCoverFile] = useState<File>()

    const formik = useFormik<CreateLearningType>({
        initialValues: {
            title: '',
            description: '',
            coverUrl: '',
            videoUrl: '',
            videoDuration: '',
            categoryId: ''
        },
        validationSchema: Yup.object().shape({
            title: Yup.string().required(t('errors.required')),
            description: Yup.string().required(t('errors.required')),
            videoDuration: Yup.string().required(t('errors.required')),
            categoryId: Yup.string().required(t('errors.required'))
        }),
        onSubmit: async (values) => {
            if (videoFile && coverFile) {

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

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

                createLearning.mutate(values, {
                    onSuccess: () => {
                        toast.success(t('success'))
                        navigate(Pages.learning.list)
                    },
                    onError: (error: ErrorType) => {
                        toast.error(error.response?.data?.error?.message[0])
                    }
                })
            } else {
                toast.error(t('learning.error_video_cover_required'))
            }
        }
    })

    return (
        <div className='w-full mt-4'>
            <div className='flex w-full justify-between items-center'>
                <div>
                    {t('learning.new_learning')}
                </div>
                <div>
                    <Button
                        className='px-5'
                        onClick={() => formik.handleSubmit()}
                        isLoading={createLearning.isPending || singleUpload.isPending}
                    >
                        <div className='flex gap-2'>
                            <TickCircle
                                className='size-5'
                                color='#fff'
                            />
                            <div>{t('learning.submit_learning')}</div>
                        </div>
                    </Button>
                </div>
            </div>

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

                                <div className='rowTwoInput mt-5'>
                                    <Select
                                        items={getCategory.data?.data?.categories?.map((item: CategoryLearningType) => ({ label: item.name, value: item.id.toString() }))}
                                        label={t('learning.category')}
                                        placeholder={t('select')}
                                        name='categoryId'
                                        onChange={formik.handleChange}
                                        error_text={formik.touched.categoryId && formik.errors.categoryId ? formik.errors.categoryId : ''}
                                    />

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

                                <div className='mt-5'>
                                    <div>{t('learning.description')}</div>
                                    <div>
                                        <Textarea
                                            name='description'
                                            placeholder={t('learning.description')}
                                            onChange={formik.handleChange}
                                            error_text={formik.touched.description && formik.errors.description ? formik.errors.description : ''}

                                        />
                                    </div>
                                </div>
                            </div>
                        </div>

                        <CreateLearningSidebar
                            onChangeCoverFile={setCoverFile}
                            onChangeVideoFile={setVideoFile}
                        />
                    </div>
            }

        </div>
    )
}

export default CreateLearning