import React from "react";
import { useNavigate } from "react-router-dom";

import { ButtonUi, ButtonUiType } from "../../../../shared/UI/ButtonUi";

import Form from 'react-bootstrap/Form';

import { useFormik } from 'formik';
import * as yup from 'yup';

import { AuthResponsePayload } from '../../../../types';
import { api } from "../../../../query/query";
import { setCookie } from "typescript-cookie";
import styles from "./authLoginForm.module.scss";

export const AuthLoginFormUi = () => {

    const navigate = useNavigate();

    const schema = yup.object().shape({
        username: yup.string()
            .min(3, 'Минимум 3 символа!')
            .max(16, 'Максимум 16 символов!')
            .required('Это поле обязательное.'),

        password: yup.string().required('Это обязательное поле.').min(6, 'Минимум 6 символов!'),
    });

    const {
        handleSubmit,
        handleChange,
        handleBlur,
        errors,
        values,
        setFieldError
    } = useFormik({
        initialValues: {
            username: '',
            password: '',
        },
        validationSchema: schema,
        onSubmit: async (values): Promise<AuthResponsePayload> => {
            return await api.post('/authorization', {
                username: values.username,
                password: values.password
            }).then((res) => {
                if (res.data[0]) {
                    setFieldError('username', res.data[0])
                    setFieldError('password', res.data[0])
                } else {
                    setCookie('authToken', res.data!.authToken)
                    setCookie('refreshToken', res.data!.refreshToken)
                    navigate("/auction")
                }
                return res.data as AuthResponsePayload
            })
        },
    })

    return (
        <Form noValidate className={styles.container} onSubmit={handleSubmit}>
            <Form.Group>
                <Form.Control
                    type="text"
                    id="username"
                    placeholder="username"
                    onChange={handleChange}
                    name="username"
                    onBlur={handleBlur}
                    value={values.username}
                    isInvalid={!!errors.username}
                />
                <Form.Control.Feedback type="invalid">
                    {errors.username}
                </Form.Control.Feedback>
            </Form.Group>
            <Form.Group>
                <Form.Control
                    type="password"
                    id="password"
                    placeholder="password"
                    onChange={handleChange}
                    value={values.password}
                    name="password"
                    onBlur={handleBlur}
                    isInvalid={!!errors.password}
                />
                <Form.Control.Feedback type="invalid">
                    {errors.password}
                </Form.Control.Feedback>
            </Form.Group>
            <ButtonUi title={'Войти'} variant={ButtonUiType.PRIMARY} type={'submit'}/>
        </Form >
    )
}
