package com.jttools.datacontrol.ui.dashboard

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.padding
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.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.jttools.datacontrol.R
import com.jttools.datacontrol.data.DataState
import com.jttools.datacontrol.service.DataMonitorService
import com.jttools.datacontrol.ui.SystemActions
import com.jttools.datacontrol.ui.components.PasswordPromptDialog
import com.jttools.datacontrol.ui.theme.StateCut
import com.jttools.datacontrol.ui.theme.StateOk
import com.jttools.datacontrol.ui.theme.StateWarning
import com.jttools.datacontrol.ui.theme.StateWifi
import java.time.format.DateTimeFormatter
import java.util.Locale
import kotlinx.coroutines.launch

@Composable
fun DashboardScreen(systemActions: SystemActions) {
    val context = androidx.compose.ui.platform.LocalContext.current
    val viewModel: DashboardViewModel = hiltViewModel()
    val settings by viewModel.settings.collectAsStateWithLifecycle()
    val snapshot by viewModel.snapshot.collectAsStateWithLifecycle()
    var showResetDialog by remember { mutableStateOf(false) }
    var showDisablePasswordDialog by remember { mutableStateOf(false) }
    var disablePasswordError by remember { mutableStateOf(false) }
    val scope = rememberCoroutineScope()

    val stateColor = when {
        !snapshot.serviceRunning -> Color.Gray
        snapshot.dataState == DataState.OK -> StateOk
        snapshot.dataState == DataState.WARNING -> StateWarning
        snapshot.dataState == DataState.WIFI -> StateWifi
        else -> StateCut
    }
    val stateLabel = when {
        !snapshot.serviceRunning -> stringResource(R.string.dashboard_control_disabled)
        snapshot.dataState == DataState.OK -> stringResource(R.string.dashboard_state_ok)
        snapshot.dataState == DataState.WARNING -> stringResource(R.string.dashboard_state_warning)
        snapshot.dataState == DataState.CUT -> stringResource(R.string.dashboard_state_cut)
        else -> stringResource(R.string.dashboard_state_wifi)
    }

    val consumedMo = snapshot.consumedMo
    val planLimitMo = settings.planLimitMo.coerceAtLeast(1L)
    val progress = (consumedMo.toFloat() / planLimitMo.toFloat()).coerceIn(0f, 1f)
    val overageMo = (consumedMo - settings.planLimitMo).coerceAtLeast(0L)
    val estimatedTotal = settings.planPriceEuro + overageMo * settings.overagePricePerMoEuro

    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
            .padding(20.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        Text(
            stringResource(R.string.dashboard_title),
            style = MaterialTheme.typography.headlineMedium
        )

        // Carte état + consommation
        Card(shape = RoundedCornerShape(20.dp), elevation = CardDefaults.cardElevation(2.dp)) {
            Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
                Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
                    Surface(shape = RoundedCornerShape(50), color = stateColor, modifier = Modifier.size(14.dp)) {}
                    Text(stateLabel, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
                }

                Text(stringResource(R.string.dashboard_consumed), style = MaterialTheme.typography.bodyMedium)
                Text(
                    "$consumedMo / ${settings.planLimitMo} Mo",
                    style = MaterialTheme.typography.headlineMedium,
                    fontWeight = FontWeight.Bold
                )
                LinearProgressIndicator(
                    progress = { progress },
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(10.dp),
                    color = stateColor,
                    trackColor = MaterialTheme.colorScheme.surfaceVariant
                )
                Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                    Text(
                        "${stringResource(R.string.dashboard_remaining)}: ${(settings.planLimitMo - consumedMo).coerceAtLeast(0L)} Mo",
                        style = MaterialTheme.typography.bodyMedium
                    )
                    if (overageMo > 0) {
                        Text(
                            "${stringResource(R.string.dashboard_overage)}: $overageMo Mo",
                            style = MaterialTheme.typography.bodyMedium,
                            color = StateCut
                        )
                    }
                }
            }
        }

        // Carte coût estimé
        Card(shape = RoundedCornerShape(20.dp), elevation = CardDefaults.cardElevation(2.dp)) {
            Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                Text(stringResource(R.string.dashboard_cost_title), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
                HorizontalDivider()
                CostRow(stringResource(R.string.dashboard_cost_plan), settings.planPriceEuro)
                CostRow(stringResource(R.string.dashboard_cost_overage), overageMo * settings.overagePricePerMoEuro)
                HorizontalDivider()
                CostRow(stringResource(R.string.dashboard_cost_total), estimatedTotal, emphasize = true)
            }
        }

        // Carte contrôle
        Card(shape = RoundedCornerShape(20.dp), elevation = CardDefaults.cardElevation(2.dp)) {
            Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) {
                Row(
                    Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        if (settings.controlEnabled) stringResource(R.string.dashboard_toggle_disable)
                        else stringResource(R.string.dashboard_toggle_enable),
                        style = MaterialTheme.typography.titleMedium
                    )
                    Switch(
                        checked = settings.controlEnabled,
                        onCheckedChange = { checked ->
                            if (checked) {
                                systemActions.requestNotificationPermission { _ ->
                                    systemActions.requestVpnPermission { granted ->
                                        if (granted) {
                                            viewModel.setControlEnabled(true)
                                            DataMonitorService.start(context)
                                        }
                                    }
                                }
                            } else {
                                if (settings.hasPassword) {
                                    disablePasswordError = false
                                    showDisablePasswordDialog = true
                                } else {
                                    viewModel.setControlEnabled(false)
                                }
                            }
                        }
                    )
                }

                Text(
                    "${stringResource(R.string.dashboard_next_reset)}: ${
                        settings.nextAutoResetDate().format(
                            DateTimeFormatter.ofPattern("d MMMM yyyy", Locale.FRENCH)
                        )
                    }",
                    style = MaterialTheme.typography.bodyMedium
                )

                OutlinedButton(onClick = { showResetDialog = true }, modifier = Modifier.fillMaxWidth()) {
                    Text(stringResource(R.string.dashboard_reset_now))
                }
            }
        }
    }

    if (showResetDialog) {
        AlertDialog(
            onDismissRequest = { showResetDialog = false },
            title = { Text(stringResource(R.string.dashboard_reset_confirm_title)) },
            text = { Text(stringResource(R.string.dashboard_reset_confirm_message)) },
            confirmButton = {
                Button(onClick = {
                    viewModel.resetPlanNow()
                    showResetDialog = false
                }) { Text(stringResource(R.string.common_confirm)) }
            },
            dismissButton = {
                OutlinedButton(onClick = { showResetDialog = false }) {
                    Text(stringResource(R.string.common_cancel))
                }
            }
        )
    }

    if (showDisablePasswordDialog) {
        PasswordPromptDialog(
            title = stringResource(R.string.password_gate_title),
            error = disablePasswordError,
            onDismiss = { showDisablePasswordDialog = false },
            onConfirm = { password ->
                scope.launch {
                    if (viewModel.verifyPassword(password)) {
                        viewModel.setControlEnabled(false)
                        showDisablePasswordDialog = false
                    } else {
                        disablePasswordError = true
                    }
                }
            }
        )
    }
}

@Composable
private fun CostRow(label: String, value: Double, emphasize: Boolean = false) {
    Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
        Text(
            label,
            style = if (emphasize) MaterialTheme.typography.titleMedium else MaterialTheme.typography.bodyMedium,
            fontWeight = if (emphasize) FontWeight.Bold else FontWeight.Normal
        )
        Text(
            String.format(Locale.FRENCH, "%.2f €", value),
            style = if (emphasize) MaterialTheme.typography.titleMedium else MaterialTheme.typography.bodyMedium,
            fontWeight = if (emphasize) FontWeight.Bold else FontWeight.Normal
        )
    }
}
