"use client"
import { InputForm } from '@/components/Form/inputForm';
import { Form, Formik, FormikHelpers, FormikProps } from 'formik';
import React, { useEffect, useState } from 'react';
import * as Yup from 'yup';
// import { toast } from 'react-toastify';
import { BackButton } from '@/components/common/BackButton';

import { ButtonForm } from '@/components/Form/ButtonForm';
import { LoadingForm } from '@/components/Form/loadingForm';
import { getTranslation } from '../../../../i18n';
import { ChoiceDataResponse, useLazyChoiceGetDataByIdQuery, useChoiceCreateMutation, useChoiceRemoveMutation, useChoiceUpdateMutation } from '@/services/choice';
import { useRouter } from 'next/navigation';
import { SelectForm } from '@/components/Form/SelectForm';
import DeleteModel from '@/components/common/DeleteModel';
import { UploadFileForm } from '@/components/Form/uploadFileForm';
import { BASE_URL } from '@/services/api';
import { useQuestionsGetDataQuery } from '@/services/questions';
 export interface FormValues extends ChoiceDataResponse {


}

const CreateOrUpdateChoiceComponent = ({ id }: { id: string }) => {
    const { t }: any = getTranslation();
    const router = useRouter();

    const [ChoiceGetDataById, { currentData: DataChoiceGetDataById, isFetching }] = useLazyChoiceGetDataByIdQuery()
    const [search, setSearch] = useState('')
    const { isFetching: isFetchingQuestion, currentData: DataQuestion } = useQuestionsGetDataQuery({
        page: 1,
        paginate: 1000,
        search
    });


    useEffect(() => {
        if (id) {
            ChoiceGetDataById({ id: String(id) })
        }
    }, [id])



    const validationSchema = Yup.object().shape({
        // title: Yup.string().required(t('this-field-is-required')),



    });
    const [ChoiceCreate, { isLoading: isLoadingChoiceCreate }] = useChoiceCreateMutation();
    const [ChoiceUpdate, { isLoading: isLoadingChoiceUpdate }] = useChoiceUpdateMutation();

    const handleSubmit = async (values: FormValues, { setSubmitting, resetForm }: FormikHelpers<FormValues>) => {

        try {


            if (id) {
                await ChoiceUpdate({
                    id: String(id),
                    ...values
                }).unwrap();
            } else {
                await ChoiceCreate({
                    ...values
                }).unwrap();
            }


            // toast.success(t(id ? "updated-successfully" : "added-successfully"), { autoClose: 3000 });
            resetForm();
            router.push('/choice')

        } catch (error: any) {
            console.error('Failed to operation :', error);
            if (error && error.message) {
                // return toast.error(error.message, { autoClose: 3000 });
            }
            // toast.error(error, { autoClose: 3000 });
        }

    };
    const [ChoiceRemove, { isLoading: isLoadingChoiceRemove }] = useChoiceRemoveMutation();
    const handleRemove = async () => {
        try {
            await ChoiceRemove({ id: id }).unwrap();
            // toast.success(t("deleted-successfully"), { autoClose: 3000 });
            router.push('/choice')
        } catch (error: any) {
            console.error('Failed to operation :', error);
            if (error && error.message) {
                // return toast.error(error.message, { autoClose: 3000 });
            }
            // toast.error(error, { autoClose: 3000 });
        }
    };

    return (
        <>

            <div className="mx-auto my-0 max-md:max-w-[100%] md:max-w-[50%]">
                <BackButton title={t("choice")} />
                {isFetching ?
                    <LoadingForm /> :
                    <Formik<FormValues>
                        initialValues={{
                            choice: DataChoiceGetDataById?.info.choice ?? "",
                            questionId: DataChoiceGetDataById?.info.questionId ?? "",
                            status: DataChoiceGetDataById?.info.status ?? true,
                        }}
                        validationSchema={validationSchema}
                        onSubmit={handleSubmit}

                    >

                        {(props: FormikProps<any>) => (
                            <Form className={'p-4 flex flex-col gap-4'}>

                                <div className="Card">
                                    <div className=" text-base font-semibold text-black dark:text-white-dark  mb-2 ">
                                        {t('choice-information')}
                                    </div>

                                    <InputForm
                                        formikProps={props}
                                        name={'choice'}
                                        title={t('choice')}
                                        placeholder={t('enter-choice')}
                                    /> 
                                    <SelectForm
                                        formikProps={props}
                                        name={'questionId'}
                                        title={t('questionId')}
                                        placeholder={t('choses-questionId')}
                                        options={DataQuestion?.details?.docs?.map((item) => {
                                            return { label: item.question, value: item.id }
                                        })
                                            ?? [] as any
                                        }
                                        props={
                                            {
                                                isLoading: isFetchingQuestion,
                                                isClearable: true,
                                                onInputChange: (value) => {
                                                    setSearch(value)
                                                },
                                                onChange: (value) => {
                                                    props.setFieldValue('questionId', (value as any)?.value ?? "" as any)
                                                }

                                            }

                                        }
                                    /> 
                                    <SelectForm
                                        formikProps={props}
                                        name={'status'}
                                        title={t('status')}
                                        placeholder={t('choses-status')}
                                        options={[
                                            { label: t('active'), value: "true" },
                                            { label: t('inactive'), value: "false" },
                                        ]}

                                    />

                                </div>

                                <div className='flex flex-row-reverse gap-2'>
                                    <ButtonForm
                                        title={t(id ? "update" : 'add')}
                                        isLoading={isLoadingChoiceCreate || isLoadingChoiceUpdate}

                                    />
                                    {
                                        id && <ButtonForm
                                            props={{
                                                onClick: () => {
                                                    router.push(`/choice/createOrUpdate?id=${id}&openDeleteModel=true`)
                                                },
                                                type: 'button',
                                                className: " hover:!bg-danger/10 !border-danger/70 !text-danger/70 !bg-transparent "
                                            }}
                                            title={t('delete')}
                                            isLoading={false}
                                        />
                                    }
                                </div>
                            </Form>
                        )
                        }
                    </Formik>
                }
            </div>
            <DeleteModel name={String(DataChoiceGetDataById?.info.choice)} title={t('delete-choice')} handleRemove={handleRemove} isLoading={isLoadingChoiceRemove} description={t('are-you-sure-you-want-to-delete-this-choice')} />
        </>
    );
};

export default CreateOrUpdateChoiceComponent