package com.horrortv.app.presentation.home

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
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.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
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.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.res.painterResource
import androidx.compose.ui.unit.dp
import com.horrortv.app.domain.model.Movie
import com.horrortv.app.domain.model.MovieCategory
import com.horrortv.app.presentation.common.TvErrorDisplay
import com.horrortv.app.presentation.theme.HorrorColors
import com.horrortv.app.presentation.theme.HorrorTypography

@Composable
fun HomeScreen(
    viewModel: HomeViewModel,
    onNavigateToSearch: () -> Unit,
    onNavigateToDetail: (String) -> Unit,
    onExit: () -> Unit = {},
    modifier: Modifier = Modifier
) {
    var showExitDialog by remember { mutableStateOf(false) }
    
    BackHandler(enabled = true) {
        showExitDialog = true
    }
    
    val uiState by viewModel.uiState.collectAsState()
    val firstCardFocusRequester = remember { FocusRequester() }
    
    var hasRequestedInitialFocus by remember { mutableStateOf(false) }
    
    LaunchedEffect(uiState.categories.isNotEmpty()) {
        if (uiState.categories.isNotEmpty() && uiState.categories.first().movies.isNotEmpty() && !hasRequestedInitialFocus) {
            kotlinx.coroutines.delay(800)
            try {
                firstCardFocusRequester.requestFocus()
                hasRequestedInitialFocus = true
            } catch (e: IllegalStateException) {
            }
        }
    }
    
    val onMovieClick = remember(onNavigateToDetail) { 
        { movie: Movie -> onNavigateToDetail(movie.imdbId) }
    }
    
    Box(
        modifier = modifier.fillMaxSize().background(HorrorColors.HorrorBlack)
    ) {
        Column(modifier = Modifier.fillMaxSize()) {
            HomeHeader(onSearchClick = onNavigateToSearch)
            
            when {
                uiState.isLoading && uiState.categories.isEmpty() -> CategoryPlaceholderList()
                uiState.error != null -> {
                    val error = uiState.error
                    if (error != null) {
                        TvErrorDisplay(error = error, onRetry = { viewModel.retry() })
                    }
                }
                uiState.categories.isEmpty() -> EmptyState()
                else -> CategoriesList(
                    categories = uiState.categories,
                    onMovieClick = onMovieClick,
                    firstCardFocusRequester = firstCardFocusRequester
                )
            }
        }
        
        if (showExitDialog) {
            ExitConfirmationDialog(
                onConfirm = { showExitDialog = false; onExit() },
                onDismiss = { showExitDialog = false }
            )
        }
    }
}

@Composable
private fun CategoryPlaceholderList() {
    Column(
        modifier = Modifier.padding(vertical = 16.dp),
        verticalArrangement = Arrangement.spacedBy(4.dp)
    ) {
        repeat(3) { CategoryPlaceholderRow() }
    }
}

@Composable
private fun EmptyState() {
    Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
        Text(text = "No hay películas disponibles", style = HorrorTypography.DetailPlot)
    }
}

@Composable
private fun CategoriesList(
    categories: List<MovieCategory>,
    onMovieClick: (Movie) -> Unit,
    firstCardFocusRequester: FocusRequester
) {
    LazyColumn(
        contentPadding = PaddingValues(vertical = 8.dp),
        verticalArrangement = Arrangement.spacedBy(0.dp)
    ) {
        itemsIndexed(
            items = categories,
            key = { _, category -> category.name }
        ) { index, category ->
            HorrorRow(
                category = category,
                onMovieClick = onMovieClick,
                isFirstRow = index == 0,
                focusRequester = if (index == 0) firstCardFocusRequester else null
            )
        }
    }
}

