package lu.rewardflow.terminal.ui.terminal

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.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Snackbar
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import lu.rewardflow.terminal.R
import lu.rewardflow.terminal.data.model.CardLookupResponse
import lu.rewardflow.terminal.data.model.TransactionItem
import java.time.format.DateTimeFormatter
import java.time.OffsetDateTime
import java.time.ZoneId

/**
 * Main POS terminal screen.
 *
 * Phase D.1 surface — landscape layout:
 *
 *   ┌────────────────────────────────────────────────────┐
 *   │ Staff: Diana   Online •   |   Lock                 │
 *   ├──────────────┬─────────────────────────────────────┤
 *   │              │  Customer card (or empty state)     │
 *   │   Search /   │  Balance, stamps, available rewards │
 *   │   QR / Enroll│                                      │
 *   │              │  Action buttons (wired in D.2)      │
 *   └──────────────┴─────────────────────────────────────┘
 */
@Composable
fun TerminalScreen(
    staffPinId: Int,
    staffName: String,
    onLockScreen: () -> Unit,
    viewModel: TerminalViewModel = hiltViewModel(),
) {
    val state by viewModel.state.collectAsStateWithLifecycle()

    androidx.compose.runtime.LaunchedEffect(staffPinId) {
        viewModel.setStaffPinId(staffPinId)
    }

    IdleTracker(
        timeoutMillis = AUTO_LOCK_TIMEOUT_MS,
        onIdle = onLockScreen,
    ) {
        TerminalContent(
            state = state,
            staffName = staffName,
            onLockScreen = onLockScreen,
            viewModel = viewModel,
        )
    }
}

private const val AUTO_LOCK_TIMEOUT_MS = 2 * 60 * 1000L  // 2 minutes per spec

@Composable
private fun TerminalContent(
    state: TerminalUiState,
    staffName: String,
    onLockScreen: () -> Unit,
    viewModel: TerminalViewModel,
) {
    val snackbarHostState = remember { SnackbarHostState() }
    val queuedMessage = stringResource(R.string.snackbar_queued_for_sync)

    LaunchedEffect(state.actionResult) {
        if (state.actionResult is ActionResult.Queued) {
            snackbarHostState.showSnackbar(message = queuedMessage)
        }
    }

    Column(modifier = Modifier.fillMaxSize()) {
        TopBar(
            staffName = staffName,
            isOnline = state.isOnline,
            pendingSyncCount = state.pendingSyncCount,
            onLockScreen = onLockScreen,
        )
        Row(modifier = Modifier.fillMaxSize()) {
            LeftPane(
                modifier = Modifier
                    .weight(0.4f)
                    .fillMaxHeight()
                    .padding(16.dp),
                state = state,
                onSearchChanged = viewModel::onSearchChanged,
                onSearchSubmit = viewModel::onSearchSubmit,
                onScanQrClicked = viewModel::openScanner,
                onEnrollClicked = viewModel::openEnrollDialog,
                recentTransactions = state.recentTransactions,
            )
            RightPane(
                modifier = Modifier
                    .weight(0.6f)
                    .fillMaxHeight()
                    .padding(16.dp),
                customer = state.customer,
                stampsTarget = state.program?.stamps_target ?: 0,
                isOnline = state.isOnline,
                onClearCustomer = viewModel::clearCustomer,
                onAction = viewModel::openAction,
            )
        }
    }

    if (state.activeAction != null) {
        ActionSheet(
            state = state,
            onDismiss = viewModel::dismissAction,
            onSubmitStamp = viewModel::submitStamp,
            onSubmitEarn = viewModel::submitEarnPoints,
            onSubmitRedeemStamps = viewModel::submitRedeemStamps,
            onSubmitRedeemReward = viewModel::submitRedeemReward,
        )
    }

    if (state.enrollDialogOpen) {
        EnrollDialog(
            inProgress = state.enrolling,
            error = state.enrollError,
            onSubmit = viewModel::submitEnroll,
            onDismiss = viewModel::dismissEnrollDialog,
        )
    }

    if (state.scannerOpen) {
        QrScannerOverlay(
            onScanned = viewModel::onCardQrScanned,
            onCancel = viewModel::dismissScanner,
        )
    }

    // Snackbar host pinned at the bottom — always present so it can fire
    // over any of the dialogs/overlays above.
    Box(modifier = Modifier.fillMaxSize()) {
        SnackbarHost(
            hostState = snackbarHostState,
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .padding(16.dp),
        ) { data ->
            Snackbar(snackbarData = data)
        }
    }
}

