import { useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";

import { toast } from "react-toastify"

import useAuth from "../../auth/auth";

import FormField from "../../components/FormField"
import "./register.css"


const Register = () => {
  const { setToken } = useAuth();
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

  const navigate = useNavigate();
  const location = useLocation();
  const searchPath = new URLSearchParams(location.search);
  const redirectPath = searchPath.get("to") || "/";

  const [usernameEmpty, setUsernameEmpty] = useState(false);
  const [passwordEmpty, setPasswordEmpty] = useState(false);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    setUsernameEmpty(!username);
    setPasswordEmpty(!password);

    if (!username || !password) {
      return;
    }

    // TODO: request to API - register
    if (username === "user" && password === "user") {
      const token = "newusertodo.jwt.token";
      setToken(token);
      navigate(redirectPath, { replace: true });
    } else {
      toast.error("Wrong login or password");
    }
  };

  return (
    <div className="register">
      <img className="register-background" src="register-background.jpg"></img>
      <div className="register-block">
        <form onSubmit={handleSubmit}
          style={{
            flexDirection: "column",
            display: "flex",
            gap: "10px",
            alignItems: "center",
          }}
          noValidate
        >
          <FormField
            type="text"
            placeholder="Username"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            required
            showError={usernameEmpty}
            errorMessage="Please enter the username you want"
          />
          <FormField
            type="password"
            placeholder="Password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
            showError={passwordEmpty}
            errorMessage="Please enter the password you want"
          />
          <button type="submit" className="register-button">
            Create account
          </button>
          <h4>
            <a href={`/login?to=${redirectPath}`} className="register-link">Back to login</a>
          </h4>
        </form>
      </div>
    </div>
  )
}

export default Register;