@Composable
fun HomeHeader(onSearchClick: () -> Unit, modifier: Modifier = Modifier) {
    var isSearchFocused by remember { mutableStateOf(false) }
    val searchFocusRequester = remember { FocusRequester() }
    val interactionSource = remember { MutableInteractionSource() }
    
    Row(
        modifier = modifier.fillMaxWidth().padding(horizontal = 48.dp, vertical = 16.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(text = "HORROR TV", style = HorrorTypography.DetailTitle, color = HorrorColors.HorrorRed)
        
        Box(
            modifier = Modifier
                .size(48.dp)
                .clip(RoundedCornerShape(8.dp))
                .background(if (isSearchFocused) HorrorColors.HorrorGray else Color.Transparent)
                .border(if (isSearchFocused) 2.dp else 0.dp, HorrorColors.HorrorRed, RoundedCornerShape(8.dp))
                .focusRequester(searchFocusRequester)
                .focusable(interactionSource = interactionSource)
                .onFocusChanged { isSearchFocused = it.isFocused }
                .clickable(interactionSource = interactionSource, indication = null, onClick = onSearchClick),
            contentAlignment = Alignment.Center
        ) {
            Icon(
                painter = painterResource(id = android.R.drawable.ic_menu_search),
                contentDescription = "Buscar",
                tint = HorrorColors.HorrorWhite,
                modifier = Modifier.size(32.dp)
            )
        }
    }
}

@Composable
fun CategoryPlaceholderRow(modifier: Modifier = Modifier) {
    Column(modifier = modifier.fillMaxWidth().padding(vertical = 8.dp)) {
        Box(
            modifier = Modifier.width(200.dp).height(20.dp)
                .padding(horizontal = 48.dp).clip(RoundedCornerShape(4.dp))
                .background(HorrorColors.HorrorGray)
        )
        Spacer(modifier = Modifier.height(8.dp))
        Row(
            modifier = Modifier.padding(horizontal = 48.dp),
            horizontalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            repeat(6) {
                Box(
                    modifier = Modifier.width(180.dp).height(270.dp)
                        .clip(RoundedCornerShape(8.dp)).background(HorrorColors.HorrorGray)
                )
            }
        }
    }
}

@Composable
fun ExitConfirmationDialog(onConfirm: () -> Unit, onDismiss: () -> Unit) {
    var isConfirmFocused by remember { mutableStateOf(false) }
    val confirmFocusRequester = remember { FocusRequester() }
    val confirmInteractionSource = remember { MutableInteractionSource() }
    
    Box(
        modifier = Modifier.fillMaxSize().background(HorrorColors.HorrorBlack.copy(alpha = 0.85f)),
        contentAlignment = Alignment.Center
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(24.dp)
        ) {
            Text(text = "¿Salir de Horror TV?", style = HorrorTypography.DetailTitle, color = HorrorColors.HorrorWhite)
            Row(horizontalArrangement = Arrangement.spacedBy(32.dp)) {
                TextButton(onClick = onDismiss) { Text("No", color = HorrorColors.HorrorWhite) }
                Box(
                    modifier = Modifier
                        .width(200.dp).height(56.dp)
                        .clip(RoundedCornerShape(8.dp))
                        .background(if (isConfirmFocused) HorrorColors.HorrorAccent else HorrorColors.HorrorRed)
                        .border(if (isConfirmFocused) 3.dp else 1.dp, if (isConfirmFocused) Color.White else HorrorColors.HorrorLightGray, RoundedCornerShape(8.dp))
                        .focusRequester(confirmFocusRequester)
                        .focusable(interactionSource = confirmInteractionSource)
                        .onFocusChanged { isConfirmFocused = it.isFocused }
                        .clickable(interactionSource = confirmInteractionSource, indication = null, onClick = onConfirm),
                    contentAlignment = Alignment.Center
                ) {
                    Text("Sí, salir", style = HorrorTypography.PlayButton, color = HorrorColors.HorrorWhite)
                }
            }
        }
    }
}

@Composable
private fun TextButton(onClick: () -> Unit, content: @Composable () -> Unit) {
    var isFocused by remember { mutableStateOf(false) }
    val focusRequester = remember { FocusRequester() }
    val interactionSource = remember { MutableInteractionSource() }
    
    Box(
        modifier = Modifier
            .width(100.dp).height(56.dp)
            .clip(RoundedCornerShape(8.dp))
            .background(if (isFocused) HorrorColors.HorrorGray else Color.Transparent)
            .border(if (isFocused) 2.dp else 0.dp, HorrorColors.HorrorWhite, RoundedCornerShape(8.dp))
            .focusRequester(focusRequester)
            .focusable(interactionSource = interactionSource)
            .onFocusChanged { isFocused = it.isFocused }
            .clickable(interactionSource = interactionSource, indication = null, onClick = onClick),
        contentAlignment = Alignment.Center
    ) {
        content()
    }
}