@Composable
private fun TopBar(
    staffName: String,
    isOnline: Boolean,
    pendingSyncCount: Int,
    onLockScreen: () -> Unit,
) {
    Surface(
        color = MaterialTheme.colorScheme.primaryContainer,
        modifier = Modifier.fillMaxWidth(),
    ) {
        Row(
            modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Text(
                text = staffName,
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.SemiBold,
            )
            Spacer(Modifier.size(16.dp))
            OnlinePill(isOnline = isOnline)
            if (pendingSyncCount > 0) {
                Spacer(Modifier.size(8.dp))
                PendingSyncPill(count = pendingSyncCount)
            }
            Spacer(modifier = Modifier.weight(1f))
            FilledTonalButton(onClick = onLockScreen) {
                Text(stringResource(R.string.terminal_lock))
            }
        }
    }
}

@Composable
private fun PendingSyncPill(count: Int) {
    val color = MaterialTheme.colorScheme.tertiary
    Surface(
        shape = RoundedCornerShape(12.dp),
        color = color.copy(alpha = 0.18f),
    ) {
        Text(
            text = stringResource(R.string.pin_pending_sync, count),
            color = color,
            style = MaterialTheme.typography.labelSmall,
            fontWeight = FontWeight.SemiBold,
            modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp),
        )
    }
}

@Composable
private fun OnlinePill(isOnline: Boolean) {
    val (label, color) = if (isOnline)
        stringResource(R.string.terminal_online) to MaterialTheme.colorScheme.tertiary
    else
        stringResource(R.string.terminal_offline) to MaterialTheme.colorScheme.error
    Surface(
        shape = RoundedCornerShape(12.dp),
        color = color.copy(alpha = 0.18f),
    ) {
        Text(
            text = label,
            color = color,
            style = MaterialTheme.typography.labelSmall,
            fontWeight = FontWeight.SemiBold,
            modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp),
        )
    }
}

@Composable
private fun LeftPane(
    modifier: Modifier,
    state: TerminalUiState,
    onSearchChanged: (String) -> Unit,
    onSearchSubmit: () -> Unit,
    onScanQrClicked: () -> Unit,
    onEnrollClicked: () -> Unit,
    recentTransactions: List<TransactionItem>,
) {
    Surface(
        modifier = modifier,
        shape = RoundedCornerShape(16.dp),
        color = MaterialTheme.colorScheme.surfaceVariant,
    ) {
        Column(
            modifier = Modifier.padding(16.dp),
        ) {
            Text(
                text = stringResource(R.string.terminal_search_hint),
                style = MaterialTheme.typography.titleMedium,
            )
            Spacer(Modifier.height(8.dp))

            OutlinedTextField(
                value = state.searchQuery,
                onValueChange = onSearchChanged,
                singleLine = true,
                placeholder = { Text(stringResource(R.string.terminal_search_hint)) },
                keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
                keyboardActions = KeyboardActions(onSearch = { onSearchSubmit() }),
                modifier = Modifier.fillMaxWidth(),
                trailingIcon = {
                    if (state.isSearching) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(20.dp),
                            strokeWidth = 2.dp,
                        )
                    }
                },
            )
            Spacer(Modifier.height(12.dp))
            Button(
                onClick = onSearchSubmit,
                enabled = state.searchQuery.isNotBlank() && !state.isSearching,
                modifier = Modifier.fillMaxWidth(),
                contentPadding = PaddingValues(vertical = 12.dp),
            ) {
                Text(stringResource(R.string.terminal_search_hint))
            }

            Spacer(Modifier.height(12.dp))

            OutlinedButton(
                onClick = onScanQrClicked,
                modifier = Modifier.fillMaxWidth(),
                contentPadding = PaddingValues(vertical = 12.dp),
            ) {
                Text(stringResource(R.string.terminal_scan_qr))
            }
            Spacer(Modifier.height(8.dp))
            OutlinedButton(
                onClick = onEnrollClicked,
                modifier = Modifier.fillMaxWidth(),
                contentPadding = PaddingValues(vertical = 12.dp),
            ) {
                Text(stringResource(R.string.terminal_enroll_customer))
            }

            if (state.errorMessage != null) {
                Spacer(Modifier.height(16.dp))
                Surface(
                    shape = RoundedCornerShape(8.dp),
                    color = MaterialTheme.colorScheme.errorContainer,
                ) {
                    Text(
                        text = state.errorMessage,
                        modifier = Modifier.padding(12.dp),
                        color = MaterialTheme.colorScheme.onErrorContainer,
                        style = MaterialTheme.typography.bodyMedium,
                    )
                }
            }

            Spacer(Modifier.height(20.dp))
            RecentTransactionsList(
                modifier = Modifier.weight(1f),
                transactions = recentTransactions,
            )
        }
    }
}

