import { useMutation } from "@tanstack/react-query";
import { useLocation, useNavigate } from "react-router";
import { authApi, LoginPayload, RegisterPayload } from "../lib/api/auth";
import { useAuthStore } from "../stores/authStore";

export function useAuth() {
  const navigate = useNavigate();
  const location = useLocation();
  const setAuth = useAuthStore((state) => state.setAuth);
  const clearAuth = useAuthStore((state) => state.clearAuth);
  const isAuthenticated = useAuthStore((state) => state.isAuthenticated);
  const user = useAuthStore((state) => state.user);

  const getRedirectTarget = () => {
    const queryRedirect = new URLSearchParams(location.search).get("redirect");
    const stateRedirect = (location.state as { from?: { pathname?: string } } | null)?.from?.pathname;
    return queryRedirect || stateRedirect || "/";
  };

  const loginMutation = useMutation({
    mutationFn: (payload: LoginPayload) => authApi.login(payload),
    onSuccess: (data) => {
      setAuth(data.token, {
        id: String(data.user.id),
        username: data.user.username,
        email: data.user.email,
        role: data.user.role,
        tenantId: String(data.user.tenantId),
      });
      navigate(getRedirectTarget(), { replace: true });
    },
  });

  const registerMutation = useMutation({
    mutationFn: (payload: RegisterPayload) => authApi.register(payload),
    onSuccess: (data) => {
      setAuth(data.token, {
        id: String(data.user.id),
        username: data.user.username,
        email: data.user.email,
        role: data.user.role,
        tenantId: String(data.user.tenantId),
      });
      navigate(getRedirectTarget(), { replace: true });
    },
  });

  const logoutMutation = useMutation({
    mutationFn: () => authApi.logout(),
    onSettled: () => {
      clearAuth();
      navigate("/login");
    },
  });

  return {
    isAuthenticated,
    user,
    login: loginMutation.mutate,
    loginAsync: loginMutation.mutateAsync,
    register: registerMutation.mutate,
    registerAsync: registerMutation.mutateAsync,
    logout: logoutMutation.mutate,
    loginPending: loginMutation.isPending,
    registerPending: registerMutation.isPending,
    loginError: loginMutation.error,
    registerError: registerMutation.error,
  };
}
