import { type FC, useState } from 'react'
import { useFormik } from 'formik'
import { type BlogFormType, type BlogCategory } from './types/Types'
import * as Yup from 'yup'
import { useCreateBlog, useGetBlogCategories } from './hooks/useBlogsData'
import { useNavigate } from 'react-router-dom'
import Button from '../../components/Button'
import { TickCircle } from 'iconsax-react'
import { useUploadSingle } from '../uploader/hooks/useUploaderData'
import { toast } from 'react-toastify'
import { extractErrorMessage } from '@/helpers/utils'
import { BlogFormFields, FileUploadSection } from './components'
import { Pages } from '@/config/Pages'

const CreateBlog: FC = () => {
    const navigate = useNavigate()
    const { data: categoriesData } = useGetBlogCategories()
    const uploadSingle = useUploadSingle()
    const createBlogMutation = useCreateBlog()

    const [imageFile, setImageFile] = useState<File[]>([])

    const formik = useFormik<BlogFormType>({
        initialValues: {
            title_fa: '',
            slug: '',
            category: '',
            description: '',
            content: '',
            tags: [],
            imageUrl: '',
        },
        validationSchema: Yup.object({
            title_fa: Yup.string().required('عنوان فارسی بلاگ الزامی است'),
            slug: Yup.string().required('اسلاگ بلاگ الزامی است'),
            category: Yup.string().required('دسته بندی بلاگ الزامی است'),
            description: Yup.string().required('توضیحات بلاگ الزامی است'),
            content: Yup.string().required('محتوای بلاگ الزامی است'),
        }),
        onSubmit: async (values) => {
            let imageUrl = values.imageUrl

            if (imageFile.length > 0) {
                const imageResponse = await uploadSingle.mutateAsync(imageFile[0])
                imageUrl = imageResponse.results?.url?.url || ''
            }

            const submitData = {
                ...values,
                imageUrl
            }

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

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

    return (
        <div className='mt-4'>
            <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={createBlogMutation.isPending || uploadSingle.isPending}
                        disabled={!formik.isValid || createBlogMutation.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>
                    <BlogFormFields formik={formik} categoryOptions={categoryOptions} />
                </div>

                {/* فایل‌ها */}
                <FileUploadSection onFileChange={setImageFile} />
            </div>
        </div>
    )
}

export default CreateBlog