import React, { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { PHXInput } from '../Input';
import { PHXButton } from '../Button';
import { PHXBanner } from '../Banner';
import { getEnv } from '../../read-env-config';
import saveCookiesClient from '../Func/saveCookiesClient';
import { PHXCheckbox } from '../Checkbox';
import LoginStyle from './login-style';
import PHXFuncGetCookieSession from '../Func/getCookieSession';
export const PHXLoginV3 = (props) => {
    const { logo, banner, router, redirectPath, buttonColor } = props;
    const [remember, setRemember] = useState(true);
    const [loginError, setLoginError] = useState(false);
    const [loading, setLoading] = useState(false);
    const schoolLogo = getEnv('NEXT_PUBLIC_ENV_LOGIN_LOGO', process.env.NEXT_PUBLIC_ENV_LOGIN_LOGO);
    const { handleSubmit, register, formState: { errors }, } = 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;
        saveCookiesClient({ 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 = PHXFuncGetCookieSession();
    // nếu đã có token login thì push về dasboard
    useEffect(() => {
        if (userSessionInfo && (userSessionInfo === null || userSessionInfo === void 0 ? void 0 : userSessionInfo.access_token)) {
            window.location.replace(redirectPath);
        }
    }, [userSessionInfo]);
    return (React.createElement(React.Fragment, null,
        React.createElement(LoginStyle, { buttonColor: buttonColor }),
        React.createElement("main", { className: 'flex min-h-full' },
            React.createElement("div", { className: 'm-auto flex h-[100vh] max-w-[100vw] flex-1 justify-center' },
                React.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.createElement("div", { className: 'lg:w-76 w-full xl:w-96' },
                        React.createElement("div", { className: 'flex flex-col' },
                            React.createElement("img", { className: 'max-w-[240px] mb-3', src: logo !== null && logo !== void 0 ? logo : `${schoolLogo}`, alt: 'logo' }),
                            React.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.createElement("div", { className: 'w-full' },
                                React.createElement(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.createElement("form", { onSubmit: handleSubmit(onSubmitForm) },
                                React.createElement("div", { className: 'space-y-6' },
                                    React.createElement("div", { className: 'mt-2' },
                                        React.createElement(PHXInput, { errorType: 'custom-message', label: 'Email', 
                                            //@ts-ignore
                                            error: errors.email, register: register('email', {
                                                required: true,
                                            }), errorMessageCustom: 'Vui l\u00F2ng nh\u1EADp email' })),
                                    React.createElement(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.createElement(PHXCheckbox, { defaultChecked: remember, title: 'Ghi nh\u1EDB t\u00E0i kho\u1EA3n', onChange: (e) => setRemember(e.target.checked) }),
                                    React.createElement(PHXButton, { loading: loading, className: 'w-full', primary: true, submit: true, size: 'large' }, "\u0110\u0103ng nh\u1EADp")))))),
                React.createElement("div", { className: 'relative hidden w-0 flex-1 lg:block lg:w-full' },
                    React.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' }))))));
};
export default PHXLoginV3;
//# sourceMappingURL=LoginV3.js.map