import { useNavigate } from "react-router-dom";
import { enqueueSnackbar } from "notistack";
import { useTheme } from "@mui/material/styles";
import { Formik, Field, Form, FormikHelpers } from "formik";
import { Link } from "react-router-dom";
import { Box, Checkbox, Typography, FormControlLabel, Button } from "@mui/material";
import Logo from "@pages/Logo";
import OutlinedInput from "@kitUI/outlinedInput";
import EmailOutlinedIcon from "@mui/icons-material/EmailOutlined";
import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
import { authStore } from "@root/stores/auth";

interface Values {
  email: string;
  password: string;
}

function validate(values: Values) {
  const errors = {} as any;

  if (!values.email) {
    errors.email = "Required";
  }

  if (!values.password) {
    errors.password = "Required";
  }

  if (values.password && !/^[\S]{8,25}$/i.test(values.password)) {
    errors.password = "Invalid password";
  }

  return errors;
}

const SigninForm = () => {
  const theme = useTheme();
  const navigate = useNavigate();

  const { makeRequest } = authStore();

  const initialValues: Values = {
    email: "",
    password: "",
  };

  const onSignFormSubmit = (values: Values, formikHelpers: FormikHelpers<Values>) => {
    formikHelpers.setSubmitting(true);
    makeRequest({
      url: "https://admin.pena.digital/auth/login",
      body: {
        login: values.email,
        password: values.password,
      },
      useToken: false,
    })
      .then((e) => {
        navigate("/users");
      })
      .catch((e) => {
        console.log(e);
        enqueueSnackbar(e.message ? e.message : `Unknown error`);
      })
      .finally(() => {
        formikHelpers.setSubmitting(false);
      });
  };

  return (
    <Formik initialValues={initialValues} validate={validate} onSubmit={onSignFormSubmit}>
      {(props) => (
        <Form>
          <Box
            component="section"
            sx={{
              minHeight: "100vh",
              height: "100%",
              width: "100%",
              backgroundColor: theme.palette.content.main,
              display: "flex",
              justifyContent: "center",
              alignItems: "center",
              padding: "15px 0",
            }}
          >
            <Box
              component="article"
              sx={{
                width: "350px",
                backgroundColor: theme.palette.content.main,
                display: "flex",
                flexDirection: "column",
                justifyContent: "center",
                "> *": {
                  marginTop: "15px",
                },
              }}
            >
              <Logo />
              <Box>
                <Typography variant="h5" color={theme.palette.secondary.main}>
                  Добро пожаловать
                </Typography>
                <Typography variant="h6" color={theme.palette.secondary.main}>
                  Мы рады что вы выбрали нас!
                </Typography>
              </Box>
              <Box sx={{ display: "flex", alignItems: "center", marginTop: "15px", "> *": { marginRight: "10px" } }}>
                <EmailOutlinedIcon htmlColor={theme.palette.golden.main} />
                <Field as={OutlinedInput} name="email" variant="filled" label="Эл. почта" />
              </Box>
              <Box sx={{ display: "flex", alignItems: "center", marginTop: "15px", "> *": { marginRight: "10px" } }}>
                <LockOutlinedIcon htmlColor={theme.palette.golden.main} />
                <Field as={OutlinedInput} type="password" name="password" variant="filled" label="Пароль" />
              </Box>
              <Box
                component="article"
                sx={{
                  display: "flex",
                  alignItems: "center",
                }}
              >
                <FormControlLabel
                  sx={{ color: "white" }}
                  control={
                    <Checkbox
                      value="checkedA"
                      inputProps={{ "aria-label": "Checkbox A" }}
                      sx={{
                        color: "white",
                        transform: "scale(1.5)",
                        "&.Mui-checked": {
                          color: "white",
                        },
                        "&.MuiFormControlLabel-root": {
                          color: "white",
                        },
                      }}
                    />
                  }
                  label="Запомнить этот компьютер"
                />
              </Box>
              <Link to="/restore" style={{ textDecoration: "none" }}>
                <Typography color={theme.palette.golden.main}>Забыли пароль?</Typography>
              </Link>
              <Button
                type="submit"
                disabled={props.isSubmitting}
                sx={{
                  width: "250px",
                  margin: "15px auto",
                  padding: "20px 30px",
                  fontSize: 18,
                }}
              >
                Войти
              </Button>
              <Box
                sx={{
                  display: "flex",
                }}
              >
                <Typography color={theme.palette.secondary.main}>У вас нет аккаунта?&nbsp;</Typography>
                <Link to="/signup" style={{ textDecoration: "none" }}>
                  <Typography color={theme.palette.golden.main}>Зарегестрируйтесь</Typography>
                </Link>
              </Box>
            </Box>
          </Box>
        </Form>
      )}
    </Formik>
  );
};

export default SigninForm;
