import { type FC, useState } from 'react'
import PageTitle from '../../components/PageTitle'
import { useFormik } from 'formik'
import { type CreateLearningType } from './types/Types'
import * as Yup from 'yup'
import { useCreateLearning, useGetLearningCategory } from './hooks/useSellerData'
import { useNavigate } from 'react-router-dom'
import Input from '../../components/Input'
import Select from '../../components/Select'
import Textarea from '../../components/Textarea'
import Button from '../../components/Button'
import { TickCircle } from 'iconsax-react'
import { useUploadSingle } from '../uploader/hooks/useUploaderData'
import UploadBoxDraggble from '@/components/UploadBoxDraggble'
import { toast } from 'react-toastify'
import { extractErrorMessage } from '@/helpers/utils'
import { Pages } from '@/config/Pages'

const CreateLearning: FC = () => {
    const navigate = useNavigate()
    const { data: categoriesData } = useGetLearningCategory()
    const uploadSingle = useUploadSingle()
    const createLearningMutation = useCreateLearning()

    const [videoFile, setVideoFile] = useState<File[]>([])
    const [coverFile, setCoverFile] = useState<File[]>([])

    const formik = useFormik<CreateLearningType>({
        initialValues: {
            title: '',
            description: '',
            videoUrl: '',
            cover: '',
            category: ''
        },
        validationSchema: Yup.object({
            title: Yup.string().required('عنوان یادگیری الزامی است'),
            description: Yup.string().required('توضیحات یادگیری الزامی است'),
            category: Yup.string().required('دسته‌بندی یادگیری الزامی است')
        }),
        onSubmit: async (values) => {
            let videoUrl = values.videoUrl
            let coverUrl = values.cover

            if (videoFile.length > 0) {
                const videoResponse = await uploadSingle.mutateAsync(videoFile[0])
                videoUrl = videoResponse.results?.url?.url || ''
            }

            if (coverFile.length > 0) {
                const coverResponse = await uploadSingle.mutateAsync(coverFile[0])
                coverUrl = coverResponse.results?.url?.url || ''
            }

            const submitData = {
                ...values,
                videoUrl,
                cover: coverUrl
            }

            createLearningMutation.mutate(submitData, {
                onSuccess: () => {
                    toast.success('یادگیری با موفقیت ایجاد شد')
                    navigate(Pages.sellers.learning)
                },
                onError: (error) => {
                    toast.error(extractErrorMessage(error))
                }
            })
        },
    })

    const categories = categoriesData?.results?.learningCategory || []
    const categoryOptions = categories.map(category => ({
        value: category._id,
        label: category.title
    }))

    console.log(formik.errors);


    return (
        <div className='mt-4'>
            <PageTitle />
            <div className='flex justify-between items-center'>
                <div className='flex items-center gap-3'>
                    <h1>ساخت یادگیری جدید</h1>
                </div>
                <div>
                    <Button
                        className='px-6'
                        onClick={() => formik.handleSubmit()}
                        isLoading={createLearningMutation.isPending || uploadSingle.isPending}
                        disabled={!formik.isValid || createLearningMutation.isPending || uploadSingle.isPending}
                    >
                        <div className='flex gap-2 items-center'>
                            <TickCircle size={16} color='#fff' />
                            <div>ثبت یادگیری</div>
                        </div>
                    </Button>
                </div>
            </div>

            <div className='flex gap-6 xl:mt-8 mt-6'>
                {/* اطلاعات اصلی */}
                <div className='flex-1 text-sm bg-white py-8 xl:px-10 px-6 rounded-3xl'>
                    <h2 className='text-lg font-medium mb-6'>اطلاعات اصلی</h2>

                    <div className='space-y-6'>
                        <Input
                            label="عنوان یادگیری"
                            placeholder="عنوان یادگیری را وارد کنید"
                            {...formik.getFieldProps('title')}
                            error_text={formik.touched.title && formik.errors.title ? formik.errors.title : ''}
                        />

                        <Textarea
                            label="توضیحات یادگیری"
                            placeholder="توضیحات یادگیری را وارد کنید"
                            {...formik.getFieldProps('description')}
                            error_text={formik.touched.description && formik.errors.description ? formik.errors.description : ''}
                        />

                        <Select
                            label="دسته‌بندی"
                            placeholder="دسته‌بندی را انتخاب کنید"
                            items={categoryOptions}
                            value={formik.values.category}
                            onChange={(e) => formik.setFieldValue('category', e.target.value)}
                            error_text={formik.touched.category && formik.errors.category ? formik.errors.category : ''}
                        />
                    </div>
                </div>

                {/* فایل‌ها */}
                <div className='w-80 space-y-6'>
                    <div className='text-sm bg-white py-8 px-6 rounded-3xl'>
                        <h2 className='text-lg font-medium mb-6'>فایل‌ها</h2>

                        <div className='space-y-6'>
                            <div>
                                <UploadBoxDraggble
                                    label='ویدیو یادگیری'
                                    isMultiple={false}
                                    onChange={(files) => setVideoFile(files)}
                                />
                            </div>

                            <div>
                                <UploadBoxDraggble
                                    label='تصویر کاور'
                                    isMultiple={false}
                                    onChange={(files) => setCoverFile(files)}
                                />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default CreateLearning
