import { useState } from "react";
import { Route, useHistory } from "react-router";
import Box from "@mui/material/Box";
import LoginHeader from "../components/LoginHeader";
import Typography from "@mui/material/Typography";
import { CircularProgress, TextField } from "@mui/material";
import Button from "@mui/material/Button";
import * as React from "react";
import { initGamerun } from "../helpers/gameruns";
import ErrorBox from "../components/errorBox";
import Grid from "@mui/material/Grid";

// Page used for entering username and initializing gamerun
export default function UsernamePage() {
  const [username, setUsername] = useState("");
  const [error, setError] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const history = useHistory();

  function handleChangeUsername(e) {
    setError(""); // clear error msg when username is changed
    setUsername(e.target.value);
  }

  function handleStart() {
    setError("");
    if (username.trim().length === 0) {
      // if username is blank set error
      setError("Username cannot be blank!");
      return;
    }

    //fix
    localStorage.setItem("username", username);
    setIsLoading(true);
    initGamerun(username)
      .then((e) => {
        history.push("/play");
        // setInitSuccessful(true)
      })
      .catch((err) => {
        setError("Couldn't initialize gamerun.");
      })
      .finally(() => setIsLoading(false));
  }
  // fix

  return (
    <div>
      <LoginHeader />
      {/* if username is blank, show box with error */}
      <ErrorBox severity="error" msg={error} />
      {/* Wrapper for centering username form */}

      <Box
        sx={{
          width: "100%",
          height: "100%",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
        }}
      >
        <Box
          sx={{
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
          }}
        >
          <Typography variant="h4">Enter your nickname</Typography>
          {/* Box with input TextField for username */}
          <Grid container mt={2}>
            <TextField
              id="username"
              label="Username"
              value={username}
              onChange={handleChangeUsername}
              sx={{ mr: 3 }}
            />
            <Button
              disabled={isLoading}
              variant="contained"
              size="large"
              onClick={handleStart}
            >
              {isLoading ? <CircularProgress size={30} /> : "Start"}
            </Button>
          </Grid>
        </Box>
      </Box>
      {/*{initSuccessful && <Redirect to="/play" />}*/}
    </div>
  );
}
