import 'dayjs/locale/ru'; // load on demand

import { useState } from 'react';

import dayjs from 'dayjs';
import {
  Block,
  Button,
  List,
  ListInput,
  Navbar,
  Page,
} from 'konsta/react';
import { observer } from 'mobx-react';
import { CgSpinner } from 'react-icons/cg';

import { rpc } from '../../api/request';
import { ROUTER } from '../../router/router';

dayjs.locale("ru");


const LoginPage = () => {


    const [login, setLogin] = useState<string>("");
    const [password, setPassword] = useState<string>("");


    const [isLoading, setIsLoading] = useState<boolean>(false);

    const onAuth = () => {
        setIsLoading(true);
        rpc.auth({
            login: login,
            password: password,
        }).then(({ result }) => {

            if (result) {
                localStorage.setItem('token', result);
                ROUTER().MainPage.move({});
            }

        }).catch((error) => {

            setIsLoading(false);
        });

    }

    return (
        <Page className="ios:bg-white ios:dark:bg-black overflow-hidden">

            <Navbar title="Вход" large />



            <List dividers outline >
                <ListInput label="Логин" placeholder="Введите логин" value={login} onChange={(e) => setLogin(e.target.value)} />
                <ListInput label="Пароль" placeholder="Введите пароль" value={password} onChange={(e) => setPassword(e.target.value)} />

            </List>

            <Block>
                <Button
                    disabled={!login || !password || isLoading}
                    large
                    outline
                    onClick={() => {
                        onAuth();
                    }}>{isLoading ? <CgSpinner className='animate-spin' /> : 'Вход'}</Button>

            </Block>


        </Page>


    );
};

export default observer(LoginPage);
