import { type FC, useState, useEffect } from 'react'
import { useParams } from 'react-router-dom'
import { useFormik } from 'formik'
import { type BlogFormType } from './types/Types'
import * as Yup from 'yup'
import { useGetBlogDetail, useGetBlogCategories, useUpdateBlog } 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 UpdateBlog: FC = () => {
    const navigate = useNavigate()
    const { id } = useParams<{ id: string }>()
    const { data: blogDetail, isLoading: blogDetailLoading, error: blogDetailError } = useGetBlogDetail(id!)
    const { data: categoriesData } = useGetBlogCategories()
    const uploadSingle = useUploadSingle()
    const updateBlogMutation = useUpdateBlog()

    const [imageFile, setImageFile] = useState<File[]>([])
    const [blogId, setBlogId] = useState<string>('')

    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 || ''
            }

            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            const { slug: _slug, ...valuesWithoutSlug } = values
            const submitData = {
                ...valuesWithoutSlug,
                imageUrl
            }

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

    useEffect(() => {
        if (blogDetail) {
            setBlogId(blogDetail._id)
            formik.setValues({
                title_fa: blogDetail.title_fa,
                slug: blogDetail.slug,
                category: blogDetail.category._id,
                description: blogDetail.description,
                content: blogDetail.content,
                tags: blogDetail.tags,
                imageUrl: blogDetail.imageUrl,
            })
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [blogDetail])

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

    if (blogDetailLoading) {
        return <div>در حال بارگذاری...</div>
    }

    if (blogDetailError) {
        return <div>خطا در بارگذاری داده‌ها</div>
    }

    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={updateBlogMutation.isPending || uploadSingle.isPending}
                        disabled={!formik.isValid || updateBlogMutation.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 UpdateBlog