import 'dayjs/locale/ru';

import { useState } from 'react';

import dayjs from 'dayjs';
import { observer } from 'mobx-react';
import { HiOutlineChatBubbleLeftRight } from 'react-icons/hi2';

import { rpc } from '../../api/request';
import Button from '../../ui/Button';
import Input from '../../ui/Input';
import Page from '../../ui/Page';

dayjs.locale('ru');

const LoginPage = () => {
  const [login, setLogin] = useState('');
  const [password, setPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const onAuth = () => {
    setError(null);
    setIsLoading(true);
    rpc
      .auth({ login, password })
      .then(({ result }) => {
        if (result) {
          localStorage.setItem('token', result);
          window.location.reload();
        } else {
          setError('Неверный логин или пароль');
          setIsLoading(false);
        }
      })
      .catch(() => {
        setError('Ошибка входа');
        setIsLoading(false);
      });
  };

  return (
    <Page className="items-center justify-center">
      <div className="w-full max-w-[380px] px-6 flex flex-col items-center my-auto">
        <div
          className="w-20 h-20 rounded-full flex items-center justify-center mb-6
            shadow-[0_8px_24px_rgba(51,144,236,0.35)]"
          style={{
            background:
              'linear-gradient(135deg, var(--tg-accent) 0%, #5eaaf3 100%)',
          }}
        >
          <HiOutlineChatBubbleLeftRight className="w-10 h-10 text-white" />
        </div>
        <h1 className="text-[24px] font-semibold text-[var(--tg-text-primary)] mb-1">
          Вход в чат
        </h1>
        <p className="text-[14px] text-[var(--tg-text-secondary)] mb-7 text-center">
          Введите данные для входа в аккаунт
        </p>

        <div className="w-full space-y-3 mb-2">
          <Input
            label="Логин"
            placeholder="Введите логин"
            value={login}
            onChange={setLogin}
          />
          <Input
            label="Пароль"
            type="password"
            placeholder="Введите пароль"
            value={password}
            onChange={setPassword}
          />
        </div>

        {error && (
          <div className="text-[13px] text-[var(--tg-danger)] my-1.5 px-1 w-full">
            {error}
          </div>
        )}

        <Button
          fullWidth
          size="lg"
          loading={isLoading}
          disabled={!login || !password}
          onClick={onAuth}
          className="mt-4"
        >
          Войти
        </Button>
      </div>
    </Page>
  );
};

export default observer(LoginPage);
