package com.example.livingai.pages.camera

import android.net.Uri
import android.widget.VideoView
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
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.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
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.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.example.livingai.ui.theme.LivingAITheme
import kotlinx.coroutines.delay

@Composable
fun ViewVideoScreen(
    videoUri: String,
    shouldAllowRetake: Boolean,
    onRetake: () -> Unit,
    onAccept: () -> Unit,
    onBack: () -> Unit
) {
    var isPlaying by remember { mutableStateOf(false) }
    var videoView: VideoView? by remember { mutableStateOf(null) }
    var isPrepared by remember { mutableStateOf(false) }
    var currentPosition by remember { mutableIntStateOf(0) }
    var duration by remember { mutableIntStateOf(0) }

    // Polling for video progress
    LaunchedEffect(isPlaying, isPrepared) {
        if (isPlaying && isPrepared) {
            while (true) {
                videoView?.let {
                    currentPosition = it.currentPosition
                    if (duration == 0) duration = it.duration
                }
                delay(100) 
            }
        }
    }

    LivingAITheme {
        Scaffold { padding ->
            Box(modifier = Modifier.fillMaxSize().padding(padding)) {
                AndroidView(
                    factory = { context ->
                        VideoView(context).apply {
                            setVideoURI(Uri.parse(videoUri))
                            setOnPreparedListener { mp ->
                                mp.isLooping = true
                                isPrepared = true
                                duration = mp.duration
                                seekTo(1) 
                            }
                            setOnCompletionListener {
                                isPlaying = false
                            }
                        }
                    },
                    update = { view ->
                        videoView = view
                        if (isPrepared) {
                            if (isPlaying) {
                                if (!view.isPlaying) view.start()
                            } else {
                                if (view.isPlaying) view.pause()
                            }
                        }
                    },
                    modifier = Modifier.fillMaxSize()
                )

                // Controls Overlay
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(if (!isPlaying) Color.Black.copy(alpha = 0.3f) else Color.Transparent)
                        .clickable { isPlaying = !isPlaying },
                    contentAlignment = Alignment.Center
                ) {
                    if (!isPlaying) {
                        Icon(
                            imageVector = Icons.Default.PlayArrow,
                            contentDescription = "Play",
                            tint = Color.White,
                            modifier = Modifier
                                .size(64.dp)
                                .background(Color.Black.copy(alpha = 0.4f), shape = MaterialTheme.shapes.medium)
                                .padding(8.dp)
                        )
                    }
                }

                // Bottom Control Bar
                Column(
                    modifier = Modifier
                        .align(Alignment.BottomCenter)
                        .fillMaxWidth()
                        .background(Color.Black.copy(alpha = 0.6f))
                        .padding(16.dp)
                ) {
                    // Progress Bar
                    if (duration > 0) {
                        LinearProgressIndicator(
                            progress = { if (duration > 0) currentPosition.toFloat() / duration.toFloat() else 0f },
                            modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
                        )
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            Text(
                                text = formatTime(currentPosition),
                                color = Color.White,
                                style = MaterialTheme.typography.bodySmall
                            )
                            Text(
                                text = formatTime(duration),
                                color = Color.White,
                                style = MaterialTheme.typography.bodySmall
                            )
                        }
                    }

                    if (shouldAllowRetake) {
                        Row(
                            modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
                            horizontalArrangement = Arrangement.SpaceEvenly
                        ) {
                            Button(onClick = onRetake) {
                                Text("Retake")
                            }
                            Button(onClick = onAccept) {
                                Text("Accept")
                            }
                        }
                    }
                }

                if (!shouldAllowRetake) {
                    IconButton(
                        onClick = onBack,
                        modifier = Modifier
                            .align(Alignment.TopStart)
                            .padding(16.dp)
                    ) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "Back",
                            tint = Color.White
                        )
                    }
                }
            }
        }
    }
    
    DisposableEffect(Unit) {
        onDispose {
             videoView?.stopPlayback()
        }
    }
}

fun formatTime(millis: Int): String {
    val seconds = (millis / 1000) % 60
    val minutes = (millis / (1000 * 60)) % 60
    return String.format("%02d:%02d", minutes, seconds)
}
