"use client";

import { useState, FormEvent } from "react";
import { z } from "zod";
import { useAuth } from "./useAuth";

const loginSchema = z.object({
  username: z.email("E-mail inválido."),
  password: z.string().min(6, "A senha deve ter pelo menos 6 caracteres."),
});

export function useLoginForm() {
  const { signIn, isLoading } = useAuth();
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);

  async function handleSubmit(event: FormEvent) {
    event.preventDefault();
    setError("");

    const validation = loginSchema.safeParse({ username, password });
    if (!validation.success) {
      setError(validation.error.issues[0].message);
      return;
    }

    setIsSubmitting(true);

    try {
      await signIn({ username, password });
    } catch (err: unknown) {
      if (err && typeof err === "object" && "response" in err) {
        const axiosError = err as {
          response?: { status?: number };
        };
        if (axiosError.response?.status === 403) {
          setError(
            "Acesso negado. Apenas usuários ADMIN ou EMBRAPA podem acessar o sistema.",
          );
        } else {
          setError("E-mail ou senha inválidos. Verifique seus dados e tente novamente.");
        }
      } else {
        setError("Erro ao fazer login. Tente novamente.");
      }
    } finally {
      setIsSubmitting(false);
    }
  }

  const isLoadingState = isSubmitting || isLoading;

  return {
    username,
    setUsername,
    password,
    setPassword,
    error,
    isLoading: isLoadingState,
    handleSubmit,
  };
}
