import DefaulModal from '@/components/DefaulModal'
import { Button } from '@/components/ui/button'
import { FC } from 'react'
import { useForm } from 'react-hook-form'
import { AddQuestionProps } from '../types/Types'
import * as yup from 'yup'
import { yupResolver } from '@hookform/resolvers/yup'
import { Textarea } from '@/components/ui/textarea'
import { useParams } from 'next/navigation'
import { useAddQuestion } from '../hooks/useProductData'
import { toast } from '@/components/Toast'
import { extractErrorMessage } from '@/helpers/errorUtils'

type Props = {
    open: boolean,
    close: () => void,
}

const AddQuestion: FC<Props> = (props) => {
    const { open, close } = props
    const { id } = useParams()
    const { mutate: addQuestion, isPending } = useAddQuestion()

    const validationSchema = yup.object({
        content: yup.string().required('متن سوال خود را وارد کنید'),
        productId: yup.string().optional()
    })

    const {
        register,
        handleSubmit,
        formState: { errors },
        reset
    } = useForm({
        resolver: yupResolver(validationSchema),
        defaultValues: {
            content: '',
            productId: id as string
        }
    })

    const onSubmit = (data: AddQuestionProps) => {
        addQuestion(data, {
            onSuccess: (res) => {
                toast(res?.results?.message, 'success')
                reset()
                close()
            },
            onError: (error: Error) => {
                toast(extractErrorMessage(error), 'error')
            }
        })
    }

    return (
        <DefaulModal
            open={open}
            close={close}
            isHeader
            title_header='ثبت سوال'
        >
            <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
                {/* متن سوال */}
                <div className="space-y-2">
                    <label className="text-sm font-medium text-gray-700">
                        متن سوال شما
                    </label>
                    <Textarea
                        {...register('content')}
                        placeholder="سوال خود را در مورد این محصول بپرسید..."
                        className="w-full h-32 p-3 text-sm rounded-xl border border-[#D0D0D0] resize-none focus:outline-none focus:ring-2 focus:ring-primary/20"
                        error_text={errors.content?.message}
                    />
                </div>

                {/* دکمه ثبت */}
                <Button
                    type="submit"
                    className="w-full"
                    isLoading={isPending}
                >
                    ثبت سوال
                </Button>
            </form>
        </DefaulModal>
    )
}

export default AddQuestion