"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 { useQuestionsGetDataQuery } from '@/services/questions';
import { SchoolsCreate, useLazySchoolsGetDataByIdQuery, useSchoolsCreateMutation, useSchoolsRemoveMutation, useSchoolsUpdateMutation } from '@/services/school';
export interface FormValues extends SchoolsCreate {


}

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

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


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



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



    });
    const [SchoolsCreate, { isLoading: isLoadingSchoolsCreate }] = useSchoolsCreateMutation();
    const [SchoolsUpdate, { isLoading: isLoadingSchoolsUpdate }] = useSchoolsUpdateMutation();

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

        try {


            if (id) {
                await SchoolsUpdate({
                    id: String(id),
                    ...values
                }).unwrap();
            } else {
                await SchoolsCreate({
                    ...values
                }).unwrap();
            }


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

        } 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 [SchoolsRemove, { isLoading: isLoadingSchoolsRemove }] = useSchoolsRemoveMutation();
    const handleRemove = async () => {
        try {
            await SchoolsRemove({ id: id }).unwrap();
            // toast.success(t("deleted-successfully"), { autoClose: 3000 });
            router.push('/schools')
        } 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("schools")} />
                {isFetching ?
                    <LoadingForm /> :
                    <Formik<FormValues>
                        initialValues={{
                            name: DataSchoolsGetDataById?.info.name ?? "",
                            address: DataSchoolsGetDataById?.info.address ?? "",
                            email: DataSchoolsGetDataById?.info.email ?? "",
                            phone: DataSchoolsGetDataById?.info.phone ?? "",
                            notes: DataSchoolsGetDataById?.info.notes ?? "",
                            status: DataSchoolsGetDataById?.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('schools-information')}
                                    </div>

                                    <InputForm
                                        formikProps={props}
                                        name={'name'}
                                        title={t('name')}
                                        placeholder={t('enter-name')}
                                    />
                                    <InputForm
                                        formikProps={props}
                                        name={'address'}
                                        title={t('address')}
                                        placeholder={t('enter-address')}
                                    />

                                    <InputForm
                                        formikProps={props}
                                        name={'email'}
                                        title={t('email')}
                                        placeholder={t('enter-email')}
                                    />
                                    <InputForm
                                        formikProps={props}
                                        name={'phone'}
                                        title={t('phone')}
                                        placeholder={t('enter-phone')}
                                    />
                                    <InputForm
                                        formikProps={props}
                                        name={'notes'}
                                        title={t('notes')}
                                        placeholder={t('enter-notes')}
                                    />



                                    {/* <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 ?? "")
                                            }
                                        }}
                                    /> */}




                                </div>

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

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

export default CreateOrUpdateSchoolsComponent