import { User, UserRole, UserProfile } from '../types';
import { api, setAuthToken, removeAuthToken } from './api';

interface ApiResponse<T> {
  success: boolean;
  data: T;
  error?: string;
}

export const getUsers = async (): Promise<{ success: boolean; users?: User[]; error?: string }> => {
  try {
    const res = await api.get<ApiResponse<{ users: User[] }>>('/auth/users');
    if (res.success && res.data) {
      return { success: true, users: res.data.users };
    }
    return { success: false, error: res.error };
  } catch (e: any) {
    try {
      const err = JSON.parse(e.message);
      return { success: false, error: err.error || 'Failed to fetch users' };
    } catch {
      return { success: false, error: 'Failed to fetch users' };
    }
  }
};

export const login = async (email: string, password: string): Promise<{ success: boolean; user?: User; error?: string }> => {
  try {
    const res = await api.post<ApiResponse<{ user: User, token: string }>>('/auth/login', { email, password });
    if (res.success && res.data) {
      setAuthToken(res.data.token);
      return { success: true, user: res.data.user };
    }
    return { success: false, error: res.error };
  } catch (e: any) {
    try {
      const err = JSON.parse(e.message);
      return { success: false, error: err.error || 'Login failed' };
    } catch {
      return { success: false, error: 'Login failed' };
    }
  }
};

export const createUser = async (email: string, password: string): Promise<{ success: boolean; error?: string }> => {
  try {
    const res = await api.post<ApiResponse<{ user: User, token: string }>>('/auth/register', { email, password });
    if (res.success && res.data) {
      return { success: true };
    }
    return { success: false, error: res.error };
  } catch (e: any) {
    try {
      const err = JSON.parse(e.message);
      return { success: false, error: err.error || 'Registration failed' };
    } catch {
      return { success: false, error: 'Registration failed' };
    }
  }
};

export const deleteUser = async (userId: string) => {
  try {
    const res = await api.delete<ApiResponse<any>>(`/auth/users/${userId}`);
    return res;
  } catch (e: any) {
    try {
      const err = JSON.parse(e.message);
      return { success: false, error: err.error || 'Failed to delete user' };
    } catch {
      return { success: false, error: 'Failed to delete user' };
    }
  }
};

export const toggleBlockUser = async (userId: string, block: boolean) => {
  try {
    const res = await api.patch<ApiResponse<any>>(`/auth/users/${userId}/block`, { block });
    return res;
  } catch (e: any) {
    try {
      const err = JSON.parse(e.message);
      return { success: false, error: err.error || 'Failed to update user status' };
    } catch {
      return { success: false, error: 'Failed to update user status' };
    }
  }
};

export const adminResetPassword = async (userId: string, newPass: string) => {
  try {
    const res = await api.post<ApiResponse<any>>(`/auth/users/${userId}/reset-password`, { newPassword: newPass });
    return res;
  } catch (e: any) {
    try {
      const err = JSON.parse(e.message);
      return { success: false, error: err.error || 'Failed to reset password' };
    } catch {
      return { success: false, error: 'Failed to reset password' };
    }
  }
};

export const updateUserProfile = async (userId: string, profile: Partial<UserProfile>): Promise<{ success: boolean; error?: string }> => {
  try {
    const res = await api.patch<ApiResponse<any>>('/auth/profile', profile);
    return res;
  } catch (e: any) {
    try {
      const err = JSON.parse(e.message);
      return { success: false, error: err.error || 'Failed to update profile' };
    } catch {
      return { success: false, error: 'Failed to update profile' };
    }
  }
};

export const changePassword = async (userId: string, newPassword: string) => {
  try {
    const res = await api.post<ApiResponse<any>>('/auth/change-password', { userId, newPassword });
    if (!res.success) {
      console.error('Failed to change password:', res.error);
    }
    return res;
  } catch (e: any) {
    try {
      const err = JSON.parse(e.message);
      return { success: false, error: err.error || 'Network error' };
    } catch {
      return { success: false, error: 'Network error' };
    }
  }
};

export const getCurrentUserProfile = (userId: string): UserProfile | undefined => {
  // This was synchronous. Now it needs to be async or fetched on load.
  // For now, we return undefined and let the app fetch it.
  return undefined;
};

export const getMe = async (): Promise<{ success: boolean; user?: User; error?: string }> => {
  try {
    const res = await api.get<ApiResponse<{ user: User }>>('/auth/me');
    if (res.success && res.data) {
      return { success: true, user: res.data.user };
    }
    return { success: false, error: res.error };
  } catch (e: any) {
    return { success: false, error: 'Failed to fetch user' };
  }
};
export const initializeAccount = async (language: string, profile?: Partial<UserProfile>): Promise<{ success: boolean; user?: User; error?: string }> => {
  try {
    const res = await api.post<ApiResponse<{ user: User }>>('/auth/initialize', { language, ...profile });
    if (res.success && res.data) {
      return { success: true, user: res.data.user };
    }
    return { success: false, error: res.error };
  } catch (e: any) {
    try {
      const err = JSON.parse(e.message);
      return { success: false, error: err.error || 'Failed to initialize account' };
    } catch {
      return { success: false, error: 'Failed to initialize account' };
    }
  }
};
