import { useAuthStore } from '@/store/useAuthStore';
import { api, apiEndpoints } from '@/lib/api';
import type { LoginData, RegisterData, AuthResponse, User } from '@/types';
import { useRouter } from 'next/navigation';
import { useCallback } from 'react';

export function useAuth() {
  const router = useRouter();
  const {
    user,
    token,
    isAuthenticated,
    isLoading,
    error,
    setUser,
    login: loginStore,
    logout: logoutStore,
    setLoading,
    setError,
    clearError,
  } = useAuthStore();

  /**
   * Register a new user
   */
  const register = useCallback(
    async (data: RegisterData): Promise<void> => {
      setLoading(true);
      setError(null);
      try {
        const response = await api.post<AuthResponse>(
          apiEndpoints.auth.register,
          data
        );
        loginStore(response.user, response.token);

        // Store token in localStorage
        if (typeof window !== 'undefined') {
          localStorage.setItem('auth_token', response.token);
        }

        router.push('/dashboard');
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Error al registrar');
        throw err;
      } finally {
        setLoading(false);
      }
    },
    [setLoading, setError, loginStore, router]
  );

  /**
   * Login user
   */
  const login = useCallback(
    async (data: LoginData): Promise<void> => {
      setLoading(true);
      setError(null);
      try {
        const response = await api.post<AuthResponse>(
          apiEndpoints.auth.login,
          data
        );
        loginStore(response.user, response.token);

        // Store token in localStorage
        if (typeof window !== 'undefined') {
          localStorage.setItem('auth_token', response.token);
        }

        router.push('/dashboard');
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Error al iniciar sesión');
        throw err;
      } finally {
        setLoading(false);
      }
    },
    [setLoading, setError, loginStore, router]
  );

  /**
   * Logout user
   */
  const logout = useCallback(async (): Promise<void> => {
    setLoading(true);
    try {
      // Call logout endpoint
      await api.post(apiEndpoints.auth.logout);
    } catch (err) {
      console.error('Logout error:', err);
    } finally {
      logoutStore();

      // Clear token from localStorage
      if (typeof window !== 'undefined') {
        localStorage.removeItem('auth_token');
      }

      setLoading(false);
      router.push('/');
    }
  }, [setLoading, logoutStore, router]);

  /**
   * Fetch current user
   */
  const fetchMe = useCallback(async (): Promise<void> => {
    if (!token) return;

    setLoading(true);
    setError(null);
    try {
      const user = await api.get<User>(apiEndpoints.auth.me);
      setUser(user);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error al obtener usuario');
      // If unauthorized, logout
      if (err instanceof Error && err.message.includes('401')) {
        void logout();
      }
    } finally {
      setLoading(false);
    }
  }, [token, setLoading, setError, setUser, logout]);

  return {
    // State
    user,
    token,
    isAuthenticated,
    isLoading,
    error,

    // Actions
    register,
    login,
    logout,
    fetchMe,
    clearError,
  };
}
