import { useState, useEffect } from 'react';
import { User } from '../services/api';
import authService, { LoginRequest, RegisterRequest } from '../services/auth';

interface AuthState {
  user: User | null;
  isAuthenticated: boolean;
  isLoading: boolean;
}

export function useAuth() {
  const [authState, setAuthState] = useState<AuthState>({
    user: null,
    isAuthenticated: false,
    isLoading: true,
  });

  useEffect(() => {
    const initAuth = () => {
      const isAuthenticated = authService.isAuthenticated();
      const user = authService.getCurrentUser();
      
      setAuthState({
        user,
        isAuthenticated,
        isLoading: false,
      });
    };

    initAuth();
  }, []);

  const login = async (credentials: LoginRequest) => {
    try {
      const { user } = await authService.login(credentials);
      setAuthState({
        user,
        isAuthenticated: true,
        isLoading: false,
      });
      return { success: true };
    } catch (error: any) {
      return { 
        success: false, 
        error: error.message || 'Login failed' 
      };
    }
  };

  const register = async (userData: RegisterRequest) => {
    try {
      const { user } = await authService.register(userData);
      setAuthState({
        user,
        isAuthenticated: true,
        isLoading: false,
      });
      return { success: true };
    } catch (error: any) {
      return { 
        success: false, 
        error: error.message || 'Registration failed' 
      };
    }
  };

  const logout = async () => {
    try {
      await authService.logout();
      setAuthState({
        user: null,
        isAuthenticated: false,
        isLoading: false,
      });
      return { success: true };
    } catch (error: any) {
      return { 
        success: false, 
        error: error.message || 'Logout failed' 
      };
    }
  };

  const refreshUser = () => {
    const user = authService.getCurrentUser();
    setAuthState(prev => ({
      ...prev,
      user,
    }));
  };

  return {
    ...authState,
    login,
    register,
    logout,
    refreshUser,
  };
}