package com.aiosman.ravenow.ui.profile

import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.aiosman.ravenow.GuestLoginCheckOut
import com.aiosman.ravenow.GuestLoginCheckOutScene
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.data.UserServiceImpl
import com.aiosman.ravenow.exp.viewModelFactory
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.composables.PointsPaymentDialog
import com.aiosman.ravenow.ui.index.tabs.ai.tabs.mine.MineAgentViewModel
import com.aiosman.ravenow.ui.index.tabs.profile.MyProfileViewModel
import com.aiosman.ravenow.ui.navigateToChatAi
import com.aiosman.ravenow.ui.navigateToPost
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AiProfileWrap(id: String) {
    val model: AiProfileViewModel = viewModel(factory = viewModelFactory {
        AiProfileViewModel()
    }, key = "aiViewModel_${id}")
    
    val navController = LocalNavController.current
    val scope = rememberCoroutineScope()
    
    // 记忆管理相关状态
    var showMemoryManageDialog by remember { mutableStateOf(false) }
    var showAddMemoryDialog by remember { mutableStateOf(false) }
    var showAddMemoryConfirmDialog by remember { mutableStateOf(false) }
    var pendingMemoryText by remember { mutableStateOf("") }
    val memoryManageSheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    val addMemorySheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    
    // 获取 chatAIId (openId)
    val chatAIId = model.profile?.chatAIId ?: ""
    
    // 创建记忆管理 ViewModel
    val memoryViewModel: AgentMemoryManageViewModel? = if (chatAIId.isNotEmpty()) {
        viewModel(factory = viewModelFactory {
            AgentMemoryManageViewModel(chatAIId)
        }, key = "agentMemoryViewModel_${chatAIId}")
    } else {
        null
    }
    
    LaunchedEffect(Unit) {
        model.loadProfile(id)
        MyProfileViewModel.loadProfile()
    }
    
    val isSelf = id == MyProfileViewModel.profile?.id.toString()
    
    Box(modifier = Modifier.fillMaxSize()) {
        AiProfileV3(
            profile = model.profile,
            moments = model.moments,
            postCount = model.momentLoader.total,
            isSelf = isSelf,
            onFollowClick = {
                model.profile?.let {
                    if (it.isFollowing) {
                        model.unFollowUser(id)
                    } else {
                        model.followUser(id)
                    }
                }
            },
            onChatClick = {
                // 检查游客模式
                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.CHAT_WITH_AGENT)) {
                    navController.navigate(NavigationRoute.Login.route)
                } else {
                    model.profile?.let { profile ->
                        scope.launch {
                            try {
                                // 参考主页逻辑：使用chatAIId作为openId创建单聊并导航
                                // 创建单聊
                                MineAgentViewModel.createSingleChat(profile.chatAIId)
                                
                                // 通过chatAIId获取完整的AI profile（类似主页的goToChatAi逻辑）
                                val userService = UserServiceImpl()
                                val aiProfile = userService.getUserProfileByOpenId(profile.chatAIId)
                                
                                // 导航到AI聊天页面
                                navController.navigateToChatAi(aiProfile.id.toString())
                            } catch (e: Exception) {
                                Log.e("AiProfileWrap", "Error navigating to AI chat", e)
                                // 如果获取失败，直接使用当前profile的id
                                navController.navigateToChatAi(profile.id.toString())
                            }
                        }
                    }
                }
            },
            onShareClick = {
                // TODO: 实现分享逻辑
                Log.d("AiProfileWrap", "分享功能待实现")
            },
            onMemoryManageClick = {
                if (chatAIId.isNotEmpty()) {
                    showMemoryManageDialog = true
                }
            },
            onLoadMore = {
                Log.d("AiProfileWrap", "onLoadMore被调用")
                model.loadMoreMoment()
            },
            onComment = { moment ->
                navController.navigateToPost(moment.id)
            }
        )
        
        // 添加记忆对话框
        if (showAddMemoryDialog && memoryViewModel != null) {
            ModalBottomSheet(
                onDismissRequest = { showAddMemoryDialog = false },
                sheetState = addMemorySheetState,
                containerColor = Color(0xFFFAF9FB),
                dragHandle = {
                    Box(
                        modifier = Modifier
                            .width(36.dp)
                            .height(5.dp)
                            .padding(top = 5.dp)
                            .background(
                                Color(0xFFCCCCCC),
                                RoundedCornerShape(100.dp)
                            )
                    )
                },
                shape = RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp)
            ) {
                AddAgentMemoryDialog(
                    profile = model.profile,
                    viewModel = memoryViewModel,
                    onDismiss = { showAddMemoryDialog = false },
                    onRequestAddMemory = { memoryText ->
                        // 关闭添加对话框，显示确认框
                        showAddMemoryDialog = false
                        pendingMemoryText = memoryText
                        showAddMemoryConfirmDialog = true
                    }
                )
            }
        }
        
        // 记忆管理弹窗
        if (showMemoryManageDialog && memoryViewModel != null && chatAIId.isNotEmpty()) {
            ModalBottomSheet(
                onDismissRequest = { showMemoryManageDialog = false },
                sheetState = memoryManageSheetState,
                containerColor = Color(0xFFFAF9FB),
                dragHandle = {
                    Box(
                        modifier = Modifier
                            .width(36.dp)
                            .height(5.dp)
                            .padding(top = 5.dp)
                            .background(
                                Color(0xFFCCCCCC),
                                RoundedCornerShape(100.dp)
                            )
                    )
                },
                shape = RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp)
            ) {
                // 立即展开到全屏，避免逐渐变高的动画
                LaunchedEffect(Unit) {
                    memoryManageSheetState.expand()
                }
                AgentMemoryManageContent(
                    openId = chatAIId,
                    profile = model.profile,
                    viewModel = memoryViewModel,
                    onAddMemoryClick = {
                        showMemoryManageDialog = false
                        showAddMemoryDialog = true
                    },
                    onDismiss = {
                        showMemoryManageDialog = false
                    }
                )
            }
        }
        
        // 添加记忆确认对话框
        if (showAddMemoryConfirmDialog && memoryViewModel != null) {
            val cost = memoryViewModel.addMemoryCost ?: 0
            val currentBalance = memoryViewModel.pointsBalance ?: 0
            val balanceAfterCost = (currentBalance - cost).coerceAtLeast(0)
            val isBalanceSufficient = currentBalance >= cost
            
            // 监听添加成功，关闭确认对话框并刷新积分余额
            LaunchedEffect(memoryViewModel.addMemorySuccess) {
                if (memoryViewModel.addMemorySuccess) {
                    showAddMemoryConfirmDialog = false
                    pendingMemoryText = ""
                    memoryViewModel.addMemorySuccess = false
                    memoryViewModel.loadPointsBalance() // 刷新积分余额
                }
            }
            
            PointsPaymentDialog(
                cost = cost,
                currentBalance = currentBalance,
                balanceAfterCost = balanceAfterCost,
                isBalanceSufficient = isBalanceSufficient,
                onConfirm = {
                    // 确认支付，添加记忆
                    memoryViewModel.addAgentMemory(pendingMemoryText)
                },
                onCancel = {
                    showAddMemoryConfirmDialog = false
                    pendingMemoryText = ""
                },
                title = stringResource(R.string.group_chat_info_add_memory),
                description = stringResource(R.string.group_chat_info_memory_description),
                isProcessing = memoryViewModel.isAddingMemory
            )
        }
    }
}

