package com.joe.camera.webcam.ui

import android.content.Context
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.media3.common.MediaItem as ExoMediaItem
import androidx.media3.common.MimeTypes
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import coil.ImageLoader
import coil.compose.AsyncImage
import coil.decode.VideoFrameDecoder
import coil.request.ImageRequest
import coil.request.videoFrameMillis
import com.joe.camera.webcam.MainViewModel
import com.joe.camera.webcam.model.MediaItem
import com.joe.camera.webcam.model.MediaKind
import kotlinx.coroutines.delay

@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class)
@Composable
fun MediaGridScreen(viewModel: MainViewModel, media: List<MediaItem>, onBack: () -> Unit, onOpen: (MediaItem) -> Unit) {
    var deleteTarget by remember { mutableStateOf<MediaItem?>(null) }
    LaunchedEffect(Unit) { viewModel.loadMedia() }
    Scaffold(topBar = { TopAppBar(title = { Text("媒体库") }, navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.Default.ArrowBack, "返回") } }) }) { padding ->
        if (media.isEmpty()) Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) { Text("Download/jf 中暂无媒体", color = Color.Gray) }
        else LazyVerticalGrid(columns = GridCells.Fixed(3), modifier = Modifier.fillMaxSize().padding(padding), horizontalArrangement = Arrangement.spacedBy(4.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
            items(media, key = { "${it.kind}-${it.id}" }) { item ->
                Box(Modifier.aspectRatio(1f).background(Color.DarkGray).combinedClickable(onClick = { onOpen(item) }, onLongClick = { viewModel.selectMedia(item); deleteTarget = item })) {
                    MediaThumbnail(item, Modifier.fillMaxSize())
                    if (item.kind == MediaKind.VIDEO) Icon(Icons.Default.PlayCircle, null, tint = Color.White, modifier = Modifier.align(Alignment.Center).size(42.dp))
                }
            }
        }
    }
    deleteTarget?.let { item ->
        AlertDialog(onDismissRequest = { deleteTarget = null }, title = { Text("删除文件") }, text = { Text(item.displayName) }, confirmButton = { TextButton(onClick = { viewModel.deleteSelected(); deleteTarget = null }) { Text("确定") } }, dismissButton = { TextButton(onClick = { deleteTarget = null }) { Text("取消") } })
    }
}

@Composable
private fun MediaThumbnail(item: MediaItem, modifier: Modifier = Modifier) {
    val context = LocalContext.current
    val imageLoader = remember(context) { ImageLoader.Builder(context).components { add(VideoFrameDecoder.Factory()) }.build() }
    val request = remember(item.uri) { ImageRequest.Builder(context).data(item.uri).apply { if (item.kind == MediaKind.VIDEO) videoFrameMillis(0) }.crossfade(true).build() }
    AsyncImage(model = request, imageLoader = imageLoader, contentDescription = item.displayName, contentScale = ContentScale.Crop, modifier = modifier)
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ImageViewerScreen(viewModel: MainViewModel, onBack: () -> Unit) {
    val item = viewModel.selectedMedia ?: return onBack()
    var confirmDelete by remember { mutableStateOf(false) }
    Scaffold(topBar = { TopAppBar(title = { Text(item.displayName) }, navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.Default.ArrowBack, "返回") } }, actions = { IconButton(onClick = { confirmDelete = true }) { Icon(Icons.Default.Delete, "删除") } }) }) { padding ->
        AsyncImage(model = item.uri, contentDescription = item.displayName, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize().padding(padding).background(Color(0xFF17171A)))
    }
    if (confirmDelete) DeleteDialog(item.displayName, onDismiss = { confirmDelete = false }, onConfirm = { if (viewModel.deleteSelected()) onBack(); confirmDelete = false })
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun VideoViewerScreen(viewModel: MainViewModel, onBack: () -> Unit) {
    val item = viewModel.selectedMedia ?: return onBack()
    val context = LocalContext.current
    val player = remember(item.uri) {
        ExoPlayer.Builder(context).build().apply {
            setMediaItem(ExoMediaItem.Builder().setUri(item.uri).setMimeType(MimeTypes.VIDEO_MP4).build())
            prepare()
        }
    }
    var position by remember { mutableLongStateOf(0L) }
    var duration by remember { mutableLongStateOf(1L) }
    var playing by remember { mutableStateOf(false) }
    var rotation by remember { mutableFloatStateOf(0f) }
    var confirmDelete by remember { mutableStateOf(false) }
    DisposableEffect(player) { onDispose { player.release() } }
    LaunchedEffect(player) { while (true) { position = player.currentPosition.coerceAtLeast(0); duration = player.duration.coerceAtLeast(1); playing = player.isPlaying; delay(100) } }
    Scaffold(topBar = { TopAppBar(title = { Text(item.displayName) }, navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.Default.ArrowBack, "返回") } }, actions = { IconButton(onClick = { confirmDelete = true }) { Icon(Icons.Default.Delete, "删除") } }) }) { padding ->
        Box(Modifier.fillMaxSize().padding(padding).background(Color(0xFF17171A))) {
            AndroidView(factory = { PlayerView(it).apply { useController = false; this.player = player } }, update = { it.player = player }, modifier = Modifier.fillMaxSize().graphicsLayer { rotationZ = rotation })
            Column(Modifier.align(Alignment.BottomCenter).fillMaxWidth().background(Color.Black.copy(alpha = 0.35f)).padding(bottom = 20.dp)) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    IconButton(onClick = { player.seekTo((player.currentPosition - 34).coerceAtLeast(0)) }) { Icon(Icons.Default.Remove, null) }
                    IndustrialSlider(
                        value = position.toFloat().coerceIn(0f, duration.toFloat()),
                        onValueChange = { position = it.toLong(); player.seekTo(position) },
                        valueRange = 0f..duration.toFloat(),
                        activeColor = Color.White,
                        modifier = Modifier.weight(1f),
                    )
                    IconButton(onClick = { player.seekTo((player.currentPosition + 34).coerceAtMost(duration)) }) { Icon(Icons.Default.Add, null) }
                }
                Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically) {
                    IconButton(onClick = { rotation -= 90f }) { Icon(Icons.Default.RotateLeft, null, modifier = Modifier.size(30.dp)) }
                    IconButton(onClick = { if (player.isPlaying) player.pause() else player.play() }) { Icon(if (playing) Icons.Default.Pause else Icons.Default.PlayArrow, null, modifier = Modifier.size(48.dp)) }
                    IconButton(onClick = { rotation += 90f }) { Icon(Icons.Default.RotateRight, null, modifier = Modifier.size(30.dp)) }
                }
            }
        }
    }
    if (confirmDelete) DeleteDialog(item.displayName, onDismiss = { confirmDelete = false }, onConfirm = { player.release(); if (viewModel.deleteSelected()) onBack(); confirmDelete = false })
}

@Composable
private fun DeleteDialog(name: String, onDismiss: () -> Unit, onConfirm: () -> Unit) {
    AlertDialog(onDismissRequest = onDismiss, title = { Text("删除文件") }, text = { Text(name) }, confirmButton = { TextButton(onClick = onConfirm) { Text("确定") } }, dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } })
}
