/*
 * Copyright (c) 2026 QPQ IaaS AG <info@qpq.swiss>. All rights reserved.
 * Project: Gajumaru Core Java Libraries <gajumaru.io>
 *
 * This program is dual-licensed:
 * 1) Under the GNU Affero General Public License as published by the Free
 *    Software Foundation, either version 3 of the License, or (at your option)
 *    any later version (AGPL-3.0-or-later).
 *
 * 2) Under a commercial/proprietary license available directly from QPQ IaaS AG.
 *    If you wish to use this software outside the strict constraints of the
 *    AGPLv3 (e.g. within a closed-source or proprietary product), you must
 *    purchase a commercial license from QPQ IaaS AG.
 *
 * Authors:
 *   - Craig Everett <craigeverett@qpq.swiss>
 *
 * SPDX-License-Identifier: AGPL-3.0-or-later OR LicenseRef-QPQ-Commercial
 */

package swiss.qpq.gajumobile.ui.screens

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AssistChip
import androidx.compose.material3.AssistChipDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.SuggestionChip
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.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import swiss.qpq.gajumobile.R
import swiss.qpq.gajumobile.security.AccountAirlock
import swiss.qpq.gajumobile.ui.components.CommittedWordChip
import swiss.qpq.gajumobile.ui.components.GajuButton
import swiss.qpq.gajumobile.ui.components.GajuHeader
import swiss.qpq.gajumobile.ui.components.GajuTextField

@OptIn(ExperimentalLayoutApi::class)
@Composable
fun MnemonicVerifyScreen(
    label: String,
    expectedPhrase: Array<ByteArray>,
    onVerified: () -> Unit,
    onBack: () -> Unit,
) {
    var committedWords by remember { mutableStateOf(listOf<String>()) }
    var currentDraft by remember { mutableStateOf("") }
    var isAddingWord by remember { mutableStateOf(value = true) }
    var verificationError by remember { mutableStateOf(false) }

    val allWords = remember { AccountAirlock.getWordList().toList() }
    val focusRequester = remember { FocusRequester() }
    
    LaunchedEffect(isAddingWord) {
        if (isAddingWord) focusRequester.requestFocus()
    }

    val suggestions = if (currentDraft.length >= 2) {
        allWords.asSequence().filter { it.startsWith(currentDraft) }.take(5).toList()
    } else emptyList()

    Scaffold(
        modifier = Modifier.fillMaxSize().imePadding(),
        bottomBar = {
            Column {
                if (suggestions.isNotEmpty() && isAddingWord) {
                    Surface(
                        modifier = Modifier.fillMaxWidth(),
                        color = MaterialTheme.colorScheme.surfaceVariant,
                        tonalElevation = 8.dp
                    ) {
                        FlowRow(
                            modifier = Modifier.padding(8.dp).fillMaxWidth(),
                            horizontalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            suggestions.forEach { suggestion ->
                                SuggestionChip(
                                    onClick = {
                                        committedWords += suggestion
                                        currentDraft = ""
                                        isAddingWord = false
                                        verificationError = false
                                    },
                                    label = { Text(suggestion) }
                                )
                            }
                        }
                    }
                }
                
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .windowInsetsPadding(WindowInsets.navigationBars)
                        .padding(24.dp),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    GajuButton(
                        text = stringResource(R.string.back_button_caps), 
                        onClick = onBack, 
                        modifier = Modifier.weight(1f),
                        containerColor = MaterialTheme.colorScheme.secondary,
                        contentColor = MaterialTheme.colorScheme.onSecondary
                    )
                    Spacer(modifier = Modifier.width(16.dp))
                    GajuButton(
                        text = stringResource(R.string.verify_button_caps),
                        enabled = (committedWords.size == expectedPhrase.size) && !isAddingWord,
                        onClick = { 
                            val inputPhrase = committedWords.map { it.toByteArray(Charsets.UTF_8) }
                            var match = true
                            for (i in inputPhrase.indices) {
                                if (!inputPhrase[i].contentEquals(expectedPhrase[i])) {
                                    match = false
                                    break
                                }
                            }

                            if (match) {
                                onVerified()
                            } else {
                                verificationError = true
                            }
                        },
                        modifier = Modifier.weight(1f)
                    )
                }
            }
        }
    ) { innerPadding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding)
                .padding(horizontal = 24.dp)
                .verticalScroll(rememberScrollState())
        ) {
            GajuHeader()
            Text(
                stringResource(R.string.verify_backup_title), 
                style = MaterialTheme.typography.headlineMedium,
                color = MaterialTheme.colorScheme.onBackground
            )
            Text(
                label.uppercase(), 
                style = MaterialTheme.typography.labelLarge,
                color = MaterialTheme.colorScheme.primary
            )
            Spacer(modifier = Modifier.height(16.dp))

            FlowRow(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                committedWords.forEachIndexed { index, word ->
                    CommittedWordChip(
                        index = index + 1,
                        word = word,
                        onClick = {
                            currentDraft = word
                            committedWords = committedWords.take(index)
                            isAddingWord = true
                            verificationError = false
                        }
                    )
                }
                
                if (isAddingWord && committedWords.size < expectedPhrase.size) {
                    Box(modifier = Modifier.width(120.dp)) {
                        GajuTextField(
                            value = currentDraft,
                            onValueChange = { currentDraft = it.lowercase() },
                            label = (committedWords.size + 1).toString(),
                            placeholder = "...",
                            modifier = Modifier.focusRequester(focusRequester)
                        )
                    }
                } else if (committedWords.size < expectedPhrase.size) {
                    AssistChip(
                        onClick = { isAddingWord = true },
                        label = { Text(stringResource(R.string.add_next_word_button)) },
                        colors = AssistChipDefaults.assistChipColors(
                            containerColor = MaterialTheme.colorScheme.primaryContainer,
                            labelColor = MaterialTheme.colorScheme.onPrimaryContainer
                        )
                    )
                }
            }

            if (verificationError) {
                Spacer(modifier = Modifier.height(16.dp))
                Text(
                    stringResource(R.string.err_mnemonic_mismatch),
                    color = MaterialTheme.colorScheme.error,
                    style = MaterialTheme.typography.bodySmall
                )
            }
            
            Spacer(modifier = Modifier.height(32.dp))
        }
    }
}
