package com.aiosman.ravenow.ui.post

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
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.setValue
import android.graphics.BitmapFactory
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
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.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewModelScope
import com.aiosman.ravenow.AppThemeData
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.modifiers.noRippleClickable
import com.aiosman.ravenow.utils.DraftStore
import kotlinx.coroutines.launch
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DraftBoxBottomSheet(
    onDismiss: () -> Unit
) {
    val AppColors = LocalAppTheme.current
    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    val context = LocalContext.current
    val navController = LocalNavController.current
    val model = NewPostViewModel
    
    var drafts by remember { mutableStateOf<List<Draft>>(emptyList()) }
    val draftStore = remember { DraftStore(context) }
    val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()) }

    LaunchedEffect(Unit) {
        drafts = draftStore.getAllDrafts()
    }

    ModalBottomSheet(
        onDismissRequest = onDismiss,
        sheetState = sheetState,
        containerColor = AppColors.background,
        shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
        dragHandle = {}
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight(0.9f)
                .padding(horizontal = 16.dp, vertical = 8.dp)
        ) {
            // 标题
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 16.dp),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = stringResource(R.string.drafts),
                    fontSize = 17.sp,
                    fontWeight = FontWeight.Bold,
                    color = AppColors.text
                )
            }

            // 草稿列表
            if (drafts.isEmpty()) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .fillMaxHeight(),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = stringResource(R.string.no_drafts),
                        fontSize = 16.sp,
                        color = AppColors.secondaryText
                    )
                }
            } else {
                LazyColumn(
                    modifier = Modifier
                        .fillMaxWidth()
                        .weight(1f),
                    verticalArrangement = Arrangement.spacedBy(0.dp)
                ) {
                    itemsIndexed(drafts) { index, draft ->
                        DraftItem(
                            draft = draft,
                            dateFormat = dateFormat,
                            onEditClick = {
                                model.viewModelScope.launch {
                                    model.loadDraft(context, draft)
                                    onDismiss()
                                }
                            },
                            onDeleteClick = {
                                draftStore.deleteDraft(index)
                                drafts = draftStore.getAllDrafts()
                            },
                            AppColors = AppColors,
                            context = context
                        )
                        // 在草稿项之间添加分割线（最后一个不添加）
                        if (index < drafts.size - 1) {
                            Spacer(modifier = Modifier.height(12.dp))
                            Divider(
                                color = AppColors.secondaryText.copy(alpha = 0.2f),
                                thickness = 0.5.dp,
                                modifier = Modifier.padding(horizontal = 16.dp)
                            )
                            Spacer(modifier = Modifier.height(12.dp))
                        }
                    }
                }

                // 底部提示
                Text(
                    text = stringResource(R.string.only_save_the_last_5_drafts),
                    fontSize = 12.sp,
                    color = AppColors.secondaryText,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 8.dp),
                    textAlign = androidx.compose.ui.text.style.TextAlign.Center
                )
            }
        }
    }
}

@Composable
private fun DraftItem(
    draft: Draft,
    dateFormat: SimpleDateFormat,
    onEditClick: () -> Unit,
    onDeleteClick: () -> Unit,
    AppColors: AppThemeData,
    context: android.content.Context
) {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(12.dp))
            .background(AppColors.secondaryBackground)
            .padding(12.dp)
    ) {
        Column {
            // 文字内容（最多1行，超出用...截断）
            if (draft.textContent.isNotBlank()) {
                Text(
                    text = draft.textContent,
                    fontSize = 14.sp,
                    color = AppColors.text,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    modifier = Modifier.fillMaxWidth()
                )
                Spacer(modifier = Modifier.height(8.dp))
            }

            // 图片预览
            if (draft.imageList.isNotEmpty()) {
                val displayImages = draft.imageList.take(5) // 最多显示5张
                val totalImages = draft.imageList.size
                val showMoreIndicator = totalImages > 5
                val visibleCount = if (showMoreIndicator) 3 else displayImages.size
                val remainingCount = totalImages - 3

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    // 显示前3张或全部（如果少于5张）
                    displayImages.take(visibleCount).forEach { imageItem ->
                        DraftImageThumbnail(
                            imageItem = imageItem,
                            context = context,
                            modifier = Modifier.size(55.dp),
                            AppColors = AppColors
                        )
                    }
                    
                    // 如果超过5张，显示"more X images"
                    if (showMoreIndicator) {
                        Box(
                            modifier = Modifier
                                .size(55.dp)
                                .clip(RoundedCornerShape(12.dp))
                                .background(AppColors.inputBackground),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = "more\n$remainingCount\nimages",
                                fontSize = 11.sp,
                                color = AppColors.secondaryText,
                                textAlign = androidx.compose.ui.text.style.TextAlign.Center,
                                lineHeight = 14.sp
                            )
                        }
                    }
                }
                Spacer(modifier = Modifier.height(8.dp))
            }

            // 底部操作栏
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 编辑和删除按钮
                Row(
                    horizontalArrangement = Arrangement.spacedBy(12.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // 编辑按钮
                    Row(
                        modifier = Modifier.noRippleClickable { onEditClick() },
                        horizontalArrangement = Arrangement.spacedBy(4.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            painter = painterResource(id = R.mipmap.icons_infor_edit),
                            contentDescription = "edit",
                            modifier = Modifier.size(16.dp),
                            tint = AppColors.text
                        )
                        Text(
                            text = stringResource(R.string.edit_profile),
                            fontSize = 12.sp,
                            color = AppColors.text
                        )
                    }

                    // 删除按钮
                    Row(
                        modifier = Modifier.noRippleClickable { onDeleteClick() },
                        horizontalArrangement = Arrangement.spacedBy(4.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            painter = painterResource(id = R.drawable.rider_pro_moment_delete),
                            contentDescription = "delete",
                            modifier = Modifier.size(16.dp),
                            tint = AppColors.text
                        )
                        Text(
                            text = stringResource(R.string.delete),
                            fontSize = 12.sp,
                            color = AppColors.text
                        )
                    }
                }

                // 时间戳
                Text(
                    text = dateFormat.format(Date(draft.createdAt)),
                    fontSize = 12.sp,
                    color = AppColors.secondaryText
                )
            }
        }
    }
}

@Composable
private fun DraftImageThumbnail(
    imageItem: DraftImageItem,
    context: android.content.Context,
    modifier: Modifier = Modifier,
    AppColors: AppThemeData
) {
    Box(
        modifier = modifier
            .clip(RoundedCornerShape(12.dp))
           
    ) {
        val file = File(context.cacheDir, imageItem.filename)
        if (file.exists()) {
            // 尝试从文件加载 Bitmap
            val bitmap = remember(file.absolutePath) {
                BitmapFactory.decodeFile(file.absolutePath)
            }
            if (bitmap != null) {
                CustomAsyncImage(
                    context = context,
                    imageUrl = bitmap,
                    contentDescription = "",
                    modifier = Modifier.fillMaxSize(),
                    contentScale = ContentScale.Crop
                )
            } else {
                // 如果加载失败，尝试使用 URI
                CustomAsyncImage(
                    context = context,
                    imageUrl = imageItem.uri,
                    contentDescription = "",
                    modifier = Modifier.fillMaxSize(),
                    contentScale = ContentScale.Crop
                )
            }
        } else {
            // 如果文件不存在，显示占位符
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    painter = painterResource(id = R.drawable.rider_pro_new_post_add_pic),
                    contentDescription = "image",
                    modifier = Modifier.size(24.dp),
                    tint = AppColors.secondaryText
                )
            }
        }
    }
}
