import { type FC } from 'react'
import PageTitle from '../../components/PageTitle'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import { useGetContentContract, useUpdateContract } from './hooks/useSellerData'
import PageLoading from '@/components/PageLoading'
import Error from '@/components/Error'
import Button from '@/components/Button'
import TextEditor from '@/components/TextEditor'
import { TickCircle } from 'iconsax-react'
import { toast } from 'react-toastify'
import { extractErrorMessage } from '@/helpers/utils'

const validationSchema = Yup.object().shape({
    content: Yup.string().required('محتوای قرارداد الزامی است')
})

const ContractPage: FC = () => {
    const { data: contentContract, isLoading, error } = useGetContentContract()
    const updateContractMutation = useUpdateContract()

    const contract = contentContract?.results?.contract
    const isDataLoaded = !!contract

    const formik = useFormik({
        initialValues: {
            id: contract?._id || '',
            content: contract?.content || '<p>در حال بارگذاری...</p>'
        },
        validationSchema,
        enableReinitialize: true,
        onSubmit: async (values) => {
            updateContractMutation.mutate({
                id: values.id,
                content: values.content
            }, {
                onSuccess: () => {
                    toast.success('قرارداد با موفقیت بروزرسانی شد')
                },
                onError: (error) => {
                    toast.error(extractErrorMessage(error))
                }
            })
        }
    })


    if (isLoading) {
        return <PageLoading />
    }

    if (error) {
        return <Error errorText="خطا در بارگذاری قرارداد" />
    }

    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={updateContractMutation.isPending}
                        disabled={!isDataLoaded || !formik.isValid || updateContractMutation.isPending}
                    >
                        <div className='flex gap-2 items-center'>
                            <TickCircle size={16} color='#fff' />
                            <div>بروزرسانی قرارداد</div>
                        </div>
                    </Button>
                </div>
            </div>

            <div className='xl:mt-8 mt-6'>
                <div className='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'>
                        <TextEditor
                            key={isDataLoaded ? 'loaded' : 'loading'}
                            value={formik.values.content}
                            onChange={(value) => formik.setFieldValue('content', value)}
                            placeholder='محتوای قرارداد را وارد کنید...'
                            height='h-[400px]'
                        />
                        {formik.touched.content && formik.errors.content && (
                            <div className='text-red-500 text-sm mt-1'>
                                {String(formik.errors.content)}
                            </div>
                        )}
                    </div>
                </div>
            </div>
        </div>
    )
}

export default ContractPage