import React, { useState } from 'react';
import styled from 'styled-components';
import { Surface } from '../ui';
import { Button, TextInput, Loading } from '@nemo-ui/core';
import { $session, logoutPressed, sendLoginFromFx } from './auth-model';
import { useFormik } from 'formik';
import * as Yup from 'yup';
import {useUnit} from 'effector-react';

const Wrapper = styled.div`
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    min-height: 100vh;
`;

const FormSuface = styled(Surface)`
    padding: 24px 24px 16px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;
    width: 100%;
    max-width: 440px;

    p {
        font-style: normal;
        font-weight: 700;
        font-size: 18px;
        line-height: 24px;
        text-align: center;
    }

    .inputs {
        width: 100%;
        display: flex;
        flex-direction: column;
        gap: 8px;
        padding: 8px 0px;

        & > * {
            width: 100%;
        }
        p.error-text {
            color: red;
            font-size: 14px;
        }
    }

    .button {
        width: 100%;
    }
`;

const schema = Yup.object({
    username: Yup.string().email("Невалидный email").required("Обязательно"),
    password: Yup.string().min(6, "Минимум 6 символов").required('Обязательно'),
});

type Schema = Yup.InferType<typeof schema>;

export const AuthView: React.FC = () => {
    const [loading, setLoading] = useState<boolean>(false);

    const formik = useFormik<Schema>({
        initialValues: {
            username: '',
            password: '',
        },
        validationSchema: schema,
        onSubmit: async (values, helpers) => {
            setLoading(true);
            await new Promise((res) => {
                setTimeout(() => {
                    res(undefined)
                }, 1500);
            })
            await sendLoginFromFx({
                username: values.username,
                password: values.password,
            });

            setLoading(false);
        }
    });


    return (
        <Wrapper>
            <FormSuface>
                <p>Вход в систему Сократ</p>
                <div
                  className="inputs"
                >
                    <TextInput
                      size="large"
                      style={{ width: '100%' }}
                      placeholder="login user@ibs.ru"
                      inputProps={{
                            ...formik.getFieldProps("username")
                        }}
                      error={formik.touched.username && formik.errors.username}
                      disabled={loading}
                    />
                    {formik.touched.username && formik.errors.username && (
                        <p
                          className="error-text"
                        >
                            {formik.errors.username}
                        </p>
                    )}
                    <TextInput
                      size="large"
                      style={{ width: '100%' }}
                      placeholder="password"
                      inputProps={{
                            ...formik.getFieldProps("password"),
                            type: "password"
                        }}
                      error={formik.touched.password && formik.errors.password}
                      disabled={loading}
                    />
                    {formik.touched.password && formik.errors.password && (
                        <p
                          className="error-text"
                        >
                            {formik.errors.password}
                        </p>
                    )}
                    
                    
                </div>
                <Button
                  className="button"
                  onClick={() => {
                    void formik.submitForm();
                  }}
                  disabled={loading}
                >
                    {
                        loading 
                        ? <Loading 
                            size={20}
                          />
                        : 'Войти'
                    }
                </Button>
            </FormSuface>
        </Wrapper>

    )
}