package lu.rewardflow.terminal.ui.terminal

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.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import lu.rewardflow.terminal.R
import lu.rewardflow.terminal.data.model.CardLookupResponse
import lu.rewardflow.terminal.data.model.CategoryItem
import lu.rewardflow.terminal.data.model.RewardItem

/**
 * Modal action sheets fired from the Terminal screen's right-pane buttons.
 *
 * Each is an [AlertDialog] keyed on [TerminalUiState.activeAction] —
 * [TerminalScreen] delegates to this single composable which dispatches
 * to the right body. The dialog dismisses on submit (the ViewModel closes
 * `activeAction` on success) or on Cancel.
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ActionSheet(
    state: TerminalUiState,
    onDismiss: () -> Unit,
    onSubmitStamp: (List<Int>) -> Unit,
    onSubmitEarn: (amountCents: Int, categoryIds: List<Int>) -> Unit,
    onSubmitRedeemStamps: () -> Unit,
    onSubmitRedeemReward: (rewardId: String) -> Unit,
) {
    val customer = state.customer ?: return
    when (state.activeAction) {
        ActionKind.AddStamp -> AddStampDialog(
            categories = state.categories,
            inProgress = state.actionInProgress,
            failure = (state.actionResult as? ActionResult.Failure)?.message,
            onConfirm = onSubmitStamp,
            onDismiss = onDismiss,
        )

        ActionKind.EarnPoints -> EarnPointsDialog(
            categories = state.categories,
            inProgress = state.actionInProgress,
            failure = (state.actionResult as? ActionResult.Failure)?.message,
            onConfirm = onSubmitEarn,
            onDismiss = onDismiss,
        )

        ActionKind.RedeemStamps -> RedeemStampsDialog(
            customer = customer,
            inProgress = state.actionInProgress,
            failure = (state.actionResult as? ActionResult.Failure)?.message,
            onConfirm = onSubmitRedeemStamps,
            onDismiss = onDismiss,
        )

        ActionKind.RedeemReward -> RedeemRewardDialog(
            rewards = customer.available_rewards,
            inProgress = state.actionInProgress,
            failure = (state.actionResult as? ActionResult.Failure)?.message,
            onConfirm = onSubmitRedeemReward,
            onDismiss = onDismiss,
        )

        null -> Unit
    }
}

// ── Add Stamp ─────────────────────────────────────────────────────────

@Composable
private fun AddStampDialog(
    categories: List<CategoryItem>,
    inProgress: Boolean,
    failure: String?,
    onConfirm: (List<Int>) -> Unit,
    onDismiss: () -> Unit,
) {
    val selected = remember { mutableStateOf(emptySet<Int>()) }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(stringResource(R.string.action_add_stamp)) },
        text = {
            Column {
                CategoryPills(
                    categories = categories,
                    selected = selected.value,
                    onToggle = { id -> selected.value = selected.value.toggle(id) },
                )
                FailureLine(failure)
            }
        },
        confirmButton = {
            ConfirmButton(
                inProgress = inProgress,
                onClick = { onConfirm(selected.value.toList()) },
            )
        },
        dismissButton = {
            TextButton(onClick = onDismiss, enabled = !inProgress) {
                Text(stringResource(R.string.action_cancel))
            }
        },
    )
}

// ── Earn Points ───────────────────────────────────────────────────────

@Composable
private fun EarnPointsDialog(
    categories: List<CategoryItem>,
    inProgress: Boolean,
    failure: String?,
    onConfirm: (amountCents: Int, categoryIds: List<Int>) -> Unit,
    onDismiss: () -> Unit,
) {
    var amountText by remember { mutableStateOf("") }
    val selected = remember { mutableStateOf(emptySet<Int>()) }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(stringResource(R.string.action_earn_points)) },
        text = {
            Column {
                OutlinedTextField(
                    value = amountText,
                    onValueChange = { input ->
                        // Accept digits + optional single comma/period for cents.
                        amountText = input.filter { it.isDigit() || it == '.' || it == ',' }
                    },
                    label = { Text(stringResource(R.string.action_purchase_amount)) },
                    singleLine = true,
                    keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
                        keyboardType = KeyboardType.Decimal,
                    ),
                    modifier = Modifier.fillMaxWidth(),
                )
                Spacer(Modifier.height(12.dp))
                CategoryPills(
                    categories = categories,
                    selected = selected.value,
                    onToggle = { id -> selected.value = selected.value.toggle(id) },
                )
                FailureLine(failure)
            }
        },
        confirmButton = {
            val cents = parseCents(amountText)
            ConfirmButton(
                inProgress = inProgress,
                enabled = cents != null && cents > 0,
                onClick = {
                    parseCents(amountText)?.let { v ->
                        onConfirm(v, selected.value.toList())
                    }
                },
            )
        },
        dismissButton = {
            TextButton(onClick = onDismiss, enabled = !inProgress) {
                Text(stringResource(R.string.action_cancel))
            }
        },
    )
}

// ── Redeem Stamps ─────────────────────────────────────────────────────

@Composable
private fun RedeemStampsDialog(
    customer: CardLookupResponse,
    inProgress: Boolean,
    failure: String?,
    onConfirm: () -> Unit,
    onDismiss: () -> Unit,
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(stringResource(R.string.action_redeem_stamps)) },
        text = {
            Column {
                Text(
                    text = customer.stamp_reward_description
                        ?: stringResource(R.string.action_redeem_stamps),
                    style = MaterialTheme.typography.bodyLarge,
                )
                Spacer(Modifier.height(8.dp))
                Text(
                    text = stringResource(
                        R.string.balance_stamps,
                        customer.stamp_count,
                        customer.stamps_target,
                    ),
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
                FailureLine(failure)
            }
        },
        confirmButton = {
            ConfirmButton(inProgress = inProgress, onClick = onConfirm)
        },
        dismissButton = {
            TextButton(onClick = onDismiss, enabled = !inProgress) {
                Text(stringResource(R.string.action_cancel))
            }
        },
    )
}

// ── Redeem Reward ─────────────────────────────────────────────────────

@Composable
private fun RedeemRewardDialog(
    rewards: List<RewardItem>,
    inProgress: Boolean,
    failure: String?,
    onConfirm: (String) -> Unit,
    onDismiss: () -> Unit,
) {
    var selectedId by remember { mutableStateOf(rewards.firstOrNull()?.id) }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(stringResource(R.string.action_redeem_reward)) },
        text = {
            Column {
                if (rewards.isEmpty()) {
                    Text(
                        text = stringResource(R.string.error_unknown),
                        style = MaterialTheme.typography.bodyMedium,
                    )
                } else {
                    LazyColumn {
                        items(rewards, key = { it.id }) { reward ->
                            RewardRow(
                                reward = reward,
                                selected = reward.id == selectedId,
                                onClick = { selectedId = reward.id },
                            )
                            HorizontalDivider()
                        }
                    }
                }
                FailureLine(failure)
            }
        },
        confirmButton = {
            ConfirmButton(
                inProgress = inProgress,
                enabled = selectedId != null,
                onClick = { selectedId?.let(onConfirm) },
            )
        },
        dismissButton = {
            TextButton(onClick = onDismiss, enabled = !inProgress) {
                Text(stringResource(R.string.action_cancel))
            }
        },
    )
}

@Composable
private fun RewardRow(
    reward: RewardItem,
    selected: Boolean,
    onClick: () -> Unit,
) {
    Surface(
        modifier = Modifier.fillMaxWidth(),
        onClick = onClick,
        color = if (selected)
            MaterialTheme.colorScheme.primaryContainer
        else
            MaterialTheme.colorScheme.surface,
    ) {
        Row(
            modifier = Modifier.wrapContentSize(),
            verticalAlignment = androidx.compose.ui.Alignment.CenterVertically,
        ) {
            RadioButton(selected = selected, onClick = onClick)
            Column(modifier = Modifier.padding(end = 8.dp)) {
                Text(
                    text = reward.name,
                    style = MaterialTheme.typography.titleMedium,
                )
                Text(
                    text = "${reward.points_required} pts",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
            }
        }
    }
}

// ── Shared bits ───────────────────────────────────────────────────────

@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun CategoryPills(
    categories: List<CategoryItem>,
    selected: Set<Int>,
    onToggle: (Int) -> Unit,
) {
    if (categories.isEmpty()) {
        return
    }
    Text(
        text = stringResource(R.string.action_select_category),
        style = MaterialTheme.typography.labelLarge,
    )
    Spacer(Modifier.height(6.dp))
    FlowRow(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(6.dp),
        verticalArrangement = Arrangement.spacedBy(6.dp),
    ) {
        categories.forEach { c ->
            FilterChip(
                selected = c.id in selected,
                onClick = { onToggle(c.id) },
                label = { Text(c.name) },
            )
        }
    }
}

@Composable
private fun FailureLine(failure: String?) {
    if (failure == null) return
    Spacer(Modifier.height(8.dp))
    Text(
        text = failure,
        style = MaterialTheme.typography.bodySmall,
        color = MaterialTheme.colorScheme.error,
    )
}

@Composable
private fun ConfirmButton(
    inProgress: Boolean,
    enabled: Boolean = true,
    onClick: () -> Unit,
) {
    TextButton(
        onClick = onClick,
        enabled = enabled && !inProgress,
    ) {
        if (inProgress) {
            CircularProgressIndicator(
                modifier = Modifier.size(16.dp),
                strokeWidth = 2.dp,
            )
            Spacer(Modifier.size(8.dp))
        }
        Text(stringResource(R.string.action_confirm))
    }
}

// ── Helpers ───────────────────────────────────────────────────────────

private fun Set<Int>.toggle(id: Int): Set<Int> =
    if (contains(id)) this - id else this + id

/** Parse "12.50" / "12,50" / "1250" → cents. Returns null on garbage. */
private fun parseCents(text: String): Int? {
    val normalized = text.replace(',', '.').trim()
    if (normalized.isEmpty()) return null
    val euros = normalized.toDoubleOrNull() ?: return null
    if (euros <= 0) return null
    return (euros * 100).toInt()
}
