package com.aiosman.ravenow.ui.group

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.ui.platform.LocalContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.InputStream
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.ui.zIndex
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.compose.viewModel
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.StatusBarSpacer
import com.aiosman.ravenow.ui.modifiers.noRippleClickable

@Composable
fun GroupProfileSettingsScreen(groupId: String) {
    val navController = LocalNavController.current
    val context = LocalContext.current
    val AppColors = LocalAppTheme.current

    val viewModel = viewModel<GroupProfileSettingsViewModel>(
        key = "GroupProfileSettingsViewModel_$groupId",
        factory = object : ViewModelProvider.Factory {
            override fun <T : ViewModel> create(modelClass: Class<T>): T {
                return GroupProfileSettingsViewModel(groupId) as T
            }
        }
    )

    // 群图标选择器
    val groupIconPicker = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri ->
        uri?.let {
            // 直接转换为 Bitmap 并显示，不进行裁剪
            kotlinx.coroutines.CoroutineScope(Dispatchers.IO).launch {
                val bitmap = uriToBitmap(context, it)
                bitmap?.let { bmp ->
                    withContext(Dispatchers.Main) {
                        viewModel.setGroupIcon(bmp)
                    }
                }
            }
        }
    }

    // 群头像选择器
    val groupAvatarPicker = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri ->
        uri?.let {
            // 直接转换为 Bitmap 并显示，不进行裁剪
            kotlinx.coroutines.CoroutineScope(Dispatchers.IO).launch {
                val bitmap = uriToBitmap(context, it)
                bitmap?.let { bmp ->
                    withContext(Dispatchers.Main) {
                        viewModel.setGroupAvatar(bmp)
                    }
                }
            }
        }
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(AppColors.background)
    ) {
        // 群默认图标图片区域（渐变背景）
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(249.dp)
                .background(
                    brush = Brush.horizontalGradient(
                        colors = listOf(
                            Color(0xFF7C45ED),
                            Color(0xFFE91E63)
                        )
                    ),
                    shape = RoundedCornerShape(bottomStart = 20.dp, bottomEnd = 20.dp)
                )
                .noRippleClickable {
                    groupIconPicker.launch("image/*")
                }
        ) {
            // 显示选中的图标或默认渐变
            viewModel.groupIconBitmap?.let { bitmap ->
                Image(
                    bitmap = bitmap.asImageBitmap(),
                    contentDescription = null,
                    modifier = Modifier.fillMaxSize(),
                    contentScale = ContentScale.Crop
                )
            }
        }

        // 顶部导航栏（显示在渐变背景上层）
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .zIndex(1f)
        ) {
            StatusBarSpacer()
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 12.dp, horizontal = 12.dp),
                horizontalArrangement = Arrangement.Start,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Image(
                    painter = painterResource(R.drawable.rider_pro_back_icon),
                    modifier = Modifier
                        .size(24.dp)
                        .noRippleClickable {
                            navController.navigateUp()
                        },
                    contentDescription = null,
                    colorFilter = ColorFilter.tint(Color.White)
                )
                Spacer(modifier = Modifier.weight(1f))
                Text(
                    text = stringResource(R.string.group_info_edit),
                    style = TextStyle(
                        color = Color.White,
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold
                    ),
                    textAlign = TextAlign.Center
                )
                Spacer(modifier = Modifier.weight(1f))
            }
        }

        // 群头像区域
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 270.dp)
        ) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp),
                contentAlignment = Alignment.Center
            ) {
                Box(
                    modifier = Modifier
                        .size(70.dp)
                ) {
                    // 群头像显示
                    if (viewModel.groupInfo?.groupAvatar?.isNotEmpty() == true) {
                        CustomAsyncImage(
                            imageUrl = viewModel.groupInfo!!.groupAvatar,
                            modifier = Modifier
                                .fillMaxSize()
                                .clip(RoundedCornerShape(12.dp)),
                            contentDescription = "群聊头像"
                        )
                    } else {
                        Box(
                            modifier = Modifier
                                .fillMaxSize()
                                .clip(RoundedCornerShape(16.dp))
                                .background(AppColors.decentBackground),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = viewModel.groupInfo?.groupName?.firstOrNull()?.toString() ?: "",
                                style = TextStyle(
                                    color = AppColors.text,
                                    fontSize = 32.sp,
                                    fontWeight = FontWeight.Bold
                                )
                            )
                        }
                    }

                    // 右下角加号按钮
                    Box(
                        modifier = Modifier
                            .align(Alignment.BottomEnd)
                            .size(22.dp)
                            .clip(CircleShape)
                            .background(
                                brush = Brush.horizontalGradient(
                                    colors = listOf(
                                        Color(0xFF7C45ED),
                                        Color(0xFF7BD8F8)
                                    )
                                )
                            )
                            .noRippleClickable {
                                groupAvatarPicker.launch("image/*")
                            },
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = "+",
                            color = Color.White,
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Medium
                        )
                    }
                }
            }

            Spacer(modifier = Modifier.height(24.dp))

            // 群聊名称编辑框
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp)
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clip(RoundedCornerShape(8.dp))
                        .background(AppColors.decentBackground)
                        .padding(horizontal = 12.dp, vertical = 12.dp)
                ) {
                    Text(
                        text = stringResource(R.string.group_name)+":",
                        style = TextStyle(
                            color = AppColors.text.copy(alpha = 0.7f),
                            fontSize = 14.sp
                        )
                    )
                    BasicTextField(
                        value = viewModel.groupName,
                        onValueChange = { viewModel.updateGroupName(it) },
                        textStyle = TextStyle(
                            color = AppColors.text,
                            fontSize = 15.sp
                        ),
                        cursorBrush = SolidColor(AppColors.text),
                        modifier = Modifier.padding(start = 70.dp),
                        singleLine = true
                    )
                }
            }

            Spacer(modifier = Modifier.weight(1f))

            // 保存按钮
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 24.dp)
                    .height(50.dp)
                    .clip(RoundedCornerShape(25.dp))
                    .background(
                        brush = Brush.horizontalGradient(
                            colors = listOf(
                                Color(0xFF7C45ED),
                                Color(0xFF7BD8F8)
                            )
                        )
                    )
                    .noRippleClickable {
                        // TODO: 实现保存功能
                    },
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = stringResource(R.string.save),
                    style = TextStyle(
                        color = Color.White,
                        fontSize = 17.sp,
                        fontWeight = FontWeight.Medium
                    )
                )
            }
        }
    }
}

// 将 Uri 转换为 Bitmap 的辅助函数
fun uriToBitmap(context: android.content.Context, uri: Uri): Bitmap? {
    return try {
        val inputStream: InputStream? = context.contentResolver.openInputStream(uri)
        BitmapFactory.decodeStream(inputStream)
    } catch (e: Exception) {
        e.printStackTrace()
        null
    }
}

