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 "../styles/pages/Register.css";

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

  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);
      const data = await loginRequest(username, password);
      login(data);
      setSuccess("Account created! Redirecting to the grocery list...");
      setTimeout(() => navigate("/"), 2000);
    } catch (err) {
      setError(err.response?.data?.message || "Registration failed");
      setTimeout(() => setError(""), 1000);
    }
  };

  return (
    <div className="register-container">
      <h1>Register</h1>

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

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

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

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

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

        <button disabled={error !== ""} type="submit">
          Create Account
        </button>
      </form>

      <p className="register-link">
        Already have an account? <Link to="/login">Login here</Link>
      </p>
    </div>
  );
}