"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 { useRouter } from 'next/navigation';
import { OptionType, SelectForm } from '@/components/Form/SelectForm';
import DeleteModel from '@/components/common/DeleteModel';
import { PracVideoCreate, useLazyPracVideoGetDataByIdQuery, usePracVideoCreateMutation, usePracVideoRemoveMutation, usePracVideoUpdateMutation } from '@/services/PracVideo';
import { usePracListGetDataQuery } from '@/services/PracList';
export interface FormValues extends PracVideoCreate {


}

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

    const [PracvideoGetDataById, { currentData: DataPracvideoGetDataById, isFetching }] = useLazyPracVideoGetDataByIdQuery()
    const [search, setSearch] = useState('')
    const { isFetching: isFetchingPracList, currentData: DataPracList } = usePracListGetDataQuery({
        page: 1,
        paginate: 1000,
        search
    });


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



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



    });
    const [PracvideoCreate, { isLoading: isLoadingPracvideoCreate }] = usePracVideoCreateMutation();
    const [PracvideoUpdate, { isLoading: isLoadingPracvideoUpdate }] = usePracVideoUpdateMutation();

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

        try {


            if (id) {
                await PracvideoUpdate({
                    id: String(id),
                    ...values
                }).unwrap();
            } else {
                await PracvideoCreate({
                    ...values
                }).unwrap();
            }


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

        } 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 [PracvideoRemove, { isLoading: isLoadingPracvideoRemove }] = usePracVideoRemoveMutation();
    const handleRemove = async () => {
        try {
            await PracvideoRemove({ id: id }).unwrap();
            // toast.success(t("deleted-successfully"), { autoClose: 3000 });
            router.push('/pracvideo')
        } 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("pracvideo")} />
                {isFetching ?
                    <LoadingForm /> :
                    <Formik<FormValues>
                        initialValues={{
                            title: DataPracvideoGetDataById?.info.title ?? "",
                            description: DataPracvideoGetDataById?.info.description ?? "",
                            pracListId: DataPracvideoGetDataById?.info.pracListId ?? "",
                            status: DataPracvideoGetDataById?.info.status ?? true,
                            videoUrl: DataPracvideoGetDataById?.info.videoUrl ?? "",
                        }}
                        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('pracvideo-information')}
                                    </div>

                                    <InputForm
                                        formikProps={props}
                                        name={'title'}
                                        title={t('title')}
                                        placeholder={t('enter-title')}
                                    />
                                    <InputForm
                                        formikProps={props}
                                        name={'description'}
                                        title={t('description')}
                                        placeholder={t('enter-description')}
                                    />
                                    <InputForm
                                        formikProps={props}
                                        name={'videoUrl'}
                                        title={t('videoUrl')}
                                        placeholder={t('enter-videoUrl')}
                                    />
                                    {/* <SelectForm
                                        formikProps={props}
                                        name={'status'}
                                        title={t('status')}
                                        placeholder={t('choses-status')}
                                        options={[
                                            { label: t('active'), value: "true" },
                                            { label: t('inactive'), value: "false" }
                                        ]}
                                        props={{
                                            isClearable: true,
                                            onChange: (val) => {
                                                props.setFieldValue('status', (val as OptionType)?.value ?? "")
                                            }
                                        }}
                                    /> */}
                                    <SelectForm
                                        formikProps={props}
                                        name={'pracListId'}
                                        title={t('pracList')}
                                        placeholder={t('choses-pracList')}
                                        options={DataPracList?.details?.docs.map((item) => ({ label: item.title, value: item.id })) as []}
                                        props={{
                                            isLoading: isFetchingPracList,
                                            isClearable: true,
                                            onChange: (val) => {
                                                props.setFieldValue('pracListId', (val as OptionType)?.value ?? "")
                                            }
                                        }}
                                    />

                                </div>

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

                                    />
                                    {
                                        id && <ButtonForm
                                            props={{
                                                onClick: () => {
                                                    router.push(`/pracvideo/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(DataPracvideoGetDataById?.info.title)} title={t('delete-pracvideo')} handleRemove={handleRemove} isLoading={isLoadingPracvideoRemove} description={t('are-you-sure-you-want-to-delete-this-pracvideo')} />
        </>
    );
};

export default CreateOrUpdatePracvideoComponent