import Input from 'elements/Input';
import Button from 'elements/Button';
import styles from './Form.module.scss';
import { H3 } from 'elements/H';
import { useRouter } from 'next/router';
import Error from 'elements/Error';
import getConfig from 'next/config';
import axios from 'axios';
import { useState } from 'react';

const { publicRuntimeConfig: config } = getConfig();

export default function Form() {
  const router = useRouter();
  const [hasError, setError] = useState(false);
  const error = hasError ? <Error>Неверный логин или пароль</Error> : null;

  return (
    <form
      className={styles.form}
      onSubmit={(e) => {
        e.preventDefault();

        const login = e.target[0].value;
        const password = e.target[1].value;
        const data = { login, password };

        axios
          .post('/signin', data)
          .then(() => {
            router.reload();
          })
          .catch(() => {
            setError(true);
          });
      }}
    >
      <H3>{config.appTitle}</H3>
      <Input name="login" type="text" placeholder="Логин" required autoComplete="on" />
      <Input name="password" type="password" placeholder="Пароль" required autoComplete="on" />
      {error}
      <Button>Войти</Button>
    </form>
  );
}
