// src/views/home/auth/Login.tsx
import { useState, useEffect } from 'react';
import { PrimaryButton } from '../../../components/button/PrimaryButton';
import { Input } from '../../../components/input/Input';
import { useAppDispatch, useAppSelector } from '../../../redux/hooks';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import { loginUser } from '../../../redux/slices/auth';
// import { cn } from "../../../lib/cn";
import { setMenuActivePage } from '../../../redux/slices/store';
import { Balloon } from '../../../assets/icons/auth';

const Login = () => {
    const dispatch = useAppDispatch();
    const navigate = useNavigate();
    const location = useLocation();

    const [username, setUsername] = useState<string>('');
    const [password, setPassword] = useState<string>('');
    const [submitClicked, setSubmitClicked] = useState<boolean>(false);

    const { status, jwt } = useAppSelector((state) => state.auth);

    // const [err, setErr] = useState<string>("");

    // После успешного логина
    useEffect(() => {
        dispatch(setMenuActivePage('account'));
    }, []);

    useEffect(() => {
        if (jwt) {
            const from = location.state?.from;
            const path = from ? from.pathname + from.search : '/home/account';
            navigate(path, { replace: true });
        }
    }, [jwt]);

    const handleLogin = () => {
        // setErr(err == "" ? "Неверная почта и/или пароль" : "");
        setSubmitClicked(true);

        if (!username || !password) return;

        dispatch(loginUser({ username, password }));
    };

    const getErrorLoginMessage = (): string => {
        if (!submitClicked) return '';
        if (username == '') return 'Поле не может быть пустым';
        if (password == '') return '';
        if (status === 'failed')
            return 'Неверное имя пользователя и/или пароль';
        return '';
    };

    const getErrorPasswordMessage = (): string => {
        if (!submitClicked) return '';
        if (password == '') return 'Поле не может быть пустым';
        return '';
    };

    return (
        <div className="h-svh w-svw fixed pointer-events-none top-0 left-0 flex items-center justify-center">
            <div className="grid gap-[80px] grid-cols-[400px,384px]  box-border relative ">
                <div className="flex items-center justify-center ">
                    <img src={Balloon} />
                </div>
                <div className=" relative pointer-events-auto">
                    <div>
                        <div className="text-[35px] text-liquid-white font-bold h-[50px]">
                            С возвращением
                        </div>
                        <div className="text-[18px] text-liquid-light font-bold h-[23px]">
                            Вход в аккаунт
                        </div>
                    </div>

                    <Input
                        name="login"
                        autocomplete="login"
                        className="mt-[10px]"
                        type="text"
                        label="Логин"
                        onChange={(v) => {
                            setUsername(v);
                        }}
                        placeholder="login"
                        error={getErrorLoginMessage()}
                    />
                    <Input
                        name="password"
                        autocomplete="password"
                        className="mt-[10px]"
                        type="password"
                        label="Пароль"
                        onChange={(v) => {
                            setPassword(v);
                        }}
                        placeholder="abCD1234"
                        error={getErrorPasswordMessage()}
                    />

                    <div className="flex justify-end mt-[10px] h-[20px]">
                        
                    </div>

                    <div className="mt-[10px]">
                        <PrimaryButton
                            className="w-full mb-[8px]"
                            onClick={handleLogin}
                            text={status === 'loading' ? 'Вход...' : 'Вход'}
                            disabled={status === 'loading'}
                        />
                    </div>

                    <div className="flex justify-center mt-[10px]">
                        <span>
                            Нет аккаунта?{' '}
                            <Link
                                to={'/home/register'}
                                className={
                                    'text-liquid-brightmain text-[16px] h-[20px] transition-all hover:underline '
                                }
                            >
                                Регистрация
                            </Link>
                        </span>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Login;
