package com.crm.chat.data.repository

import android.content.ContentResolver
import android.net.Uri
import android.util.Log
import com.crm.chat.data.api.ApiClient
import com.crm.chat.data.model.UpdateUserRequest
import com.crm.chat.data.model.UpdateUserProfileRequest
import com.crm.chat.data.model.User
import com.crm.chat.data.model.UserProfile
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File

class UserRepository(private val apiClient: ApiClient) {

    suspend fun getUserById(userId: Long): Result<User> {
        return withContext(Dispatchers.IO) {
            try {
                val response = apiClient.userApiService.getUserById(userId)

                if (response.isSuccessful) {
                    val user = response.body()
                    if (user != null) {
                        Result.success(user)
                    } else {
                        Result.failure(Exception("Empty response"))
                    }
                } else {
                    Result.failure(Exception("Error: ${response.code()}"))
                }
            } catch (e: Exception) {
                Log.e("UserRepository", "Error getting user by id", e)
                Result.failure(e)
            }
        }
    }

    suspend fun updateUser(userId: Long, request: UpdateUserRequest): Result<User> {
        return withContext(Dispatchers.IO) {
            try {
                val response = apiClient.userApiService.updateUser(userId, request)

                if (response.isSuccessful) {
                    val user = response.body()
                    if (user != null) {
                        Result.success(user)
                    } else {
                        Result.failure(Exception("Empty response"))
                    }
                } else {
                    Result.failure(Exception("Error: ${response.code()}"))
                }
            } catch (e: Exception) {
                Log.e("UserRepository", "Error updating user", e)
                Result.failure(e)
            }
        }
    }

    suspend fun uploadUserAvatar(userId: Long, imageUri: Uri, contentResolver: ContentResolver): Result<User> {
        return withContext(Dispatchers.IO) {
            try {
                // Get file from URI
                val inputStream = contentResolver.openInputStream(imageUri)
                    ?: return@withContext Result.failure(Exception("Cannot open image file"))

                val tempFile = File.createTempFile("avatar", ".jpg").apply {
                    deleteOnExit()
                    outputStream().use { output ->
                        inputStream.copyTo(output)
                    }
                }

                val requestBody = tempFile.asRequestBody("image/*".toMediaTypeOrNull())
                val multipartBody = MultipartBody.Part.createFormData("file", tempFile.name, requestBody)

                val response = apiClient.userApiService.uploadUserAvatar(userId, multipartBody)

                // Clean up temp file
                tempFile.delete()

                if (response.isSuccessful) {
                    val user = response.body()
                    if (user != null) {
                        Result.success(user)
                    } else {
                        Result.failure(Exception("Empty response"))
                    }
                } else {
                    Result.failure(Exception("Error: ${response.code()}"))
                }
            } catch (e: Exception) {
                Log.e("UserRepository", "Error uploading avatar", e)
                Result.failure(e)
            }
        }
    }

    suspend fun removeUserAvatar(userId: Long): Result<User> {
        return withContext(Dispatchers.IO) {
            try {
                val response = apiClient.userApiService.removeUserAvatar(userId)

                if (response.isSuccessful) {
                    val user = response.body()
                    if (user != null) {
                        Result.success(user)
                    } else {
                        Result.failure(Exception("Empty response"))
                    }
                } else {
                    Result.failure(Exception("Error: ${response.code()}"))
                }
            } catch (e: Exception) {
                Log.e("UserRepository", "Error removing avatar", e)
                Result.failure(e)
            }
        }
    }

    suspend fun getUserProfile(userId: Long): Result<UserProfile> {
        return withContext(Dispatchers.IO) {
            try {
                val response = apiClient.userProfileApiService.getUserProfile(userId)

                if (response.isSuccessful) {
                    val userProfile = response.body()
                    if (userProfile != null) {
                        Result.success(userProfile)
                    } else {
                        Result.failure(Exception("Empty response"))
                    }
                } else {
                    Result.failure(Exception("Error: ${response.code()}"))
                }
            } catch (e: Exception) {
                Log.e("UserRepository", "Error getting user profile", e)
                Result.failure(e)
            }
        }
    }

    suspend fun updateUserProfile(userId: Long, request: UpdateUserProfileRequest): Result<Unit> {
        return withContext(Dispatchers.IO) {
            try {
                val response = apiClient.userProfileApiService.updateUserProfile(userId, request)

                if (response.isSuccessful) {
                    Result.success(Unit)
                } else {
                    Result.failure(Exception("Error: ${response.code()}"))
                }
            } catch (e: Exception) {
                Log.e("UserRepository", "Error updating user profile", e)
                Result.failure(e)
            }
        }
    }
}
