package eu.gaudian.translator.view.home

import android.content.Context
import androidx.compose.foundation.background
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.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AddCircle
import androidx.compose.material.icons.filled.ChevronRight
import androidx.compose.material.icons.filled.LocalFireDepartment
import androidx.compose.material.icons.filled.Psychology
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.navigation.NavHostController
import eu.gaudian.translator.R
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.NavigationRoutes
import eu.gaudian.translator.view.composable.AppCard
import eu.gaudian.translator.view.composable.Screen
import eu.gaudian.translator.view.settings.SettingsRoutes
import eu.gaudian.translator.view.vocabulary.widgets.WeeklyActivityChartWidget
import eu.gaudian.translator.viewmodel.ProgressViewModel

@Composable
fun HomeScreen(
    navController: NavHostController,
    modifier: Modifier = Modifier
) {
    val activity = LocalContext.current.findActivity()
    val viewModel: ProgressViewModel = hiltViewModel(activity)
    val streak by viewModel.streak.collectAsState()
    val dailyGoal by viewModel.dailyGoal.collectAsState()
    val todayCompletedCount by viewModel.todayCompletedCount.collectAsState()

    // Calculate daily goal progress
    val progress = if (dailyGoal > 0) {
        (todayCompletedCount.toFloat() / dailyGoal).coerceIn(0f, 1f)
    } else 0f

    // A Box with TopCenter alignment keeps the UI centered on wide screens (tablets/foldables)
    Box(
        modifier = modifier.fillMaxSize(),
        contentAlignment = Alignment.TopCenter
    ) {
        LazyColumn(
            modifier = Modifier
                .widthIn(max = 700.dp) // Prevents extreme stretching on tablets
                .fillMaxSize()
                .padding(horizontal = 16.dp, vertical = 0.dp),
            verticalArrangement = Arrangement.spacedBy(15.dp)
        ) {
            item { Spacer(modifier = Modifier.height(16.dp)) }
            item { TopProfileSection(
                navController = navController,
                context =  LocalContext.current
            ) }
            item {
                StreakAndGoalSection(
                    streak = streak,
                    progress = progress,
                    progressTitle = "$todayCompletedCount / $dailyGoal",
                    onGoalClick = { navController.navigate(SettingsRoutes.VOCABULARY_OPTIONS) },
                    onStreakClick = { navController.navigate(NavigationRoutes.STATS_VOCABULARY_HEATMAP) }
                )
            }
            item {
                //TODO replace with actual implementation
                @Suppress("HardCodedStringLiteral")
                ActionCard(
                    title = "Daily Review",
                    subtitle = "42 words need attention",
                    icon = Icons.Default.Psychology,
                    contentColor = MaterialTheme.colorScheme.onPrimary
                )
            }
            item {
                ActionCard(
                    title = stringResource(R.string.label_new_words),
                    subtitle = stringResource(R.string.desc_expand_your_vocabulary),
                    icon = Icons.Default.AddCircle,
                    contentColor = MaterialTheme.colorScheme.onSurfaceVariant,
                    onClick = { navController.navigate(NavigationRoutes.NEW_WORD) }
                )
            }
            item { WeeklyProgressSection(navController = navController) }
            item { BottomStatsSection(navController = navController) }

            // Bottom padding for edge-to-edge screens
            item { Spacer(modifier = Modifier.height(24.dp)) }
        }
    }
}

@Composable
fun TopProfileSection(navController: NavHostController, context: Context) {
    
    val motivationalPhrases = remember {
        context.resources.getStringArray(R.array.motivational_phrases)
    }
    val randomPhrase = remember { motivationalPhrases.random() }

    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier
            .fillMaxWidth()
            .padding(8.dp)
    ) {

        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = randomPhrase,
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.SemiBold,
                color = MaterialTheme.colorScheme.onSurface
            )
        }

        IconButton(
            onClick = { navController.navigate(Screen.Settings.route) },
            modifier = Modifier
                .clip(CircleShape)
                .background(MaterialTheme.colorScheme.surfaceVariant)
        ) {
            Icon(
                imageVector = Icons.Default.Settings,
                contentDescription = stringResource(R.string.label_settings),
                tint = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}

@Composable
fun StreakAndGoalSection(
    streak: Int,
    progress: Float,
    progressTitle: String,
    onGoalClick: () -> Unit,
    onStreakClick: () -> Unit
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        // Streak Card
        StatCard(
            modifier = Modifier.weight(1f),
            icon = Icons.Default.LocalFireDepartment,
            title = stringResource(R.string.label_2d_days, streak),
            subtitle = stringResource(R.string.label_current_streak).uppercase(),
            onClick = onStreakClick
        )
        // Goal Card
        GoalCard(
            modifier = Modifier.weight(1f),
            progress = progress,
            title = progressTitle,
            subtitle = stringResource(R.string.label_daily_goal).uppercase(),
            onClick = onGoalClick
        )
    }
}

@Composable
fun StatCard(
    modifier: Modifier = Modifier,
    icon: ImageVector,
    title: String,
    subtitle: String,
    onClick: (() -> Unit)? = null
) {
    if (onClick != null) {
        AppCard(
            modifier = modifier,
            onClick = onClick
        ) {
            StatCardContent(icon = icon, title = title, subtitle = subtitle)
        }
    } else {
        AppCard(
            modifier = modifier,
        ) {
            StatCardContent(icon = icon, title = title, subtitle = subtitle)
        }
    }
}

