package com.safecheckin.app.data.cloud

import com.safecheckin.app.data.api.ApiClient
import com.safecheckin.app.data.api.SafeCheckInApi
import com.safecheckin.app.data.model.Contact
import com.safecheckin.app.data.model.CheckInRecord
import kotlinx.coroutines.flow.first
import retrofit2.HttpException
import java.text.SimpleDateFormat
import java.util.*

class CloudDataSource(private val apiClient: ApiClient) {
    
    private suspend fun getApi(): SafeCheckInApi {
        return apiClient.createApi()
    }
    
    private suspend fun getUserId(): Int {
        return apiClient.userId.first()
    }
    
    // ========== 打卡相关 ==========
    
    suspend fun getCheckIns(): List<CheckInRecord> {
        try {
            val userId = getUserId()
            val api = getApi()
            val response = api.getCheckIns(userId)
            
            if (response.isSuccessful) {
                val checkInsResponse = response.body()
                return checkInsResponse?.checkIns?.map { dto ->
                    CheckInRecord(
                        id = dto.id.toLong(),
                        timestamp = parseDateToLong(dto.timestamp),
                        note = dto.note ?: ""
                    )
                } ?: emptyList()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return emptyList()
    }
    
    suspend fun addCheckIn(note: String = ""): Boolean {
        try {
            val userId = getUserId()
            val api = getApi()
            val request = com.safecheckin.app.data.api.CheckInRequest(
                userId = userId,
                note = note
            )
            val response = api.checkIn(request)
            return response.isSuccessful
        } catch (e: Exception) {
            e.printStackTrace()
            return false
        }
    }
    
    suspend fun getCheckInCount(): Int {
        try {
            val userId = getUserId()
            val api = getApi()
            val response = api.getCheckInCount(userId)
            
            if (response.isSuccessful) {
                return response.body()?.checkInCount ?: 0
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0
    }
    
    // ========== 联系人相关 ==========
    
    suspend fun getContacts(): List<Contact> {
        try {
            val userId = getUserId()
            val api = getApi()
            val response = api.getContacts(userId)
            
            if (response.isSuccessful) {
                val contactsResponse = response.body()
                return contactsResponse?.contacts?.map { dto ->
                    Contact(
                        id = dto.id.toLong(),
                        name = dto.name,
                        email = dto.email,
                        phone = dto.phone ?: ""
                    )
                } ?: emptyList()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return emptyList()
    }
    
    suspend fun addContact(contact: Contact): Boolean {
        try {
            val userId = getUserId()
            val api = getApi()
            val request = com.safecheckin.app.data.api.ContactCreateRequest(
                userId = userId,
                name = contact.name,
                email = contact.email,
                phone = contact.phone
            )
            val response = api.createContact(request)
            return response.isSuccessful
        } catch (e: Exception) {
            e.printStackTrace()
            return false
        }
    }
    
    suspend fun deleteContact(contactId: Int): Boolean {
        try {
            val api = getApi()
            val response = api.deleteContact(contactId)
            return response.isSuccessful
        } catch (e: Exception) {
            e.printStackTrace()
            return false
        }
    }
    
    // ========== 设置相关 ==========
    
    suspend fun getGracePeriod(): Pair<Int, Int> {
        try {
            val userId = getUserId()
            val api = getApi()
            val response = api.getGracePeriod(userId)
            
            if (response.isSuccessful) {
                val gracePeriod = response.body()
                return Pair(gracePeriod?.hours ?: 24, gracePeriod?.minutes ?: 0)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return Pair(24, 0)
    }
    
    suspend fun setGracePeriod(hours: Int, minutes: Int): Boolean {
        try {
            val userId = getUserId()
            val api = getApi()
            val request = com.safecheckin.app.data.api.GracePeriodRequest(
                userId = userId,
                hours = hours,
                minutes = minutes
            )
            val response = api.updateGracePeriod(request)
            return response.isSuccessful
        } catch (e: Exception) {
            e.printStackTrace()
            return false
        }
    }
    
    // ========== 用户统计 ==========
    
    suspend fun getUserStats(): Map<String, Any> {
        try {
            val userId = getUserId()
            val api = getApi()
            val response = api.getUserStats(userId)
            
            if (response.isSuccessful) {
                val stats = response.body()
                return mapOf(
                    "check_in_count" to (stats?.checkInCount ?: 0),
                    "consecutive_days" to (stats?.consecutiveDays ?: 0),
                    "last_check_in" to (stats?.lastCheckIn ?: ""),
                    "grace_period_hours" to (stats?.gracePeriodHours ?: 24),
                    "grace_period_minutes" to (stats?.gracePeriodMinutes ?: 0),
                    "preset_message" to (stats?.presetMessage ?: "如果你收到这条消息，说明我可能出事了，请尽快联系我或报警。"),
                    "daily_reminder" to (stats?.dailyReminder ?: true)
                )
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return mapOf(
            "check_in_count" to 0,
            "consecutive_days" to 0,
            "last_check_in" to "",
            "grace_period_hours" to 24,
            "grace_period_minutes" to 0,
            "preset_message" to "如果你收到这条消息，说明我可能出事了，请尽快联系我或报警。",
            "daily_reminder" to true
        )
    }
    
    // ========== 预设消息 ==========
    
    suspend fun getPresetMessage(): String {
        try {
            val userId = getUserId()
            val api = getApi()
            val response = api.getPresetMessage(userId)
            
            if (response.isSuccessful) {
                return response.body()?.presetMessage ?: "如果你收到这条消息，说明我可能出事了，请尽快联系我或报警。"
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return "如果你收到这条消息，说明我可能出事了，请尽快联系我或报警。"
    }
    
    suspend fun setPresetMessage(message: String): Boolean {
        try {
            val userId = getUserId()
            val api = getApi()
            val request = com.safecheckin.app.data.api.PresetMessageRequest(
                userId = userId,
                message = message
            )
            val response = api.updatePresetMessage(request)
            return response.isSuccessful
        } catch (e: Exception) {
            e.printStackTrace()
            return false
        }
    }
    
    // ========== 每日提醒 ==========
    
    suspend fun getDailyReminder(): Boolean {
        try {
            val userId = getUserId()
            val api = getApi()
            val response = api.getDailyReminder(userId)
            if (response.isSuccessful) {
                return response.body()?.dailyReminder ?: true
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return true
    }
    
    suspend fun setDailyReminder(enabled: Boolean): Boolean {
        try {
            val userId = getUserId()
            val api = getApi()
            val request = com.safecheckin.app.data.api.DailyReminderRequest(
                userId = userId,
                enabled = enabled
            )
            val response = api.updateDailyReminder(request)
            return response.isSuccessful
        } catch (e: Exception) {
            e.printStackTrace()
            return false
        }
    }
    
    // ========== 账号注销 ==========
    
    suspend fun deleteAccount(): Boolean {
        try {
            val userId = getUserId()
            val api = getApi()
            val response = api.deleteAccount(userId)
            return response.isSuccessful
        } catch (e: Exception) {
            e.printStackTrace()
            return false
        }
    }
    
    // ========== 辅助函数 ==========
    
    private fun parseDateToLong(dateString: String): Long {
        return try {
            val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
            val date = format.parse(dateString) ?: Date()
            date.time
        } catch (e: Exception) {
            System.currentTimeMillis()
        }
    }
}