package ru.forbion.f7cloud.feature.files

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.media3.common.MediaItem
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import ru.forbion.f7cloud.core.designsystem.F7Theme
import java.io.File

/** Нативный проигрыватель видео/аудио (Media3/ExoPlayer). Файл уже скачан в кэш. */
class MediaPlayerActivity : ComponentActivity() {
    @OptIn(ExperimentalMaterial3Api::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val path = intent.getStringExtra(EXTRA_PATH).orEmpty()
        val title = intent.getStringExtra(EXTRA_TITLE).orEmpty()
        val isVideo = intent.getBooleanExtra(EXTRA_IS_VIDEO, true)
        if (path.isBlank()) {
            finish()
            return
        }
        setContent {
            F7Theme {
                MediaPlayerScreen(path = path, title = title, isVideo = isVideo, onClose = { finish() })
            }
        }
    }

    companion object {
        private const val EXTRA_PATH = "path"
        private const val EXTRA_TITLE = "title"
        private const val EXTRA_IS_VIDEO = "is_video"

        fun intent(context: Context, path: String, title: String, isVideo: Boolean): Intent =
            Intent(context, MediaPlayerActivity::class.java).apply {
                putExtra(EXTRA_PATH, path)
                putExtra(EXTRA_TITLE, title)
                putExtra(EXTRA_IS_VIDEO, isVideo)
            }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun MediaPlayerScreen(
    path: String,
    title: String,
    isVideo: Boolean,
    onClose: () -> Unit,
) {
    val context = LocalContext.current
    val player = remember {
        ExoPlayer.Builder(context).build().apply {
            setMediaItem(MediaItem.fromUri(Uri.fromFile(File(path))))
            prepare()
            playWhenReady = true
        }
    }
    DisposableEffect(Unit) {
        onDispose { player.release() }
    }
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Black),
    ) {
        AndroidView(
            factory = { ctx ->
                PlayerView(ctx).apply {
                    this.player = player
                    useController = true
                    setShowNextButton(false)
                    setShowPreviousButton(false)
                    // Аудио: PlayerView без видео-поверхности показывает только контролы.
                }
            },
            modifier = Modifier.fillMaxSize(),
        )
        TopAppBar(
            title = {
                Text(
                    text = title,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    color = Color.White,
                    style = MaterialTheme.typography.titleMedium,
                )
            },
            navigationIcon = {
                IconButton(onClick = onClose) {
                    Text("←", color = Color.White, modifier = Modifier.padding(8.dp))
                }
            },
            modifier = Modifier.align(Alignment.TopCenter),
        )
    }
}
