package com.horrortv.app.presentation.detail

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.focusable
import androidx.compose.foundation.interaction.MutableInteractionSource
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
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.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.horrortv.app.domain.model.Movie
import com.horrortv.app.presentation.common.TvErrorDisplay
import com.horrortv.app.presentation.theme.HorrorColors
import com.horrortv.app.presentation.theme.HorrorTypography

private val PosterShape = RoundedCornerShape(12.dp)
private val PlayButtonShape = RoundedCornerShape(12.dp)
private val PlayButtonWidth = 400.dp
private val PlayButtonHeight = 70.dp

@Composable
fun DetailScreen(
    imdbId: String,
    viewModel: DetailViewModel,
    onNavigateBack: () -> Unit,
    onNavigateToPlayer: (String, String) -> Unit,
    modifier: Modifier = Modifier
) {
    BackHandler(enabled = true) { onNavigateBack() }
    
    val uiState by viewModel.uiState.collectAsState()
    val movie = uiState.movie
    
    LaunchedEffect(imdbId) { viewModel.loadMovie(imdbId) }
    
    Box(
        modifier = modifier.fillMaxSize().background(HorrorColors.HorrorBlack)
    ) {
        when {
            uiState.isLoading -> DetailLoadingIndicator()
            uiState.error != null -> {
                val error = uiState.error
                if (error != null) {
                    TvErrorDisplay(error = error, onRetry = { viewModel.retry() })
                }
            }
            movie != null -> MovieDetailContent(
                movie = movie,
                onPlayClick = { onNavigateToPlayer(movie.imdbId, movie.title) },
                modifier = Modifier.fillMaxSize()
            )
        }
    }
}

@Composable
private fun DetailLoadingIndicator() {
    Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
        CircularProgressIndicator(color = HorrorColors.HorrorRed, modifier = Modifier.padding(48.dp))
    }
}

@Composable
fun MovieDetailContent(
    movie: Movie,
    onPlayClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    var isPlayFocused by remember { mutableStateOf(false) }
    val playFocusRequester = remember { FocusRequester() }
    val interactionSource = remember { MutableInteractionSource() }
    
    LaunchedEffect(Unit) {
        kotlinx.coroutines.delay(500)
        playFocusRequester.requestFocus()
    }
    
    val playButtonColor = if (isPlayFocused) HorrorColors.HorrorAccent else HorrorColors.HorrorRed
    val scale = if (isPlayFocused) 1.08f else 1.0f
    
    Box(modifier = modifier) {
        AsyncImage(
            model = movie.posterUrl,
            contentDescription = null,
            contentScale = ContentScale.Crop,
            modifier = Modifier.fillMaxSize().alpha(0.15f)
        )
        
        Row(
            modifier = Modifier.fillMaxSize().padding(48.dp),
            horizontalArrangement = Arrangement.spacedBy(48.dp)
        ) {
            AsyncImage(
                model = movie.posterUrl,
                contentDescription = movie.title,
                contentScale = ContentScale.Crop,
                modifier = Modifier
                    .width(350.dp)
                    .height(500.dp)
                    .clip(PosterShape)
                    .border(2.dp, HorrorColors.HorrorLightGray, PosterShape)
            )
            
            Column(
                modifier = Modifier.fillMaxWidth().padding(vertical = 24.dp).focusGroup(),
                verticalArrangement = Arrangement.spacedBy(24.dp)
            ) {
                Text(
                    text = "${movie.title} (${movie.year})",
                    style = HorrorTypography.DetailTitle,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )
                
                Row(
                    horizontalArrangement = Arrangement.spacedBy(32.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(text = "IMDb: ⭐ ${movie.rating}", style = HorrorTypography.DetailRating)
                    Text(text = movie.runtime, style = HorrorTypography.DetailInfo)
                    Text(
                        text = movie.genre,
                        style = HorrorTypography.DetailGenre,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                        modifier = Modifier.weight(1f)
                    )
                }
                
                Spacer(modifier = Modifier.height(16.dp))
                Text(text = "SINOPSIS", style = HorrorTypography.MovieTitle, color = HorrorColors.HorrorAccent)
                Text(text = movie.plot, style = HorrorTypography.DetailPlot, maxLines = 8, overflow = TextOverflow.Ellipsis)
                Spacer(modifier = Modifier.height(24.dp))
                
                Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                    if (movie.director.isNotEmpty()) {
                        Text(text = "Director: ${movie.director}", style = HorrorTypography.DetailInfo, maxLines = 2, overflow = TextOverflow.Ellipsis)
                    }
                    if (movie.actors.isNotEmpty()) {
                        Text(text = "Actores: ${movie.actors}", style = HorrorTypography.DetailInfo, maxLines = 3, overflow = TextOverflow.Ellipsis)
                    }
                }
                
                Spacer(modifier = Modifier.height(32.dp))
                
                Box(
                    modifier = Modifier
                        .width(PlayButtonWidth)
                        .height(PlayButtonHeight)
                        .graphicsLayer {
                            scaleX = scale
                            scaleY = scale
                        }
                        .clip(PlayButtonShape)
                        .background(playButtonColor)
                        .border(if (isPlayFocused) 4.dp else 2.dp, if (isPlayFocused) Color.White else HorrorColors.HorrorLightGray, PlayButtonShape)
                        .focusRequester(playFocusRequester)
                        .focusable(interactionSource = interactionSource)
                        .onFocusChanged { isPlayFocused = it.isFocused }
                        .clickable(interactionSource = interactionSource, indication = null, onClick = onPlayClick),
                    contentAlignment = Alignment.Center
                ) {
                    Text(text = "▶ VER PELÍCULA", style = HorrorTypography.PlayButton)
                }
            }
        }
    }
}