package lu.rewardflow.terminal.ui.pin

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
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.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
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.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import lu.rewardflow.terminal.R
import lu.rewardflow.terminal.data.model.PinForDeviceItem

/**
 * Two-pane landscape PIN entry.
 *
 * Left: scrollable list of staff names (cached, refreshed on init).
 * Right: PIN dots + numeric keypad. Once the user has typed enough
 * digits the view-model bcrypt-verifies against the cached list and
 * fires [onPinVerified] via a [LaunchedEffect] watching the verified
 * state.
 *
 * Footer carries the offline / pending-sync indicator so the cashier
 * sees at a glance whether their next transaction will go through
 * straight away or get queued.
 */
@Composable
fun PinScreen(
    onPinVerified: (staffPinId: Int, staffName: String) -> Unit,
    viewModel: PinViewModel = hiltViewModel(),
) {
    val state by viewModel.state.collectAsStateWithLifecycle()

    LaunchedEffect(state.verified) {
        val verified = state.verified
        if (verified != null) {
            onPinVerified(verified.id, verified.name)
            viewModel.consumeVerified()
        }
    }

    Column(modifier = Modifier.fillMaxSize().padding(24.dp)) {
        Row(modifier = Modifier.weight(1f).fillMaxWidth()) {
            StaffListPane(
                modifier = Modifier.weight(1f).fillMaxHeight(),
                pins = state.pins,
                loading = state.loading,
            )
            Spacer(Modifier.size(24.dp))
            KeypadPane(
                modifier = Modifier.weight(1f).fillMaxHeight(),
                state = state,
                onDigit = viewModel::onDigit,
                onBackspace = viewModel::onBackspace,
                onClear = viewModel::onClear,
            )
        }
        StatusFooter(
            pendingSyncCount = state.pendingSyncCount,
            isOnline = state.isOnline,
        )
    }
}

@Composable
private fun StaffListPane(
    modifier: Modifier,
    pins: List<PinForDeviceItem>,
    loading: Boolean,
) {
    Column(modifier = modifier) {
        Text(
            text = stringResource(R.string.pin_select_staff),
            style = MaterialTheme.typography.titleLarge,
        )
        Spacer(Modifier.height(16.dp))
        when {
            loading -> {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center,
                ) {
                    CircularProgressIndicator()
                }
            }
            pins.isEmpty() -> {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center,
                ) {
                    Text(
                        text = stringResource(R.string.pin_no_staff),
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                    )
                }
            }
            else -> {
                LazyColumn(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                    items(pins, key = { it.id }) { pin -> StaffRow(pin) }
                }
            }
        }
    }
}

@Composable
private fun StaffRow(pin: PinForDeviceItem) {
    val containerColor = when {
        pin.is_locked -> MaterialTheme.colorScheme.errorContainer
        !pin.is_active -> MaterialTheme.colorScheme.surfaceVariant
        else -> MaterialTheme.colorScheme.surface
    }
    Surface(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(12.dp))
            .border(
                width = 1.dp,
                color = MaterialTheme.colorScheme.outlineVariant,
                shape = RoundedCornerShape(12.dp),
            ),
        color = containerColor,
        tonalElevation = 1.dp,
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
        ) {
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .clip(CircleShape)
                    .background(MaterialTheme.colorScheme.primaryContainer),
                contentAlignment = Alignment.Center,
            ) {
                Text(
                    text = pin.name.firstOrNull()?.uppercase() ?: "?",
                    style = MaterialTheme.typography.titleMedium,
                    color = MaterialTheme.colorScheme.onPrimaryContainer,
                )
            }
            Spacer(Modifier.size(12.dp))
            Column(modifier = Modifier.weight(1f)) {
                Text(
                    text = pin.name,
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.SemiBold,
                )
                if (pin.staff_id != null) {
                    Text(
                        text = pin.staff_id,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                    )
                }
            }
            if (pin.is_locked) {
                Text(
                    text = stringResource(R.string.pin_locked),
                    style = MaterialTheme.typography.labelSmall,
                    color = MaterialTheme.colorScheme.error,
                )
            }
        }
    }
}

@Composable
private fun KeypadPane(
    modifier: Modifier,
    state: PinUiState,
    onDigit: (Char) -> Unit,
    onBackspace: () -> Unit,
    onClear: () -> Unit,
) {
    Column(
        modifier = modifier,
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
    ) {
        Text(
            text = stringResource(R.string.pin_enter),
            style = MaterialTheme.typography.titleLarge,
        )
        Spacer(Modifier.height(20.dp))

        // PIN dots — 6 wide so users see when their PIN exceeds the
        // common 4-digit length.
        Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
            repeat(6) { i ->
                val filled = state.enteredDigits.length > i
                val outlineOnly = i >= 4 && !filled
                Surface(
                    modifier = Modifier.size(48.dp),
                    shape = RoundedCornerShape(10.dp),
                    color = when {
                        filled -> MaterialTheme.colorScheme.primary
                        outlineOnly -> Color.Transparent
                        else -> MaterialTheme.colorScheme.surfaceVariant
                    },
                    border = if (outlineOnly)
                        BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant)
                    else null,
                ) {
                    Box(contentAlignment = Alignment.Center) {
                        if (filled) {
                            Text(
                                text = "•",
                                fontSize = 28.sp,
                                color = MaterialTheme.colorScheme.onPrimary,
                            )
                        }
                    }
                }
            }
        }

        if (state.errorMessage != null) {
            Spacer(Modifier.height(10.dp))
            Text(
                text = stringResource(
                    when (state.errorMessage) {
                        ErrorReason.WrongPin -> R.string.pin_wrong
                        ErrorReason.Locked -> R.string.pin_locked
                        ErrorReason.Unknown -> R.string.error_unknown
                    }
                ),
                color = MaterialTheme.colorScheme.error,
                style = MaterialTheme.typography.bodyMedium,
            )
        }

        if (state.verifying) {
            Spacer(Modifier.height(10.dp))
            CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)
        }

        Spacer(Modifier.height(28.dp))

        val rows = listOf(
            listOf("1", "2", "3"),
            listOf("4", "5", "6"),
            listOf("7", "8", "9"),
            listOf("C", "0", "⌫"),
        )
        rows.forEach { row ->
            Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
                row.forEach { label ->
                    FilledTonalButton(
                        onClick = {
                            when (label) {
                                "C" -> onClear()
                                "⌫" -> onBackspace()
                                else -> onDigit(label[0])
                            }
                        },
                        modifier = Modifier.size(76.dp),
                        contentPadding = PaddingValues(0.dp),
                    ) {
                        Text(label, fontSize = 24.sp)
                    }
                }
            }
            Spacer(Modifier.height(10.dp))
        }
    }
}

@Composable
private fun StatusFooter(
    pendingSyncCount: Int,
    isOnline: Boolean,
) {
    Spacer(Modifier.height(8.dp))
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Text(
            text = stringResource(if (isOnline) R.string.terminal_online else R.string.terminal_offline),
            style = MaterialTheme.typography.labelMedium,
            color = if (isOnline)
                MaterialTheme.colorScheme.primary
            else
                MaterialTheme.colorScheme.error,
        )
        Text(
            text = if (pendingSyncCount == 0)
                stringResource(R.string.pin_all_synced)
            else
                stringResource(R.string.pin_pending_sync, pendingSyncCount),
            style = MaterialTheme.typography.labelMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
        )
    }
}
