import API_URL from "../../../config/api";
import { useEffect, useState, type FormEvent } from "react";
import { useNavigate } from "react-router";
import type { ApiErrorResponse, LoginResponse } from "../../../types";
import styles from "./styles.module.css";
import { CgSpinner } from "react-icons/cg";

export default function Login() {
    const [email, setEmail] = useState<string>("");
    const [password, setPassword] = useState<string>("");
    const [error, setError] = useState<ApiErrorResponse | null>(null);
    const navigate = useNavigate();
    const token = localStorage.getItem("token");
    const [loading, setLoading] = useState(false);
    
    useEffect(() => {
        if (token) navigate("/dashboard");
    }, [token, navigate]);

    async function handleSignIn(event: FormEvent<HTMLFormElement>) {
        event.preventDefault();
        setLoading(true);
        setError(null);
    
        if (!email.includes('@')) {
          setError({ message: "Email inválido", data: null, errors: {} });
          return;
        }
    
        if (password.length < 6) {
          setError({ message: "Password deve ter pelo menos 6 caracteres", data: null, errors: {} });
          return;
        }
    
        try {
            const response = await fetch(`${API_URL}/api/login`, {
            method: "POST",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json"
            },
            body: JSON.stringify({
              email,
              password
            })
          });
          
          const data = (await response.json()) as LoginResponse;
    
          if (response.ok) {
            localStorage.setItem("token", data.access_token as string);
            navigate("/dashboard");
          } else {
            setError(data as ApiErrorResponse);
            setLoading(false);
          }
        } catch {
          setError({ message: "Erro de autenticação, tente novamente.", data: null, errors: {} });
          setLoading(false);
        }
    }
    return (
        <div >
          <div className={styles.loginContainer}>
          <img src="/src/assets/logo.png" alt="Logo" className={styles.loginLogo} />
            <span className="mb-4">Insira os seus dados para aceder à sua conta.</span>
            <form className={styles.loginForm} onSubmit={handleSignIn}>
    
              <div className={`${styles.loginFormItem} text-start`}>
                <label className={styles.loginFormLabel} htmlFor="email">Email</label>
                <input 
                  className={`p-2 border-0 ${styles.loginFormInput}`}
                  id="email"
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                />
              </div>
    
              <div className={`${styles.loginFormItem} text-start`}>
                <label className={styles.loginFormLabel} htmlFor="password">Password</label>
                <input 
                  className={`p-2 border-0 ${styles.loginFormInput}`}
                  id="password"
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  required
                  minLength={6}
                />
              </div>

              <p className="text-danger">
                {error && <p >{error.message}</p>}
                
              </p>

              <button type="submit" className={styles.btnLogin} disabled={loading}> {loading ? <CgSpinner className={`${styles.animateSpin} text-2xl fs-3`} /> : "Entrar"}</button>
            
            </form>
          </div>
        </div>
      );
}