import React, { useState } from 'react';
import { FormikComponent } from 'components/form/formik-component';
import { LoginBasic } from './login-basic';
import { navigate } from '@reach/router';

interface loginData {
  username: string;
  password: string;
}

export const LoginFormular = () => {
  const [error, setError] = useState('');

  async function onLoginSubmit(data: loginData) {
    setError('');
    const response = await fetch('http://localhost:8000/user/signin', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });

    const result = await response.json();

    if (!result.ok) {
      setError(result.message);
    } else {
      await localStorage.setItem('user', JSON.stringify(result.data));
      navigate('/');
    }
  }

  return (
    <FormikComponent
      initialValues={{
        login: '',
        password: '',
      }}
      api="user/login"
      onSubmit={onLoginSubmit}
      submitLabel="Přihlásit se"
      customError={error}
    >
      <LoginBasic />
    </FormikComponent>
  );
};
