import { apiClient } from './api'
import type { User } from '@/types/auth'

export interface UserApproval {
  is_approved: boolean
}

export interface UserRoleUpdate {
  role: 'director' | 'coordinator' | 'artist' | 'developer'
}

export interface UserUpdate {
  first_name?: string
  last_name?: string
  role?: 'director' | 'coordinator' | 'artist' | 'developer'
  is_admin?: boolean
  is_approved?: boolean
}

// Helper function to ensure proper boolean conversion
const normalizeUser = (user: any): User => ({
  ...user,
  is_admin: Boolean(user.is_admin),
  is_approved: Boolean(user.is_approved)
})

export const userService = {
  async getUsers(): Promise<User[]> {
    const response = await apiClient.get('/users/')
    return response.data.map(normalizeUser)
  },

  async getAllUsers(): Promise<User[]> {
    const response = await apiClient.get('/users/')
    return response.data.map(normalizeUser)
  },

  async getPendingUsers(): Promise<User[]> {
    const response = await apiClient.get('/users/pending')
    return response.data.map(normalizeUser)
  },

  async approveUser(userId: number, approval: UserApproval): Promise<{ message: string; user_id: number; is_approved: boolean }> {
    const response = await apiClient.post(`/users/${userId}/approve`, approval)
    return response.data
  },

  async updateUserRole(userId: number, roleUpdate: UserRoleUpdate): Promise<{ message: string; user_id: number; role: string }> {
    const response = await apiClient.put(`/users/${userId}/role`, roleUpdate)
    return response.data
  },

  async getUser(userId: number): Promise<User> {
    const response = await apiClient.get(`/users/${userId}`)
    return normalizeUser(response.data)
  },

  async updateCurrentUser(userUpdate: UserUpdate): Promise<User> {
    const response = await apiClient.put('/users/me', userUpdate)
    return normalizeUser(response.data)
  },

  async updateUserAdminPermission(userId: number, isAdmin: boolean): Promise<{ message: string; user_id: number; is_admin: boolean }> {
    const response = await apiClient.put(`/users/${userId}/admin`, { is_admin: isAdmin })
    return response.data
  },

  async createUser(userData: {
    email: string
    password: string
    first_name: string
    last_name: string
    role: 'artist' | 'coordinator' | 'director' | 'developer'
    is_approved: boolean
    is_admin: boolean
  }): Promise<User> {
    const response = await apiClient.post('/users/admin/create', userData)
    return normalizeUser(response.data)
  },

  async editUser(userId: number, userData: {
    first_name?: string
    last_name?: string
    email?: string
    role?: 'artist' | 'coordinator' | 'director' | 'developer'
    is_approved?: boolean
    is_admin?: boolean
  }): Promise<User> {
    console.log('userService.editUser called with:', { userId, userData })
    try {
      const response = await apiClient.put(`/users/${userId}`, userData)
      return normalizeUser(response.data)
    } catch (error: any) {
      console.error('editUser API error:', error.response?.data)
      if (error.response?.data?.detail && Array.isArray(error.response.data.detail)) {
        console.error('Validation errors:', JSON.stringify(error.response.data.detail, null, 2))
      }
      throw error
    }
  },

  async resetUserPassword(userId: number, newPassword: string): Promise<{ message: string; user_id: number }> {
    const response = await apiClient.put(`/users/${userId}/password`, { new_password: newPassword })
    return response.data
  },

  async checkCanDeleteUser(userId: number): Promise<{
    can_delete: boolean;
    reason: string | null;
    project_memberships: number;
    task_assignments: number;
  }> {
    const response = await apiClient.get(`/users/${userId}/can-delete`)
    return response.data
  },

  async deleteUser(userId: number): Promise<{ message: string; user_id: number }> {
    const response = await apiClient.delete(`/users/${userId}`)
    return response.data
  },

  async uploadAvatar(file: File): Promise<User> {
    const formData = new FormData()
    formData.append('file', file)
    
    const response = await apiClient.post('/users/me/avatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    return normalizeUser(response.data)
  },

  async removeAvatar(): Promise<User> {
    const response = await apiClient.delete('/users/me/avatar')
    return normalizeUser(response.data)
  },

  async changePassword(passwordData: {
    current_password: string
    new_password: string
  }): Promise<{ message: string; user_id: number }> {
    const response = await apiClient.put('/users/me/password', passwordData)
    return response.data
  }
}