package com.aiosman.ravenow.ui.index.tabs.moment.tabs.recommend

import android.net.Uri
import android.view.Gravity
import android.view.ViewGroup
import android.widget.FrameLayout
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlayArrow
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.DisposableEffect
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 androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
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.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.media3.common.C
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.common.util.UnstableApi
import androidx.media3.common.util.Util
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DefaultDataSourceFactory
import androidx.media3.datasource.DefaultHttpDataSource
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.ProgressiveMediaSource
import androidx.media3.ui.AspectRatioFrameLayout
import androidx.media3.ui.PlayerView
import com.aiosman.ravenow.R
import com.aiosman.ravenow.entity.MomentEntity
import com.aiosman.ravenow.ui.comment.CommentModalContent
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import androidx.compose.runtime.rememberCoroutineScope

/**
 * 短视频推荐Item组件
 * 不包含内部 Pager，由外层的 VerticalPager 处理滑动
 */
@OptIn(UnstableApi::class, ExperimentalMaterial3Api::class)
@Composable
fun VideoRecommendationItem(
    moment: MomentEntity,
    isVisible: Boolean = true, // 是否可见，用于控制播放/暂停
    onLikeClick: ((MomentEntity) -> Unit)? = null,
    onCommentClick: ((MomentEntity) -> Unit)? = null,
    onFavoriteClick: ((MomentEntity) -> Unit)? = null,
    onShareClick: ((MomentEntity) -> Unit)? = null,
    modifier: Modifier = Modifier
) {
    // 检查是否有视频
    val videoUrl = moment.videos?.firstOrNull()?.url
    if (videoUrl == null) {
        return
    }
    
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    val lifecycleOwner = LocalLifecycleOwner.current
    var showCommentModal by remember { mutableStateOf(false) }
    var sheetState = rememberModalBottomSheetState(
        skipPartiallyExpanded = true
    )
    var pauseIconVisibleState by remember { mutableStateOf(false) }
    
    val exoPlayer = remember(videoUrl) {
        ExoPlayer.Builder(context)
            .build()
            .apply {
                // 创建带有认证头的 HttpDataSource.Factory
                val httpDataSourceFactory = DefaultHttpDataSource.Factory()
                    .setUserAgent(Util.getUserAgent(context, context.packageName))
                    .setDefaultRequestProperties(
                        mapOf(
                            "Authorization" to "Bearer ${com.aiosman.ravenow.AppStore.token ?: ""}",
                            "DEVICE-OS" to "Android"
                        )
                    )
                
                // 创建 DataSource.Factory，使用自定义的 HttpDataSource.Factory
                val dataSourceFactory: DataSource.Factory = DefaultDataSourceFactory(
                    context,
                    httpDataSourceFactory
                )
                val source = ProgressiveMediaSource.Factory(dataSourceFactory)
                    .createMediaSource(MediaItem.fromUri(Uri.parse(videoUrl)))
                
                this.prepare(source)
            }
    }
    
    // 根据 isVisible 控制播放/暂停
    LaunchedEffect(isVisible) {
        if (isVisible) {
            exoPlayer.playWhenReady = true
            exoPlayer.play()
        } else {
            exoPlayer.pause()
        }
    }
    
    exoPlayer.videoScalingMode = C.VIDEO_SCALING_MODE_SCALE_TO_FIT
    exoPlayer.repeatMode = Player.REPEAT_MODE_ONE
    
    Box(
        modifier = modifier
            .fillMaxSize()
            .background(Color.Black)
    ) {
        // 视频播放器
        Box(
            modifier = Modifier
                .fillMaxSize()
        ) {
            AndroidView(
                factory = { ctx ->
                    FrameLayout(ctx).apply {
                        setBackgroundColor(Color.Black.toArgb())
                        val view = PlayerView(ctx).apply {
                            hideController()
                            useController = false
                            player = exoPlayer
                            resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIXED_HEIGHT
                            layoutParams = FrameLayout.LayoutParams(
                                ViewGroup.LayoutParams.MATCH_PARENT,
                                ViewGroup.LayoutParams.MATCH_PARENT,
                                Gravity.CENTER
                            )
                        }
                        addView(view)
                    }
                },
                modifier = Modifier
                    .fillMaxSize()
                    .noRippleClickable {
                        pauseIconVisibleState = true
                        exoPlayer.pause()
                        scope.launch {
                            delay(100)
                            if (exoPlayer.isPlaying) {
                                exoPlayer.pause()
                            } else {
                                pauseIconVisibleState = false
                                exoPlayer.play()
                            }
                        }
                    }
            )
            
            if (pauseIconVisibleState) {
                Icon(
                    imageVector = Icons.Default.PlayArrow,
                    contentDescription = null,
                    modifier = Modifier
                        .align(Alignment.Center)
                        .size(80.dp),
                    tint = Color.White
                )
            }
        }
        
        // 底部右侧：互动按钮
        Box(
            modifier = Modifier
                .fillMaxSize(),
            contentAlignment = Alignment.BottomEnd
        ) {
            Column(
                modifier = Modifier
                    .padding(bottom = 72.dp, end = 12.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                UserAvatar(avatarUrl = moment.avatar)
                VideoBtn(
                    icon = R.drawable.rider_pro_video_like,
                    text = formatCount(moment.likeCount)
                ) {
                    onLikeClick?.invoke(moment)
                }
                VideoBtn(
                    icon = R.drawable.rider_pro_video_comment,
                    text = formatCount(moment.commentCount)
                ) {
                    showCommentModal = true
                    onCommentClick?.invoke(moment)
                }
                VideoBtn(
                    icon = R.drawable.rider_pro_video_favor,
                    text = formatCount(moment.favoriteCount)
                ) {
                    onFavoriteClick?.invoke(moment)
                }
                VideoBtn(
                    icon = R.drawable.rider_pro_video_share,
                    text = formatCount(moment.shareCount)
                ) {
                    onShareClick?.invoke(moment)
                }
            }
        }
        
        // 底部左侧：用户信息和文字内容
        Box(
            modifier = Modifier
                .fillMaxSize(),
            contentAlignment = Alignment.BottomStart
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(start = 16.dp, bottom = 16.dp)
            ) {
                if (moment.location.isNotEmpty() && moment.location != "Worldwide") {
                    Row(
                        modifier = Modifier
                            .padding(bottom = 8.dp)
                            .background(
                                color = Color.Gray.copy(alpha = 0.5f),
                                shape = RoundedCornerShape(8.dp)
                            )
                            .padding(horizontal = 8.dp, vertical = 4.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.Start
                    ) {
                        Image(
                            modifier = Modifier
                                .size(20.dp)
                                .padding(end = 6.dp),
                            painter = painterResource(id = R.drawable.rider_pro_video_location),
                            contentDescription = ""
                        )
                        Text(
                            text = moment.location,
                            fontSize = 12.sp,
                            color = Color.White,
                            style = TextStyle(fontWeight = FontWeight.Bold)
                        )
                    }
                }
                Text(
                    text = "@${moment.nickname}",
                    fontSize = 16.sp,
                    color = Color.White,
                    style = TextStyle(fontWeight = FontWeight.Bold)
                )
                if (!moment.momentTextContent.isNullOrEmpty()) {
                    Text(
                        modifier = Modifier
                            .fillMaxWidth(0.8f)
                            .padding(top = 4.dp),
                        text = com.aiosman.ravenow.utils.Utils.unescapeHtml(moment.momentTextContent),
                        fontSize = 16.sp,
                        color = Color.White,
                        style = TextStyle(fontWeight = FontWeight.Bold),
                        overflow = TextOverflow.Ellipsis,
                        maxLines = 2
                    )
                }
            }
        }
    }
    
    // 评论弹窗
    if (showCommentModal) {
        ModalBottomSheet(
            onDismissRequest = { showCommentModal = false },
            containerColor = Color.White,
            sheetState = sheetState
        ) {
            CommentModalContent(postId = moment.id) {
                // 评论添加后的回调
            }
        }
    }
    
    // 释放 ExoPlayer
    DisposableEffect(videoUrl) {
        onDispose {
            exoPlayer.release()
        }
    }
    
    // 生命周期管理
    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_PAUSE -> {
                    exoPlayer.pause()
                }
                Lifecycle.Event.ON_RESUME -> {
                    if (isVisible) {
                        exoPlayer.play()
                    }
                }
                else -> {}
            }
        }
        lifecycleOwner.lifecycle.addObserver(observer)
        
        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }
}

