"use client";
import {useAppDispatch, useAppSelector} from "@/lib/redux/hooks";
import {Modal} from "antd";
import {useTranslations} from "next-intl";
import {z} from "zod";
import {useState} from "react";
import {useForm} from "react-hook-form";
import {zodResolver} from "@hookform/resolvers/zod";
import {FormItem, FormWrapper} from "@/components/ui/form";
import AppInput from "@/components/ui/input";
import AppButton from "@/components/ui/button";
import {useRouter} from "@/i18n/routing";
import {
    doCreateAppUser,
    getAppUserDetail,
} from "@/lib/redux/features/appUser";
import AppSelect from "../ui/select";
import {AppUserRole} from "@/types/appUser";
import {UserType} from "@/types/user";

export default function CreateAppUserModal({
                                               appsId,
                                               isOpenUpdateModal,
                                               setOpenUpdateModal,
                                               authInfo,
                                               fetchUserPaging,
                                           }) {
    const dispatch = useAppDispatch();
    const router = useRouter();
    const t = useTranslations("Form");
    const appUserDetail = useAppSelector(getAppUserDetail);
    const [isLoading, setIsLoading] = useState(false);

    const closeModal = () => {
        setOpenUpdateModal(false);
        updateAppSettingForm.reset();
    };

    const formSchema = z.object({
        email: z
            .string()
            .trim()
            .min(1, {message: t("validate.required")})
            .email({
                message: t("validate.email_invalid"),
            }),
        appsId: z.string(),
        role: z.string().min(1, {message: t("validate.required")}),
    });

    type CreateAppUserFormSchema = z.infer<typeof formSchema>;

    const updateAppSettingForm = useForm<CreateAppUserFormSchema>({
        resolver: zodResolver(formSchema),
        defaultValues: {
            email: "",
            appsId: "",
            role: "",
        },
    });

    async function onSubmit(values: CreateAppUserFormSchema) {
        try {
            setIsLoading(true);
            const request = {
                email: values.email,
                appsId: appsId,
                role: values.role,
            };
            const result = await dispatch(doCreateAppUser(request));
            await new Promise((resolve) => setTimeout(resolve, 500));
            if (result.payload.status === "success") {
                fetchUserPaging({appsId: appsId});
                closeModal();
                router.refresh();
            } else {
                console.error("Error creating app user:", result.payload);
            }
        } catch (error) {
            console.error("Exception when creating app user:", error);
        } finally {
            setIsLoading(false);
        }
    }

    const generateRoleOptions = () => {
        // If you are an OWNER or SUPER ADMIN, you can invite all roles.
        if (
            (authInfo?.userType === UserType.USER &&
                appUserDetail?.role === AppUserRole.OWNER) ||
            authInfo?.userType === UserType.ADMIN
        ) {
            return [
                {
                    label: t("user_role.OWNER"),
                    value: AppUserRole.OWNER,
                },
                {label: t("user_role.ADMIN"), value: AppUserRole.ADMIN},
                {label: t("user_role.DEVELOPER"), value: AppUserRole.DEVELOPER},
            ];
        }

        // // If you are an ADMIN, you can only invite ADMIN and DEVELOPER.
        if (
            authInfo?.userType === UserType.USER &&
            appUserDetail?.role === AppUserRole.ADMIN
        ) {
            return [
                {
                    label: t("user_role.OWNER"),
                    value: AppUserRole.OWNER,
                    disabled: true,
                },
                {label: t("user_role.ADMIN"), value: AppUserRole.ADMIN},
                {label: t("user_role.DEVELOPER"), value: AppUserRole.DEVELOPER},
            ];
        }

        return [];
    };

    return (
        <Modal
            title={t("invite_member")}
            open={isOpenUpdateModal}
            onOk={closeModal}
            onCancel={closeModal}
            footer={null}
        >
            <FormWrapper<CreateAppUserFormSchema>
                form={updateAppSettingForm}
                onSubmit={onSubmit}
                layout="vertical"
                className="space-y-4"
            >
                <FormItem name="email" label={t("email")}>
                    {({value, ref, ...field}) => (
                        <AppInput
                            ref={ref}
                            value={value}
                            {...field}
                            placeholder={t("email_placeholder")}
                        />
                    )}
                </FormItem>
                <div className="flex !mt-2">
                    <FormItem name="role" label={t("role")} className="!mb-0 w-full">
                        {({value, onChange, ref, ...field}) => (
                            <AppSelect
                                {...field}
                                ref={ref}
                                value={value}
                                onChange={onChange}
                                options={generateRoleOptions()}
                                placeholder={t("select_role_placeholder")}
                            />
                        )}
                    </FormItem>
                </div>

                <div className="flex justify-end items-center gap-2">
                    <AppButton
                        type="default"
                        onClick={closeModal}
                        loading={isLoading}
                        className=""
                    >
                        {t("button.cancel")}
                    </AppButton>
                    <AppButton
                        type="primary"
                        htmlType="submit"
                        loading={isLoading}
                        onClick={() => updateAppSettingForm.handleSubmit(onSubmit)}
                        className=""
                    >
                        {t("button.save")}
                    </AppButton>
                </div>
            </FormWrapper>
        </Modal>
    );
}
