import { useContext, useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { loginRequest, registerRequest } from "../api/auth";
import { checkIfUserExists } from "../api/users";
import ErrorMessage from "../components/common/ErrorMessage";
import FormInput from "../components/common/FormInput";
import { AuthContext } from "../context/AuthContext";
import useActionToast from "../hooks/useActionToast";
import getApiErrorMessage from "../lib/getApiErrorMessage";
import "../styles/pages/Register.css";

export default function Register() {
  const navigate = useNavigate();
  const { login } = useContext(AuthContext);
  const toast = useActionToast();

  const [name, setName] = useState("");
  const [username, setUsername] = useState("");
  const [userExists, setUserExists] = useState(false);
  const [password, setPassword] = useState("");
  const [passwordMatches, setPasswordMatches] = useState(true);
  const [confirm, setConfirm] = useState("");
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");

  useEffect(() => {
    checkIfUserExistsHandler();
  }, [username]);

  async function checkIfUserExistsHandler() {
    setUserExists((await checkIfUserExists(username)).data);
  }

  useEffect(() => {
    setError(userExists ? `Username '${username}' already taken` : "");
  }, [userExists]);

  useEffect(() => {
    setPasswordMatches(!password || !confirm || password === confirm);
  }, [password, confirm]);

  useEffect(() => {
    setError(passwordMatches ? "" : "Passwords are not matching");
  }, [passwordMatches]);

  const submit = async (e) => {
    e.preventDefault();
    setError("");
    setSuccess("");

    try {
      await registerRequest(username, password, name);
      toast.success("Registered account", `Created account for ${username}`);
      const data = await loginRequest(username, password);
      login(data);
      toast.success("Logged in", `Welcome ${data?.username || username}`);
      setSuccess("Account created! Redirecting to the grocery list...");
      setTimeout(() => navigate("/"), 2000);
    } catch (err) {
      const message = getApiErrorMessage(err, "Registration failed");
      setError(message);
      toast.error("Registration failed", `Registration failed: ${message}`);
      setTimeout(() => setError(""), 1000);
    }
  };

  return (
    <div className="register-container">
      <h1 className="text-center mb-4 text-2xl font-bold">Register</h1>

      <ErrorMessage message={error} />
      <ErrorMessage message={success} type="success" />

      <form className="register-form" onSubmit={submit}>
        <FormInput
          type="text"
          className="form-input"
          placeholder="Name"
          onChange={(e) => setName(e.target.value)}
          required
        />

        <FormInput
          type="text"
          className="form-input"
          placeholder="Username"
          onKeyUp={(e) => setUsername(e.target.value)}
          required
        />

        <FormInput
          type="password"
          className="form-input"
          placeholder="Password"
          onChange={(e) => setPassword(e.target.value)}
          required
        />

        <FormInput
          type="password"
          className="form-input"
          placeholder="Confirm Password"
          onChange={(e) => setConfirm(e.target.value)}
          required
        />

        <button disabled={error !== ""} type="submit" className="btn btn-primary btn-block mt-2">
          Create Account
        </button>
      </form>

      <p className="text-center mt-3">
        Already have an account? <Link to="/login" className="text-primary font-semibold">Login here</Link>
      </p>
    </div>
  );
}
