import { useCallback, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '@/stores/authStore';
import { authAPI, profileAPI } from '@/api/client';

export function useAuth() {
  const { token, user, isAuthenticated, isLoading, login, logout, setLoading, updateUser } =
    useAuthStore();
  const navigate = useNavigate();

  useEffect(() => {
    if (token && !user) {
      profileAPI
        .me()
        .then(({ data }) => {
          useAuthStore.getState().setUser(data.user ?? data);
          setLoading(false);
        })
        .catch(() => {
          logout();
        });
    } else {
      setLoading(false);
    }
  }, [token, user, logout, setLoading]);

  const handleLogin = useCallback(
    async (email: string, password: string) => {
      const { data } = await authAPI.login({ email, password });
      login(data.access_token ?? data.token, data.refresh_token ?? null, data.user);
      navigate('/dashboard');
    },
    [login, navigate]
  );

  const handleRegister = useCallback(
    async (username: string, email: string, password: string) => {
      const { data } = await authAPI.register({ username, email, password });
      login(data.access_token ?? data.token, data.refresh_token ?? null, data.user);
      navigate('/dashboard');
    },
    [login, navigate]
  );

  const handleLogout = useCallback(() => {
    const refreshToken = useAuthStore.getState().refreshToken;
    logout();
    navigate('/');
    if (refreshToken) {
      authAPI.logout(refreshToken).catch(() => {});
    }
  }, [logout, navigate]);

  return {
    user,
    token,
    isAuthenticated,
    isLoading,
    login: handleLogin,
    register: handleRegister,
    logout: handleLogout,
    updateUser,
  };
}
