import DefaulModal from '@/components/DefaulModal'
import Input from '@/components/Input'
import { Button } from '@/components/ui/button'
import { FC, useState } from 'react'
import { useForm } from 'react-hook-form'
import { AddCommentProps } from '../types/Types'
import * as yup from 'yup'
import { yupResolver } from '@hookform/resolvers/yup'
import { Add } from 'iconsax-react'
import { PRIMARY_COLOR } from '@/config/const'
import Rate from 'rc-rate'
import { Textarea } from '@/components/ui/textarea'
import { useParams } from 'next/navigation'
import { useAddComment } from '../hooks/useProductData'
import { toast } from '@/components/Toast'
import { extractErrorMessage } from '@/helpers/errorUtils'


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

const AddComment: FC<Props> = (props) => {


    const { open, close, productId: propProductId } = props
    const { id } = useParams()
    const productId = propProductId || (id as string)
    const [advantages, setAdvantages] = useState<string[]>([])
    const [disadvantages, setDisadvantages] = useState<string[]>([])
    const [currentAdvantage, setCurrentAdvantage] = useState<string>('')
    const [currentDisadvantage, setCurrentDisadvantage] = useState<string>('')
    const [rating, setRating] = useState<number>(0)
    const { mutate: addComment, isPending } = useAddComment()

    const validationSchema = yup.object({
        title: yup.string().required('عنوان خود را وارد کنید'),
        advantage: yup.array().of(yup.string().required()).required('مزایای خود را وارد کنید'),
        disAdvantage: yup.array().of(yup.string().required()).required('معایب خود را وارد کنید'),
        content: yup.string().required('محتوای خود را وارد کنید'),
        rate: yup.number().required('رای خود را وارد کنید'),
        productId: yup.string().optional()
    })

    const {
        register,
        handleSubmit,
        formState: { errors },
        setValue
    } = useForm({
        resolver: yupResolver(validationSchema),
        defaultValues: {
            title: '',
            advantage: [],
            disAdvantage: [],
            content: '',
            rate: 0,
            productId: productId
        }
    })

    const addAdvantage = () => {
        if (currentAdvantage.trim()) {
            const newAdvantages = [...advantages, currentAdvantage.trim()]
            setAdvantages(newAdvantages)
            setValue('advantage', newAdvantages)
            setCurrentAdvantage('')
        }
    }

    const removeAdvantage = (index: number) => {
        const newAdvantages = advantages.filter((_, i) => i !== index)
        setAdvantages(newAdvantages)
        setValue('advantage', newAdvantages)
    }

    const addDisadvantage = () => {
        if (currentDisadvantage.trim()) {
            const newDisadvantages = [...disadvantages, currentDisadvantage.trim()]
            setDisadvantages(newDisadvantages)
            setValue('disAdvantage', newDisadvantages)
            setCurrentDisadvantage('')
        }
    }

    const removeDisadvantage = (index: number) => {
        const newDisadvantages = disadvantages.filter((_, i) => i !== index)
        setDisadvantages(newDisadvantages)
        setValue('disAdvantage', newDisadvantages)
    }

    const handleRating = (rate: number) => {
        setRating(rate)
        setValue('rate', rate, { shouldValidate: true, shouldDirty: true })
    }

    const onSubmit = (data: AddCommentProps) => {
        addComment(data, {
            onSuccess: (res) => {
                toast(res?.results?.message, 'success')
                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">
                {/* عنوان نظر */}
                <Input
                    label="عنوان نظر"
                    {...register('title')}
                    error_text={errors.title?.message}
                    placeholder="عنوان نظر خود را وارد کنید"
                />

                <div className='relative'>
                    <Input
                        value={currentAdvantage}
                        onChange={(e) => setCurrentAdvantage(e.target.value)}
                        placeholder="نکته مثبت خود را وارد کنید"
                        className="flex-1"
                        label="نکته مثبت"
                        onKeyPress={(e) => {
                            if (e.key === 'Enter') {
                                e.preventDefault()
                                addAdvantage()
                            }
                        }}
                    />

                    <button
                        type="button"
                        onClick={addAdvantage}
                        className="absolute top-[37px] left-3 rounded"
                    >
                        <Add size={22} color={PRIMARY_COLOR} />
                    </button>
                </div>

                {/* لیست نکات مثبت اضافه شده */}
                {advantages.length > 0 && (
                    <div className="space-y-2 flex gap-4 flex-wrap">
                        {advantages.map((advantage, index) => (
                            <div key={index} className="flex min-w-[45%] flex-1 items-center justify-between bg-gray-50 py-1 px-4 rounded-lg">
                                <span className="text-sm text-gray-700">{advantage}</span>
                                <button
                                    type="button"
                                    onClick={() => removeAdvantage(index)}
                                    className="text-red-500 hover:text-red-700 p-1"
                                >
                                    ×
                                </button>
                            </div>
                        ))}
                        <div className='flex-1 min-w-[45%] px-4'></div>
                    </div>
                )}

                {/* نکات منفی */}
                <div className='relative'>
                    <Input
                        value={currentDisadvantage}
                        onChange={(e) => setCurrentDisadvantage(e.target.value)}
                        placeholder="نکته منفی خود را وارد کنید"
                        className="flex-1"
                        label="نکته منفی"
                        onKeyPress={(e) => {
                            if (e.key === 'Enter') {
                                e.preventDefault()
                                addDisadvantage()
                            }
                        }}
                    />

                    <button
                        type="button"
                        onClick={addDisadvantage}
                        className="absolute top-[37px] left-3 rounded"
                    >
                        <Add size={22} color={PRIMARY_COLOR} />
                    </button>
                </div>

                {/* لیست نکات منفی اضافه شده */}
                {disadvantages.length > 0 && (
                    <div className="space-y-2 flex gap-4 flex-wrap">
                        {disadvantages.map((disadvantage, index) => (
                            <div key={index} className="flex min-w-[45%] flex-1 items-center justify-between bg-gray-50 py-1 px-4 rounded-lg">
                                <span className="text-sm text-gray-700">{disadvantage}</span>
                                <button
                                    type="button"
                                    onClick={() => removeDisadvantage(index)}
                                    className="text-red-500 hover:text-red-700 p-1"
                                >
                                    ×
                                </button>
                            </div>
                        ))}
                        <div className='flex-1 min-w-[45%] px-4'></div>
                    </div>
                )}

                {/* امتیاز */}
                <div className="space-y-2 flex gap-1 items-center">
                    <label className="text-sm text-black">امتیاز شما:</label>
                    <div className='-mt-1.5'>
                        <Rate
                            value={rating}
                            onChange={handleRating}
                            count={5}
                            allowHalf={false}
                            style={{ fontSize: 20 }}
                        />
                    </div>
                    <input
                        type="hidden"
                        {...register('rate')}
                        value={rating}
                    />
                </div>

                {/* توضیحات */}
                <Textarea
                    {...register('content')}
                    placeholder="متن توضیحات خود را بنویسید"
                    className="w-full h-24 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}
                />

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

export default AddComment