package com.horrortv.app.presentation.search

import android.net.Uri
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.PaddingValues
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.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.relocation.BringIntoViewRequester
import androidx.compose.foundation.relocation.bringIntoViewRequester
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
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.rememberCoroutineScope
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.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.SolidColor
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.horrortv.app.domain.model.AppError
import com.horrortv.app.domain.model.Movie
import com.horrortv.app.presentation.common.PosterImage
import com.horrortv.app.util.PosterSize
import com.horrortv.app.presentation.common.TvErrorDisplay
import com.horrortv.app.presentation.theme.HorrorColors
import com.horrortv.app.presentation.theme.HorrorTypography
import androidx.compose.ui.graphics.graphicsLayer
import kotlinx.coroutines.launch

private val CardShape = RoundedCornerShape(8.dp)
private val SearchFieldShape = RoundedCornerShape(8.dp)

@Composable
fun SearchScreen(
    viewModel: SearchViewModel,
    onNavigateBack: () -> Unit = {},
    onNavigateToDetail: (String) -> Unit = {},
    modifier: Modifier = Modifier
) {
    val uiState by viewModel.uiState.collectAsState()
    var searchQuery by remember { mutableStateOf("") }
    val searchFieldFocusRequester = remember { FocusRequester() }
    
    LaunchedEffect(Unit) { searchFieldFocusRequester.requestFocus() }
    
    val movies = uiState.movies
    val isLoading = uiState.isLoading
    val error = uiState.error
    val directMovie = uiState.directMovie
    
    Column(modifier = modifier.fillMaxSize().background(HorrorColors.HorrorBlack)) {
        SearchHeader(
            query = searchQuery,
            onQueryChange = { newQuery ->
                searchQuery = newQuery
                viewModel.updateQuery(newQuery)
            },
            onBackClick = onNavigateBack,
            focusRequester = searchFieldFocusRequester
        )
        
        Box(modifier = Modifier.fillMaxSize()) {
            when {
                isLoading -> SearchLoadingIndicator()
                error != null -> TvErrorDisplay(error = error, onRetry = { viewModel.retry() })
                directMovie != null -> DirectMovieResult(
                    movie = directMovie,
                    onPlayClick = { onNavigateToDetail(directMovie.imdbId) }
                )
                searchQuery.isEmpty() -> SearchInitialState()
                movies.isEmpty() -> SearchNoResultsState()
                else -> SearchResultsGrid(
                    movies = movies,
                    onMovieClick = { movie -> onNavigateToDetail(movie.imdbId) }
                )
            }
        }
    }
}

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

@Composable
private fun SearchInitialState() {
    Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
        Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(16.dp)) {
            Icon(painter = painterResource(id = android.R.drawable.ic_menu_search), contentDescription = null, tint = HorrorColors.HorrorLightGray, modifier = Modifier.size(64.dp))
            Text(text = "Busca películas por nombre o IMDB ID", style = HorrorTypography.DetailPlot, color = HorrorColors.HorrorLightGray)
            Text(text = "Ejemplo: \"Scream\" o \"tt11245972\"", style = HorrorTypography.DetailInfo, color = HorrorColors.HorrorGray)
        }
    }
}

@Composable
private fun SearchNoResultsState() {
    Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
        Text(text = "No se encontraron resultados", style = HorrorTypography.DetailPlot, color = HorrorColors.HorrorLightGray)
    }
}

@Composable
private fun SearchResultsGrid(
    movies: List<Movie>,
    onMovieClick: (Movie) -> Unit
) {
    LazyVerticalGrid(
        columns = GridCells.Fixed(5),
        contentPadding = PaddingValues(48.dp),
        horizontalArrangement = Arrangement.spacedBy(24.dp),
        verticalArrangement = Arrangement.spacedBy(32.dp),
        modifier = Modifier.focusGroup()
    ) {
        items(items = movies, key = { it.imdbId }) { movie ->
            SearchResultCard(movie = movie, onClick = { onMovieClick(movie) })
        }
    }
}

