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 "./login.css"


const Login = () => {
  const { setToken } = useAuth();
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const navigate = useNavigate();
  const location = useLocation();

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

  const from = location.state?.from?.pathname || "/";

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

    if (!username || !password) {
      if (!username) setUsernameEmpty(true);
      if (!password) setPasswordEmpty(true);
      return;
    }

    // TODO: request to API
    if ((username === "admin" && password === "1234") || (username === "a" && password === "a")) {
      const token = "todo.jwt.token";
      setToken(token);
      navigate(from, { replace: true });
    } else {
      toast.error("Wrong login or password");
    }
  };

  return (
    <div className="login-right-div">
      <h2
        style={{
          display: "flex"
        }}
      >
        Login
      </h2>
      <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 your username"
          className="test1"
          />
        <FormField
          type="password"
          placeholder="Password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          required
          showError={passwordEmpty}
          errorMessage="Please enter your password"
          className="test2"
          />
        <button type="submit"
          style={{
            display: "flex",
            marginTop: "10px"
          }}
        >
          Login
        </button>
      </form>
    </div>
  );
};

export default Login;
