import { useEffect, useState } from "react";
import Box from "@mui/material/Box";
import Paper from "@mui/material/Paper";
import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography";
import { IconButton, TextField } from "@mui/material";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import { useHistory } from "react-router";
import PropTypes from "prop-types";
import { Redirect } from "react-router-dom";
import { connect } from "react-redux";
import { login } from "../store/auth/actions";
import ErrorBox from "../components/ErrorBox";

// Login page for logging into admin section (settings)
function LoginPage(props) {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("")
  const history = useHistory();

  // if error fails, show error box with error message
  useEffect(() => {
    if(props.loginError)
      setError("Incorrect credentials.")
  }, [props.loginError]);


  // handler for login
  function handleLogin() {
    setError("")
    // call login from props, if login was successful, user is redirected to settings Page
    props.login(username, password);
  }

  // go back to main Page
  function handleBack() {
    history.push("/");
  }

  return (
    <div>
      {
        // if user is not logged in, show login form, otherwise redirect to settings page
        !props.isAuthenticated ? (
          <Box sx={{ width: "100%", height: "100%" }}>
            <ErrorBox severity="error" error={error} setError={setError} />
            {/* if username or password was wrong, show ErrorBox */}

            <Box
              sx={{
                height: "100%",
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
              }}
            >
              <Paper
                variant="outlined"
                sx={{
                  width: "600px",
                  p: { xs: 2, sm: 3 },
                }}
              >
                <Box
                  sx={{ display: "flex", alignItems: "center" }}
                  position="absolute"
                >
                  <IconButton color="primary" onClick={handleBack}>
                    <ArrowBackIcon />
                  </IconButton>
                </Box>

                <Typography variant="h4" align="center">
                  Admin section
                </Typography>

                {/* Box with textfield for username */}
                <Box
                  sx={{
                    display: "flex",
                    justifyContent: "center",
                    mt: 5,
                    mb: 3,
                    px: { xs: "10%", sm: "20%" },
                  }}
                >
                  <TextField
                    id="username"
                    label="Username"
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                    fullWidth
                  />
                </Box>
                {/* Box with textfield for password */}
                <Box
                  sx={{
                    display: "flex",
                    justifyContent: "center",
                    mb: 4,
                    px: { xs: "10%", sm: "20%" },
                  }}
                >
                  <TextField
                    id="password"
                    type="password"
                    label="Password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    fullWidth
                  />
                </Box>
                {/* Box with Login button */}
                <Box sx={{ display: "flex", justifyContent: "center" }}>
                  <Button
                    color="primary"
                    variant="contained"
                    size="large"
                    onClick={handleLogin}
                  >
                    Login
                  </Button>
                </Box>
              </Paper>
            </Box>
          </Box>
        ) : (
          <Redirect to="/settings" />
        )
      }
    </div>
  );
}

LoginPage.propTypes = {
  login: PropTypes.func.isRequired,
  isAuthenticated: PropTypes.bool,
  loginError: PropTypes.bool,
};

const mapStateToProps = (state) => ({
  isAuthenticated: state.auth.isAuthenticated,
  loginError: state.auth.loginError,
});

export default connect(mapStateToProps, { login })(LoginPage);
