package lu.rewardflow.terminal.ui.setup

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.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
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.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
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.ui.scanner.QrScannerView

/**
 * First-time pairing screen.
 *
 * Left half: live QR scanner. Decoded value is fed to [SetupViewModel.pairFromQr]
 * which verifies with the server and persists the configuration.
 *
 * Right half: manual entry form (dev fallback). Same downstream flow.
 *
 * On successful pair, [onSetupComplete] is invoked once — the NavHost reacts
 * to the persisted ``is_device_set_up`` flag and forwards to the PIN screen.
 */
@Composable
fun SetupScreen(
    onSetupComplete: () -> Unit,
    viewModel: SetupViewModel = hiltViewModel(),
) {
    val state by viewModel.state.collectAsStateWithLifecycle()

    LaunchedEffect(state) {
        if (state is SetupState.Success) onSetupComplete()
    }

    Row(modifier = Modifier.fillMaxSize()) {
        // ── Left half: QR scanner
        Box(
            modifier = Modifier
                .weight(1f)
                .fillMaxHeight()
                .background(Color.Black),
        ) {
            QrScannerView(
                onQrScanned = { raw -> viewModel.pairFromQr(raw) },
            )

            // Status overlay on top of the camera preview
            StatusOverlay(state = state, onDismissError = viewModel::resetError)
        }

        // ── Right half: manual entry + instruction
        ManualEntryPanel(
            modifier = Modifier
                .weight(1f)
                .fillMaxHeight()
                .padding(32.dp),
            isConnecting = state is SetupState.Connecting,
            onConnect = { apiUrl, storeId, storeCode, token ->
                viewModel.pairManually(apiUrl, storeId, storeCode, token)
            },
        )
    }
}

@Composable
private fun StatusOverlay(
    state: SetupState,
    onDismissError: () -> Unit,
) {
    when (state) {
        is SetupState.Connecting -> {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(Color.Black.copy(alpha = 0.55f)),
                contentAlignment = Alignment.Center,
            ) {
                Column(horizontalAlignment = Alignment.CenterHorizontally) {
                    CircularProgressIndicator(color = Color.White)
                    Spacer(Modifier.height(12.dp))
                    Text(
                        text = stringResource(R.string.setup_connecting),
                        color = Color.White,
                        style = MaterialTheme.typography.bodyLarge,
                    )
                }
            }
        }

        is SetupState.Error -> {
            val message = when (val e = state.reason) {
                SetupError.InvalidQr -> stringResource(R.string.setup_invalid_qr)
                is SetupError.ConnectionFailed ->
                    e.detail ?: stringResource(R.string.setup_connection_failed)
            }
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(24.dp),
                contentAlignment = Alignment.BottomCenter,
            ) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    modifier = Modifier
                        .clip(RoundedCornerShape(8.dp))
                        .background(MaterialTheme.colorScheme.errorContainer)
                        .padding(16.dp),
                ) {
                    Text(
                        text = message,
                        color = MaterialTheme.colorScheme.onErrorContainer,
                        textAlign = TextAlign.Center,
                    )
                    Spacer(Modifier.height(8.dp))
                    Button(onClick = onDismissError) {
                        Text(stringResource(R.string.error_try_again))
                    }
                }
            }
        }

        else -> Unit
    }
}

@Composable
private fun ManualEntryPanel(
    modifier: Modifier = Modifier,
    isConnecting: Boolean,
    onConnect: (apiUrl: String, storeId: Int, storeCode: String, authToken: String) -> Unit,
) {
    var apiUrl by rememberSaveable { mutableStateOf("") }
    var storeIdText by rememberSaveable { mutableStateOf("") }
    var storeCode by rememberSaveable { mutableStateOf("") }
    var authToken by rememberSaveable { mutableStateOf("") }

    Column(
        modifier = modifier,
        verticalArrangement = Arrangement.Center,
    ) {
        Text(
            text = stringResource(R.string.setup_title),
            style = MaterialTheme.typography.headlineMedium,
        )
        Spacer(Modifier.height(8.dp))
        Text(
            text = stringResource(R.string.setup_instruction),
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
        )
        Spacer(Modifier.height(24.dp))
        Text(
            text = stringResource(R.string.setup_or_manual),
            style = MaterialTheme.typography.labelLarge,
        )
        Spacer(Modifier.height(8.dp))

        OutlinedTextField(
            value = apiUrl,
            onValueChange = { apiUrl = it },
            label = { Text(stringResource(R.string.setup_api_url)) },
            singleLine = true,
            placeholder = { Text("http://10.0.2.2:8000") },
            modifier = Modifier.fillMaxWidth(),
        )
        Spacer(Modifier.height(8.dp))
        OutlinedTextField(
            value = storeCode,
            onValueChange = { storeCode = it },
            label = { Text(stringResource(R.string.setup_store_code)) },
            singleLine = true,
            modifier = Modifier.fillMaxWidth(),
        )
        Spacer(Modifier.height(8.dp))
        OutlinedTextField(
            value = storeIdText,
            onValueChange = { storeIdText = it.filter(Char::isDigit) },
            label = { Text("Store ID") },
            singleLine = true,
            modifier = Modifier.fillMaxWidth(),
        )
        Spacer(Modifier.height(8.dp))
        OutlinedTextField(
            value = authToken,
            onValueChange = { authToken = it },
            label = { Text(stringResource(R.string.setup_auth_token)) },
            singleLine = true,
            visualTransformation = PasswordVisualTransformation(),
            modifier = Modifier.fillMaxWidth(),
        )
        Spacer(Modifier.height(16.dp))
        Button(
            enabled = !isConnecting,
            onClick = {
                onConnect(
                    apiUrl.trim(),
                    storeIdText.toIntOrNull() ?: 0,
                    storeCode.trim(),
                    authToken.trim(),
                )
            },
            modifier = Modifier.fillMaxWidth(),
            contentPadding = PaddingValues(vertical = 12.dp),
        ) {
            Text(stringResource(R.string.setup_connect))
        }
    }
}
