import API_URL from "../../../config/api";
import { useState, type FormEvent } from "react";
import { useNavigate } from "react-router";
import type { RegisterResponse } from "../../../types";

export default function Register() {

    const [name, setName] = useState<string>("");
    const [email, setEmail] = useState<string>("");
    const [password, setPassword] = useState<string>("");
    const [password_confirmation, setPasswordConfirmation] = useState<string>("");
    const [error, setError] = useState<string | undefined>("");
    const navigate = useNavigate();

    async function handleRegister(event: FormEvent<HTMLFormElement>) {
        event.preventDefault();
        setError("");
    
        if (name.length < 3) {
          setError("Nome deve ter pelo menos 3 caracteres");
          return;
        }

        if (!email.includes('@')) {
          setError("Email inválido");
          return;
        }

        if (password !== password_confirmation) {
          setError("As senhas não coincidem");
          return;
        }

        if (password.length < 6) {
          setError("Password deve ter pelo menos 6 caracteres");
          return;
        }
        
        try {
            const response = await fetch(`${API_URL}/api/register`, {
            method: "POST",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json"
            },
            body: JSON.stringify({
              email,
              password,
              password_confirmation
            })
          });
          
          const data = (await response.json()) as RegisterResponse;
          console.log(data);
    
          if (response.ok && typeof data.token === "string") {
            localStorage.setItem("token", data.token);
            navigate("/login");
          } else {
            setError((data as any).error);
          }
        } catch {
          setError("Erro ao registar, tente novamente.");
        }
    }

    return (
        <div >
          <div >
            <h2>Registar</h2>
            <form onSubmit={handleRegister}>
              {error && <p >{error}</p>}
    
              <div >
                <label htmlFor="name">Nome</label>
                <input
                  id="name"
                  type="text"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  required
                />
              </div>

              <div >
                <label htmlFor="email">Email</label>
                <input
                  id="email"
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                />
              </div>
    
              <div >
                <label htmlFor="password">Password</label>
                <input
                  id="password"
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  required
                  minLength={6}
                />
              </div>
              
              <div >
                <label htmlFor="password_confirmation">Confirme a Password</label>
                <input
                  id="password_confirmation"
                  type="password"
                  value={password_confirmation}
                  onChange={(e) => setPasswordConfirmation(e.target.value)}
                  required
                  minLength={6}
                />
              </div>
    
              <button type="submit">Registar</button>
            </form>
          </div>
        </div>
      );
}