package app.closer.ui.outcomes

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
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.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.TrendingUp
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import app.closer.ui.components.CloserHeartLoader
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import app.closer.domain.model.Outcome
import app.closer.domain.model.OutcomeDay
import app.closer.domain.model.OutcomeScores
import app.closer.ui.components.ErrorState
import app.closer.ui.settings.SettingsBackgroundBrush
import app.closer.ui.settings.SettingsInk
import app.closer.ui.settings.SettingsMuted
import app.closer.ui.settings.SettingsPrimaryDeep
import app.closer.ui.settings.SettingsSoft

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun YourProgressScreen(
    onBack: () -> Unit,
    viewModel: YourProgressViewModel = hiltViewModel()
) {
    val state by viewModel.uiState.collectAsState()

    LaunchedEffect(Unit) { viewModel.load() }

    Scaffold(
        containerColor = Color.Transparent,
        modifier = Modifier.background(SettingsBackgroundBrush),
        topBar = {
            TopAppBar(
                title = { Text("Your Progress", color = SettingsInk) },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(
                            Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "Back",
                            tint = SettingsInk
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent)
            )
        }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .safeDrawingPadding()
                .navigationBarsPadding()
                .verticalScroll(rememberScrollState())
                .padding(padding)
                .padding(horizontal = 20.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            Spacer(Modifier.height(8.dp))

            when {
                state.isLoading -> {
                    Column(
                        modifier = Modifier.fillMaxSize(),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Center
                    ) {
                        CloserHeartLoader()
                    }
                }
                state.error != null -> {
                    ErrorState(
                        title = "Couldn’t load progress",
                        message = state.error ?: "",
                        retryLabel = "Retry",
                        onRetry = viewModel::load
                    )
                }
                else -> {
                    ProgressHeader(state.baseline)
                    state.baseline?.let { baseline ->
                        state.latest?.let { latest ->
                            DeltaCard(baseline = baseline, latest = latest)
                        }
                    }
                    MilestoneList(state.outcomes)
                }
            }

            Spacer(Modifier.height(16.dp))
        }
    }
}

@Composable
private fun ProgressHeader(baseline: Outcome?) {
    val subtitle = if (baseline == null) {
        "Submit your first check-in to start tracking how your relationship feels over time."
    } else {
        "You’ve started tracking how your relationship feels. Check back at 30, 60, and 90 days to see what changes."
    }

    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(16.dp),
        colors = CardDefaults.cardColors(containerColor = SettingsSoft)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(20.dp),
            horizontalArrangement = Arrangement.spacedBy(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                imageVector = Icons.AutoMirrored.Filled.TrendingUp,
                contentDescription = null,
                modifier = Modifier.size(40.dp),
                tint = SettingsPrimaryDeep
            )
            Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
                Text(
                    text = if (baseline == null) "No baseline yet" else "Baseline recorded",
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.SemiBold,
                    color = SettingsInk
                )
                Text(
                    text = subtitle,
                    style = MaterialTheme.typography.bodyMedium,
                    color = SettingsMuted
                )
            }
        }
    }
}

@Composable
private fun DeltaCard(baseline: Outcome, latest: Outcome) {
    val baselineScores = baseline.baseline ?: return
    val latestScores = latest.scores ?: return
    val delta = latest.delta ?: run {
        OutcomeScores(
            connection = latestScores.connection - baselineScores.connection,
            communication = latestScores.communication - baselineScores.communication,
            intimacy = latestScores.intimacy - baselineScores.intimacy,
            happiness = latestScores.happiness - baselineScores.happiness
        )
    }

    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(16.dp),
        colors = CardDefaults.cardColors(containerColor = SettingsSoft)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(20.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            Text(
                text = "Change since baseline",
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.SemiBold,
                color = SettingsInk
            )
            DeltaRow(label = "Connected", delta = delta.connection)
            DeltaRow(label = "Communication", delta = delta.communication)
            DeltaRow(label = "Intimacy", delta = delta.intimacy)
            DeltaRow(label = "Happiness", delta = delta.happiness)
        }
    }
}

@Composable
private fun DeltaRow(label: String, delta: Int) {
    val color = when {
        delta > 0 -> SettingsPrimaryDeep
        delta < 0 -> Color(0xFFB00020)
        else -> SettingsMuted
    }
    val sign = when {
        delta > 0 -> "+"
        else -> ""
    }
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(text = label, style = MaterialTheme.typography.bodyLarge, color = SettingsInk)
        Text(
            text = "$sign$delta",
            style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold),
            color = color,
            textAlign = TextAlign.End
        )
    }
}

@Composable
private fun MilestoneList(outcomes: List<Outcome>) {
    Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
        Text(
            text = "Milestones",
            style = MaterialTheme.typography.titleMedium,
            fontWeight = FontWeight.SemiBold,
            color = SettingsInk
        )
        OutcomeDay.entries.forEach { day ->
            val outcome = outcomes.firstOrNull { it.dayKey == day.key }
            MilestoneRow(day = day, outcome = outcome)
        }
    }
}

@Composable
private fun MilestoneRow(day: OutcomeDay, outcome: Outcome?) {
    val (title, status) = when (day) {
        OutcomeDay.BASELINE -> "Baseline" to if (outcome != null) "Recorded" else "Not yet"
        OutcomeDay.DAY_30 -> "30-day check-in" to if (outcome != null) "Recorded" else "Not yet"
        OutcomeDay.DAY_60 -> "60-day check-in" to if (outcome != null) "Recorded" else "Not yet"
        OutcomeDay.DAY_90 -> "90-day check-in" to if (outcome != null) "Recorded" else "Not yet"
    }
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(text = title, style = MaterialTheme.typography.bodyLarge, color = SettingsInk)
        Text(
            text = status,
            style = MaterialTheme.typography.bodyMedium,
            color = if (outcome != null) SettingsPrimaryDeep else SettingsMuted
        )
    }
}
