package com.tt.honeyDue.ui.screens

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.tt.honeyDue.ui.components.HandleErrors
import com.tt.honeyDue.ui.theme.*
import com.tt.honeyDue.viewmodel.ResidenceViewModel
import com.tt.honeyDue.viewmodel.TaskViewModel
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.data.LocalDataManager
import honeydue.composeapp.generated.resources.*
import org.jetbrains.compose.resources.stringResource

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeScreen(
    onNavigateToResidences: () -> Unit,
    onNavigateToTasks: () -> Unit,
    onLogout: () -> Unit,
    viewModel: ResidenceViewModel = viewModel { ResidenceViewModel() },
    taskViewModel: TaskViewModel = viewModel { TaskViewModel() }
) {
    val dataManager = LocalDataManager.current
    val summaryState by viewModel.myResidencesState.collectAsStateWithLifecycle()
    val totalSummary by dataManager.totalSummary.collectAsStateWithLifecycle()
    val myResidences by dataManager.myResidences.collectAsStateWithLifecycle()
    // Fall back to DataManager cache if VM hasn't loaded yet (snapshot tests
    // + first-paint on cached launch both benefit). Screen renders the
    // populated branch whenever data is available regardless of VM state.
    val effectiveSummary: com.tt.honeyDue.models.MyResidencesResponse? =
        (summaryState as? ApiResult.Success)?.data ?: myResidences
    var isRefreshing by remember { mutableStateOf(false) }

    LaunchedEffect(Unit) {
        viewModel.loadMyResidences()
        // Also load tasks to ensure summary can be calculated from kanban data
        taskViewModel.loadTasks()
    }

    // Reset refresh state once the underlying load completes
    LaunchedEffect(summaryState) {
        if (summaryState !is ApiResult.Loading) {
            isRefreshing = false
        }
    }

    // Handle errors for loading summary
    summaryState.HandleErrors(
        onRetry = { viewModel.loadMyResidences() },
        errorTitle = stringResource(Res.string.home_failed_to_load)
    )

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(stringResource(Res.string.app_name), style = MaterialTheme.typography.headlineSmall) },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.background
                ),
                actions = {
                    IconButton(onClick = onLogout) {
                        Icon(
                            Icons.Default.ExitToApp,
                            contentDescription = stringResource(Res.string.home_logout),
                            tint = MaterialTheme.colorScheme.primary
                        )
                    }
                }
            )
        }
    ) { paddingValues ->
        WarmGradientBackground {
            PullToRefreshBox(
                isRefreshing = isRefreshing,
                onRefresh = {
                    isRefreshing = true
                    viewModel.loadMyResidences(forceRefresh = true)
                    taskViewModel.loadTasks(forceRefresh = true)
                },
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues)
            ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .verticalScroll(rememberScrollState())
                    .padding(horizontal = OrganicSpacing.comfortable, vertical = OrganicSpacing.cozy),
                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.generous)
            ) {
                // Personalized Greeting
                Column(
                    modifier = Modifier.padding(vertical = OrganicSpacing.cozy)
                ) {
                    Text(
                        text = stringResource(Res.string.home_welcome),
                        style = MaterialTheme.typography.titleLarge,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Text(
                        text = stringResource(Res.string.home_manage_properties),
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
                // Summary Card — render whenever data is available, not just when VM transitions to Success
                if (effectiveSummary != null) {
                    run {
                        val summary = effectiveSummary
                        OrganicCard(
                            modifier = Modifier.fillMaxWidth(),
                            showBlob = true,
                            blobVariation = 0
                        ) {
                            Column(
                                modifier = Modifier.fillMaxWidth()
                            ) {
                                Row(
                                    verticalAlignment = Alignment.CenterVertically,
                                    horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.cozy)
                                ) {
                                    // Gradient circular icon
                                    OrganicIconContainer(
                                        icon = Icons.Default.Home,
                                        size = 44.dp
                                    )
                                    Column {
                                        Text(
                                            text = stringResource(Res.string.home_overview),
                                            style = MaterialTheme.typography.titleMedium,
                                            color = MaterialTheme.colorScheme.onSurface
                                        )
                                        Text(
                                            text = stringResource(Res.string.home_property_stats),
                                            style = MaterialTheme.typography.bodySmall,
                                            color = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                    }
                                }

                                Spacer(modifier = Modifier.height(OrganicSpacing.generous))

                                Row(
                                    modifier = Modifier.fillMaxWidth(),
                                    horizontalArrangement = Arrangement.SpaceEvenly
                                ) {
                                    OrganicStatPill(
                                        icon = Icons.Default.Home,
                                        value = "${summary.residences.size}",
                                        label = stringResource(Res.string.home_properties),
                                        color = Color(0xFF3B82F6)
                                    )
                                    OrganicDivider(
                                        modifier = Modifier
                                            .height(48.dp)
                                            .width(1.dp),
                                        vertical = true
                                    )
                                    OrganicStatPill(
                                        icon = Icons.Default.Task,
                                        value = "${totalSummary?.totalTasks ?: 0}",
                                        label = stringResource(Res.string.home_total_tasks),
                                        color = Color(0xFF8B5CF6)
                                    )
                                    OrganicDivider(
                                        modifier = Modifier
                                            .height(48.dp)
                                            .width(1.dp),
                                        vertical = true
                                    )
                                    OrganicStatPill(
                                        icon = Icons.Default.Schedule,
                                        value = "${totalSummary?.totalPending ?: 0}",
                                        label = stringResource(Res.string.home_pending),
                                        color = Color(0xFFF59E0B)
                                    )
                                }
                            }
                        }
                    }
                } else if (summaryState is ApiResult.Loading) {
                    OrganicCard(modifier = Modifier.fillMaxWidth()) {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(120.dp),
                            contentAlignment = Alignment.Center
                        ) {
                            CircularProgressIndicator()
                        }
                    }
                }
                // When state is Idle with no data, or Error, omit the card —
                // the NavigationCards below still render.

                // Residences Card
                NavigationCard(
                    title = stringResource(Res.string.home_properties),
                    subtitle = stringResource(Res.string.home_manage_residences),
                    icon = Icons.Default.Home,
                    iconColor = Color(0xFF3B82F6),
                    onClick = onNavigateToResidences
                )

                // Tasks Card
                NavigationCard(
                    title = stringResource(Res.string.home_tasks),
                    subtitle = stringResource(Res.string.home_view_manage_tasks),
                    icon = Icons.Default.CheckCircle,
                    iconColor = Color(0xFF10B981),
                    onClick = onNavigateToTasks
                )
            }
            }
        }
    }
}

@Composable
private fun NavigationCard(
    title: String,
    subtitle: String,
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    iconColor: Color,
    onClick: () -> Unit
) {
    OrganicCard(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onClick() },
        showBlob = true,
        blobVariation = 1
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.comfortable)
        ) {
            // Gradient circular icon
            OrganicIconContainer(
                icon = icon,
                size = 56.dp,
                iconColor = iconColor
            )

            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = title,
                    style = MaterialTheme.typography.titleMedium,
                    color = MaterialTheme.colorScheme.onSurface
                )
                Spacer(modifier = Modifier.height(OrganicSpacing.minimal))
                Text(
                    text = subtitle,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }

            Icon(
                Icons.Default.KeyboardArrowRight,
                contentDescription = null, // decorative
                tint = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}