@Composable
private fun RecentTransactionsList(
    modifier: Modifier,
    transactions: List<TransactionItem>,
) {
    Column(modifier = modifier) {
        Text(
            text = stringResource(R.string.terminal_recent_transactions),
            style = MaterialTheme.typography.titleSmall,
            fontWeight = FontWeight.SemiBold,
        )
        Spacer(Modifier.height(8.dp))
        if (transactions.isEmpty()) {
            Text(
                text = "—",
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                style = MaterialTheme.typography.bodySmall,
            )
        } else {
            LazyColumn(verticalArrangement = Arrangement.spacedBy(6.dp)) {
                items(transactions, key = { it.id }) { tx ->
                    TransactionRow(tx)
                }
            }
        }
    }
}

@Composable
private fun TransactionRow(tx: TransactionItem) {
    val delta = formatDelta(tx)
    val time = formatTransactionTime(tx.transaction_at)
    Surface(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(8.dp),
        color = MaterialTheme.colorScheme.surface,
    ) {
        Row(
            modifier = Modifier.padding(horizontal = 10.dp, vertical = 8.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Column(modifier = Modifier.weight(1f)) {
                Text(
                    text = transactionLabel(tx.transaction_type),
                    style = MaterialTheme.typography.bodyMedium,
                    fontWeight = FontWeight.Medium,
                )
                if (!tx.customer_name.isNullOrBlank()) {
                    Text(
                        text = tx.customer_name,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                    )
                }
            }
            Column(horizontalAlignment = Alignment.End) {
                if (delta != null) {
                    Text(
                        text = delta,
                        style = MaterialTheme.typography.bodyMedium,
                        fontWeight = FontWeight.SemiBold,
                    )
                }
                Text(
                    text = time,
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
            }
        }
    }
}

private fun transactionLabel(type: String): String = when (type) {
    "stamp_earned" -> "Stamp"
    "stamp_redeemed" -> "Stamp redeemed"
    "stamp_voided" -> "Stamp voided"
    "points_earned" -> "Points"
    "points_redeemed" -> "Points redeemed"
    "points_voided" -> "Points voided"
    "card_created" -> "Enrolled"
    "welcome_bonus" -> "Welcome bonus"
    "points_expired" -> "Points expired"
    "points_adjustment" -> "Points adjustment"
    "stamp_adjustment" -> "Stamp adjustment"
    else -> type.replace('_', ' ').replaceFirstChar { it.uppercase() }
}

private fun formatDelta(tx: TransactionItem): String? = when {
    tx.points_delta != 0 -> "${if (tx.points_delta > 0) "+" else ""}${tx.points_delta} pts"
    tx.stamps_delta != 0 -> "${if (tx.stamps_delta > 0) "+" else ""}${tx.stamps_delta} ★"
    else -> null
}

private val timeFormatter = DateTimeFormatter.ofPattern("HH:mm")

private fun formatTransactionTime(iso: String): String =
    runCatching {
        OffsetDateTime.parse(iso).atZoneSameInstant(ZoneId.systemDefault()).format(timeFormatter)
    }.getOrDefault(iso.take(10))

@Composable
private fun RightPane(
    modifier: Modifier,
    customer: CardLookupResponse?,
    stampsTarget: Int,
    isOnline: Boolean,
    onClearCustomer: () -> Unit,
    onAction: (ActionKind) -> Unit,
) {
    Surface(
        modifier = modifier,
        shape = RoundedCornerShape(16.dp),
        color = MaterialTheme.colorScheme.surface,
    ) {
        if (customer == null) {
            EmptyCustomerState(modifier = Modifier.fillMaxSize().padding(16.dp))
        } else {
            CustomerPanel(
                modifier = Modifier.fillMaxSize().padding(16.dp),
                customer = customer,
                stampsTarget = stampsTarget,
                isOnline = isOnline,
                onClearCustomer = onClearCustomer,
                onAction = onAction,
            )
        }
    }
}

@Composable
private fun EmptyCustomerState(modifier: Modifier) {
    Column(
        modifier = modifier,
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        Text(
            text = stringResource(R.string.terminal_no_customer_title),
            style = MaterialTheme.typography.titleLarge,
            fontWeight = FontWeight.SemiBold,
        )
        Spacer(Modifier.height(8.dp))
        Text(
            text = stringResource(R.string.terminal_no_customer_hint),
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
            textAlign = TextAlign.Center,
        )
    }
}

@Composable
private fun CustomerPanel(
    modifier: Modifier,
    customer: CardLookupResponse,
    stampsTarget: Int,
    isOnline: Boolean,
    onClearCustomer: () -> Unit,
    onAction: (ActionKind) -> Unit,
) {
    Column(modifier = modifier) {
        Row(verticalAlignment = Alignment.CenterVertically) {
            Column(modifier = Modifier.weight(1f)) {
                Text(
                    text = customer.customer_name ?: customer.customer_email,
                    style = MaterialTheme.typography.headlineSmall,
                    fontWeight = FontWeight.SemiBold,
                )
                Text(
                    text = customer.customer_email,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
                Text(
                    text = "${stringResource(R.string.terminal_card_label)}: ${customer.card_number}",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
            }
            TextButton(onClick = onClearCustomer) {
                Text(stringResource(R.string.terminal_close_customer))
            }
        }

        Spacer(Modifier.height(16.dp))

        BalanceCard(
            pointsBalance = customer.points_balance,
            stampCount = customer.stamp_count,
            stampsTarget = if (stampsTarget > 0) stampsTarget else customer.stamps_target,
        )

        Spacer(Modifier.height(16.dp))

        ActionButtons(
            customer = customer,
            isOnline = isOnline,
            onAction = onAction,
        )
    }
}

@Composable
private fun BalanceCard(
    pointsBalance: Int,
    stampCount: Int,
    stampsTarget: Int,
) {
    Surface(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(12.dp),
        color = MaterialTheme.colorScheme.primaryContainer,
    ) {
        Row(
            modifier = Modifier.padding(20.dp),
            horizontalArrangement = Arrangement.SpaceEvenly,
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                Text(
                    text = stringResource(R.string.balance_points, pointsBalance),
                    style = MaterialTheme.typography.headlineMedium,
                    color = MaterialTheme.colorScheme.onPrimaryContainer,
                    fontWeight = FontWeight.Bold,
                )
            }
            Box(
                modifier = Modifier
                    .size(width = 1.dp, height = 48.dp)
                    .clip(RoundedCornerShape(1.dp))
                    .background(MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.3f)),
            )
            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                Text(
                    text = stringResource(
                        R.string.balance_stamps,
                        stampCount,
                        if (stampsTarget > 0) stampsTarget else 10,
                    ),
                    style = MaterialTheme.typography.headlineMedium,
                    color = MaterialTheme.colorScheme.onPrimaryContainer,
                    fontWeight = FontWeight.Bold,
                )
            }
        }
    }
}

@Composable
private fun ActionButtons(
    customer: CardLookupResponse,
    isOnline: Boolean,
    onAction: (ActionKind) -> Unit,
) {
    // Earn-side actions (stamp + points) are queueable in Phase E, so
    // they remain enabled offline. Redemption requires an authoritative
    // server check, so we hard-disable when offline per the plan.
    val canRedeemReward = customer.available_rewards.isNotEmpty()

    Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
        Button(
            onClick = { onAction(ActionKind.AddStamp) },
            enabled = customer.can_stamp,
            modifier = Modifier.weight(1f),
        ) { Text(stringResource(R.string.action_add_stamp)) }
        Button(
            onClick = { onAction(ActionKind.EarnPoints) },
            modifier = Modifier.weight(1f),
        ) { Text(stringResource(R.string.action_earn_points)) }
    }
    Spacer(Modifier.height(8.dp))
    Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
        OutlinedButton(
            onClick = { onAction(ActionKind.RedeemStamps) },
            enabled = isOnline && customer.can_redeem_stamps,
            modifier = Modifier.weight(1f),
        ) { Text(stringResource(R.string.action_redeem_stamps)) }
        OutlinedButton(
            onClick = { onAction(ActionKind.RedeemReward) },
            enabled = isOnline && canRedeemReward,
            modifier = Modifier.weight(1f),
        ) { Text(stringResource(R.string.action_redeem_reward)) }
    }
}