@Composable
private fun UserAvatar(avatarUrl: String? = null) {
    Box(
        modifier = Modifier
            .padding(bottom = 16.dp)
            .size(40.dp)
            .clip(CircleShape)
            .background(Color.White.copy(alpha = 0.2f))
    ) {
        if (avatarUrl != null && avatarUrl.isNotEmpty()) {
            CustomAsyncImage(
                imageUrl = avatarUrl,
                contentDescription = "用户头像",
                modifier = Modifier.fillMaxSize(),
                defaultRes = R.drawable.default_avatar
            )
        } else {
            Image(
                painter = painterResource(id = R.drawable.default_avatar),
                contentDescription = "用户头像"
            )
        }
    }
}

// 格式化数字显示
private fun formatCount(count: Int): String {
    return when {
        count >= 1_000_000 -> String.format("%.1fM", count / 1_000_000.0)
        count >= 1_000 -> String.format("%.1fK", count / 1_000.0)
        else -> count.toString()
    }
}

@Composable
private fun VideoBtn(
    icon: Int,
    text: String,
    onClick: (() -> Unit)? = null
) {
    Column(
        modifier = Modifier
            .padding(bottom = 16.dp)
            .noRippleClickable {
                onClick?.invoke()
            },
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Image(
            modifier = Modifier.size(36.dp),
            painter = painterResource(id = icon),
            contentDescription = ""
        )
        Text(
            text = text,
            fontSize = 11.sp,
            color = Color.White,
            style = TextStyle(fontWeight = FontWeight.Bold)
        )
    }
}
