"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PHXLoginV3 = void 0;
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importStar(require("react"));
const react_hook_form_1 = require("react-hook-form");
const Input_1 = require("../Input");
const Button_1 = require("../Button");
const Banner_1 = require("../Banner");
const read_env_config_1 = require("../../read-env-config");
const saveCookiesClient_1 = tslib_1.__importDefault(require("../Func/saveCookiesClient"));
const Checkbox_1 = require("../Checkbox");
const login_style_1 = tslib_1.__importDefault(require("./login-style"));
const getCookieSession_1 = tslib_1.__importDefault(require("../Func/getCookieSession"));
const PHXLoginV3 = (props) => {
    const { logo, banner, router, redirectPath, buttonColor } = props;
    const [remember, setRemember] = (0, react_1.useState)(true);
    const [loginError, setLoginError] = (0, react_1.useState)(false);
    const [loading, setLoading] = (0, react_1.useState)(false);
    const schoolLogo = (0, read_env_config_1.getEnv)('NEXT_PUBLIC_ENV_LOGIN_LOGO', process.env.NEXT_PUBLIC_ENV_LOGIN_LOGO);
    const { handleSubmit, register, formState: { errors }, } = (0, react_hook_form_1.useForm)();
    const handleLogin = async (email, password) => {
        try {
            const response = await fetch(`/api/authenticate/login`, {
                headers: {
                    'Content-Type': 'application/json',
                },
                method: 'post',
                body: JSON.stringify({
                    email,
                    password,
                }),
                credentials: 'include',
            });
            if (!response.ok)
                return;
            return await response.json();
        }
        catch (error) {
            console.error(error);
            return null;
        }
    };
    const onSubmitForm = async (values) => {
        const { email, password } = values;
        setLoading(true);
        const response = await handleLogin(email, password);
        // sai thông tin đăng nhập
        if (!response) {
            console.log('login lỗi');
            setLoginError(true);
            setLoading(false);
            return;
        }
        // ghi nhớ tài khoản
        const { userInfo, token } = response;
        (0, saveCookiesClient_1.default)({ value: { ...userSessionInfo, user_info: userInfo, access_token: token } });
        if (userInfo && userInfo.user_roles[0].role.role_code) {
            setLoading(false);
            setLoginError(false);
            router.push(redirectPath);
        }
        else {
            setLoginError(true);
            setLoading(false);
        }
    };
    const userSessionInfo = (0, getCookieSession_1.default)();
    // nếu đã có token login thì push về dasboard
    (0, react_1.useEffect)(() => {
        if (userSessionInfo && (userSessionInfo === null || userSessionInfo === void 0 ? void 0 : userSessionInfo.access_token)) {
            window.location.replace(redirectPath);
        }
    }, [userSessionInfo]);
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement(login_style_1.default, { buttonColor: buttonColor }),
        react_1.default.createElement("main", { className: 'flex min-h-full' },
            react_1.default.createElement("div", { className: 'm-auto flex h-[100vh] max-w-[100vw] flex-1 justify-center' },
                react_1.default.createElement("div", { className: 'flex flex-1 flex-col justify-center px-4 py-12 sm:px-6 lg:flex-none lg:px-20 xl:px-24' },
                    react_1.default.createElement("div", { className: 'lg:w-76 w-full xl:w-96' },
                        react_1.default.createElement("div", { className: 'flex flex-col' },
                            react_1.default.createElement("img", { className: 'max-w-[240px] mb-3', src: logo !== null && logo !== void 0 ? logo : `${schoolLogo}`, alt: 'logo' }),
                            react_1.default.createElement("h2", { style: { fontWeight: '600' }, className: 'mt-3 text-2xl leading-9 tracking-tight text-gray-900' }, "\u0110\u0103ng nh\u1EADp h\u1EC7 th\u1ED1ng"),
                            loginError && (react_1.default.createElement("div", { className: 'w-full' },
                                react_1.default.createElement(Banner_1.PHXBanner, { show: loginError, className: 'mt-4 mb-2', onClose: () => setLoginError(false), type: 'danger', title: '\u0110\u0103ng nh\u1EADp th\u1EA5t b\u1EA1i', description: 'Th\u00F4ng tin t\u00E0i kho\u1EA3n kh\u00F4ng ch\u00EDnh x\u00E1c.' }))),
                            react_1.default.createElement("form", { onSubmit: handleSubmit(onSubmitForm) },
                                react_1.default.createElement("div", { className: 'space-y-6' },
                                    react_1.default.createElement("div", { className: 'mt-2' },
                                        react_1.default.createElement(Input_1.PHXInput, { errorType: 'custom-message', label: 'Email', 
                                            //@ts-ignore
                                            error: errors.email, register: register('email', {
                                                required: true,
                                            }), errorMessageCustom: 'Vui l\u00F2ng nh\u1EADp email' })),
                                    react_1.default.createElement(Input_1.PHXInput, { errorType: 'custom-message', 
                                        //@ts-ignore
                                        error: errors.password, errorMessageCustom: 'Vui l\u00F2ng nh\u1EADp m\u1EADt kh\u1EA9u', register: register('password', {
                                            required: true,
                                        }), label: 'Password', type: 'password', id: 'password' }),
                                    react_1.default.createElement(Checkbox_1.PHXCheckbox, { defaultChecked: remember, title: 'Ghi nh\u1EDB t\u00E0i kho\u1EA3n', onChange: (e) => setRemember(e.target.checked) }),
                                    react_1.default.createElement(Button_1.PHXButton, { loading: loading, className: 'w-full', primary: true, submit: true, size: 'large' }, "\u0110\u0103ng nh\u1EADp")))))),
                react_1.default.createElement("div", { className: 'relative hidden w-0 flex-1 lg:block lg:w-full' },
                    react_1.default.createElement("img", { className: 'absolute inset-0 h-full w-full object-cover', src: banner !== null && banner !== void 0 ? banner : 'https://images.unsplash.com/photo-1496917756835-20cb06e75b4e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1908&q=80', alt: 'banner' }))))));
};
exports.PHXLoginV3 = PHXLoginV3;
exports.default = exports.PHXLoginV3;
//# sourceMappingURL=LoginV3.js.map