@Composable
private fun StatCardContent(
    icon: ImageVector,
    title: String,
    subtitle: String
) {
    Column(
        modifier = Modifier
            .padding(20.dp)
            .height(120.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null,
            tint = MaterialTheme.colorScheme.primary,
            modifier = Modifier.size(32.dp)
        )
        Spacer(modifier = Modifier.height(12.dp))
        Text(text = title, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)
        Spacer(modifier = Modifier.height(4.dp))
        Text(text = subtitle, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f))
    }
}

@Composable
fun GoalCard(
    modifier: Modifier = Modifier,
    progress: Float,
    title: String,
    subtitle: String,
    onClick: (() -> Unit)? = null
) {
    if (onClick != null) {
        AppCard(
            modifier = modifier,
            onClick = onClick
        ) {
            GoalCardContent(progress = progress, title = title, subtitle = subtitle)
        }
    } else {
        AppCard(
            modifier = modifier,
        ) {
            GoalCardContent(progress = progress, title = title, subtitle = subtitle)
        }
    }
}

@Composable
private fun GoalCardContent(
    progress: Float,
    title: String,
    subtitle: String
) {
    Column(
        modifier = Modifier
            .padding(20.dp)
            .height(120.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Box(contentAlignment = Alignment.Center) {
            CircularProgressIndicator(
                progress = { progress },
                modifier = Modifier.size(48.dp),
                strokeWidth = 4.dp,
                color = MaterialTheme.colorScheme.primary,
                trackColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.1f)
            )
            Text(text = "${(progress * 100).toInt()}%", style = MaterialTheme.typography.labelSmall, fontWeight = FontWeight.Bold)
        }
        Spacer(modifier = Modifier.height(12.dp))
        Text(text = title, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)
        Spacer(modifier = Modifier.height(4.dp))
        Text(text = subtitle, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f))
    }
}

@Composable
fun ActionCard(
    title: String,
    subtitle: String,
    icon: ImageVector,
    contentColor: Color,
    onClick: (() -> Unit)? = null
) {
    val cardContent: @Composable () -> Unit = {
        Row(
            modifier = Modifier.padding(20.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                imageVector = icon,
                contentDescription = null,
                modifier = Modifier.size(40.dp)
            )
            Spacer(modifier = Modifier.width(16.dp))
            Column(modifier = Modifier.weight(1f)) {
                Text(text = title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
                Text(text = subtitle, style = MaterialTheme.typography.bodyMedium, color = contentColor.copy(alpha = 0.8f))
            }
            Icon(
                imageVector = Icons.Default.ChevronRight,
                contentDescription = stringResource(R.string.cd_go),
                modifier = Modifier.size(24.dp)
            )
        }
    }

    if (onClick != null) {
        AppCard(
            modifier = Modifier.fillMaxWidth(),
            onClick = onClick
        ) {
            cardContent()
        }
    } else {
        AppCard(
            modifier = Modifier.fillMaxWidth(),
        ) {
            cardContent()
        }
    }
}

@Composable
fun WeeklyProgressSection(
    navController: NavHostController,
    modifier: Modifier = Modifier
) {
    val activity = LocalContext.current.findActivity()
    val viewModel: ProgressViewModel = hiltViewModel(activity)
    val weeklyActivityStats by viewModel.weeklyActivityStats.collectAsState()

    Column(modifier = modifier) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(text = stringResource(R.string.label_weekly_progress), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
            TextButton(onClick = { navController.navigate(NavigationRoutes.STATS_VOCABULARY_HEATMAP) }) {
                Text(stringResource(R.string.label_see_history))
            }
        }

        Spacer(modifier = Modifier.height(8.dp))

        AppCard(
            modifier = Modifier.fillMaxWidth(),
            onClick = { navController.navigate(NavigationRoutes.STATS_VOCABULARY_HEATMAP) }
        ) {
            if (weeklyActivityStats.isEmpty()) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp),
                    verticalArrangement = Arrangement.Center,
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = stringResource(R.string.text_desc_no_activity_data_available),
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            } else {
                WeeklyActivityChartWidget(weeklyStats = weeklyActivityStats)
            }
        }
    }
}

@Composable
fun BottomStatsSection(
    navController: NavHostController
) {
    val activity = LocalContext.current.findActivity()
    val viewModel: ProgressViewModel = hiltViewModel(activity)
    val totalWords by viewModel.totalWords.collectAsState()
    val learnedWords by viewModel.totalWordsCompleted.collectAsState()

    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        // Total Words
        AppCard(
            modifier = Modifier.weight(1f),
            onClick = { navController.navigate(Screen.Library.route) }
        ) {
            Column(modifier = Modifier.padding(20.dp)) {
                Text(text = stringResource(R.string.label_total_words).uppercase(), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f))
                Spacer(modifier = Modifier.height(8.dp))
                Text(text = totalWords.toString(), style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
                Spacer(modifier = Modifier.height(8.dp))
            }
        }

        // Learned
        AppCard(
            modifier = Modifier.weight(1f),
            onClick = { navController.navigate(NavigationRoutes.STATS_LANGUAGE_PROGRESS) }
        ) {
            Column(modifier = Modifier.padding(20.dp)) {
                Text(text = "LEARNED", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f))
                Spacer(modifier = Modifier.height(8.dp))
                Text(text = learnedWords.toString(), style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
                Spacer(modifier = Modifier.height(8.dp))
            }
        }
    }
}