@Composable
fun SearchHeader(
    query: String,
    onQueryChange: (String) -> Unit,
    onBackClick: () -> Unit,
    focusRequester: FocusRequester,
    modifier: Modifier = Modifier
) {
    var isTextFieldFocused by remember { mutableStateOf(false) }
    var isBackFocused by remember { mutableStateOf(false) }
    val backFocusRequester = remember { FocusRequester() }
    val textFieldInteractionSource = remember { MutableInteractionSource() }
    val backInteractionSource = remember { MutableInteractionSource() }
    
    val borderColor = if (isTextFieldFocused) HorrorColors.HorrorRed else HorrorColors.HorrorLightGray
    
    Row(
        modifier = modifier.fillMaxWidth().padding(horizontal = 48.dp, vertical = 24.dp),
        horizontalArrangement = Arrangement.spacedBy(24.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Box(
            modifier = Modifier
                .size(48.dp)
                .clip(RoundedCornerShape(8.dp))
                .background(if (isBackFocused) HorrorColors.HorrorGray else Color.Transparent)
                .border(if (isBackFocused) 2.dp else 0.dp, HorrorColors.HorrorRed, RoundedCornerShape(8.dp))
                .focusRequester(backFocusRequester)
                .focusable(interactionSource = backInteractionSource)
                .onFocusChanged { isBackFocused = it.isFocused }
                .clickable(interactionSource = backInteractionSource, indication = null, onClick = onBackClick),
            contentAlignment = Alignment.Center
        ) {
            Icon(painter = painterResource(id = android.R.drawable.ic_menu_close_clear_cancel), contentDescription = "Cerrar", tint = HorrorColors.HorrorWhite, modifier = Modifier.size(32.dp))
        }
        
        Box(
            modifier = Modifier
                .weight(1f)
                .height(56.dp)
                .clip(SearchFieldShape)
                .background(HorrorColors.HorrorGray)
                .border(2.dp, borderColor, SearchFieldShape)
                .padding(horizontal = 16.dp),
            contentAlignment = Alignment.CenterStart
        ) {
            if (query.isEmpty() && !isTextFieldFocused) {
                Text(text = "Buscar por nombre o IMDB ID", style = HorrorTypography.SearchHint)
            }
            
            BasicTextField(
                value = query,
                onValueChange = onQueryChange,
                textStyle = HorrorTypography.DetailPlot.copy(color = HorrorColors.HorrorWhite),
                cursorBrush = SolidColor(HorrorColors.HorrorRed),
                singleLine = true,
                modifier = Modifier
                    .fillMaxWidth()
                    .focusRequester(focusRequester)
                    .focusable(interactionSource = textFieldInteractionSource)
                    .onFocusChanged { isTextFieldFocused = it.isFocused }
            )
        }
        
        Icon(painter = painterResource(id = android.R.drawable.ic_menu_search), contentDescription = "Buscar", tint = HorrorColors.HorrorWhite, modifier = Modifier.size(32.dp))
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun SearchResultCard(
    movie: Movie,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    var isFocused by remember { mutableStateOf(false) }
    val focusRequester = remember { FocusRequester() }
    val bringIntoViewRequester = remember { BringIntoViewRequester() }
    val coroutineScope = rememberCoroutineScope()
    val interactionSource = remember { MutableInteractionSource() }
    
    val borderW = if (isFocused) 6.dp else 1.dp
    val borderC = if (isFocused) HorrorColors.HorrorRed else HorrorColors.HorrorLightGray
    val scale = if (isFocused) 1.08f else 1.0f
    
    Column(modifier = modifier.width(180.dp)) {
        Box(
            modifier = Modifier
                .width(180.dp)
                .height(270.dp)
                .graphicsLayer { scaleX = scale; scaleY = scale }
                .bringIntoViewRequester(bringIntoViewRequester)
                .clip(CardShape)
                .background(HorrorColors.HorrorGray)
                .border(borderW, borderC, CardShape)
                .focusRequester(focusRequester)
                .focusable(interactionSource = interactionSource)
                .onFocusChanged {
                    isFocused = it.isFocused
                    if (it.isFocused) {
                        coroutineScope.launch { bringIntoViewRequester.bringIntoView() }
                    }
                }
                .clickable(interactionSource = interactionSource, indication = null, onClick = onClick)
        ) {
            PosterImage(
                url = movie.posterUrl,
                contentDescription = movie.title,
                size = PosterSize.CARD,
                contentScale = ContentScale.Crop,
                shape = CardShape,
                modifier = Modifier.fillMaxSize()
            )
            
            if (isFocused) {
                Box(modifier = Modifier.fillMaxSize().background(Color.Red.copy(alpha = 0.2f)))
            }
        }
        
        Spacer(modifier = Modifier.height(8.dp))
        Text(text = movie.title, style = HorrorTypography.MovieTitle, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(horizontal = 4.dp))
        Text(text = movie.year, style = HorrorTypography.MovieYear, modifier = Modifier.padding(horizontal = 4.dp))
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun DirectMovieResult(
    movie: Movie,
    onPlayClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    var isPlayFocused by remember { mutableStateOf(false) }
    val playFocusRequester = remember { FocusRequester() }
    val interactionSource = remember { MutableInteractionSource() }
    
    LaunchedEffect(Unit) { playFocusRequester.requestFocus() }
    
    val playButtonColor = if (isPlayFocused) HorrorColors.HorrorAccent else HorrorColors.HorrorRed
    
    Column(
        modifier = modifier.fillMaxSize().padding(48.dp).focusGroup(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(32.dp)
    ) {
        Text(text = "RESULTADO ENCONTRADO", style = HorrorTypography.CategoryTitle, color = HorrorColors.HorrorAccent)
        
        Row(horizontalArrangement = Arrangement.spacedBy(48.dp), modifier = Modifier.fillMaxWidth(0.7f)) {
            PosterImage(
                url = movie.posterUrl,
                contentDescription = movie.title,
                size = PosterSize.DETAIL,
                contentScale = ContentScale.Crop,
                shape = RoundedCornerShape(12.dp),
                modifier = Modifier.width(300.dp).height(450.dp).border(2.dp, HorrorColors.HorrorRed, RoundedCornerShape(12.dp))
            )
            
            Column(verticalArrangement = Arrangement.spacedBy(16.dp), modifier = Modifier.weight(1f)) {
                Text(text = "${movie.title} (${movie.year})", style = HorrorTypography.DetailTitle)
                Text(text = "IMDb: ⭐ ${movie.rating}", style = HorrorTypography.DetailRating)
                Text(text = movie.genre, style = HorrorTypography.DetailGenre)
                Text(text = movie.plot, style = HorrorTypography.DetailPlot, maxLines = 6, overflow = TextOverflow.Ellipsis)
                Spacer(modifier = Modifier.height(24.dp))
                
                Box(
                    modifier = Modifier
                        .width(350.dp)
                        .height(60.dp)
                        .clip(RoundedCornerShape(12.dp))
                        .background(playButtonColor)
                        .border(if (isPlayFocused) 4.dp else 2.dp, if (isPlayFocused) Color.White else HorrorColors.HorrorLightGray, RoundedCornerShape(12.dp))
                        .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)
                }
            }
        }
    }
}