/*
 * 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.background
import androidx.compose.foundation.clickable
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.painterResource
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 swiss.qpq.gajumobile.R
import swiss.qpq.gajumobile.data.models.Endpoint
import swiss.qpq.gajumobile.data.models.Wallet
import swiss.qpq.gajumobile.ui.components.GajuHeader
import swiss.qpq.gajumobile.ui.components.GajuTextField
import swiss.qpq.gajumobile.ui.components.ManageAction

@Composable
fun ManageWalletsScreen(
    wallets: List<Wallet>,
    onAddWallet: () -> Unit,
    onRenameWallet: (String, String) -> Unit,
    onDeleteWallet: (String) -> Unit,
    onUpdateEndpoints: (String, List<Endpoint>) -> Unit,
    onAddEndpoint: (String, String, Int, Boolean) -> Unit,
    onCheckStatus: (String, Int) -> Unit,
    statusResult: Map<String, Any?>? = null,
    statusError: String? = null,
    onClearStatus: () -> Unit,
    onBack: () -> Unit,
) {
    var walletToRename by remember { mutableStateOf<Wallet?>(null) }
    var newName by remember { mutableStateOf("") }
    
    var walletForNewEndpoint by remember { mutableStateOf<Wallet?>(null) }
    var newHost by remember { mutableStateOf("") }
    var newPort by remember { mutableStateOf("3013") }
    var newUseTls by remember { mutableStateOf(value = false) }

    var selectedEndpoint by remember { mutableStateOf<Pair<String, Int>?>(null) }

    if (statusResult != null || statusError != null) {
        androidx.compose.ui.window.Dialog(onDismissRequest = onClearStatus) {
            Surface(
                shape = RoundedCornerShape(16.dp),
                color = MaterialTheme.colorScheme.surface,
                tonalElevation = 8.dp,
            ) {
                Column(modifier = Modifier.padding(24.dp)) {
                    Text(stringResource(R.string.node_status_title), style = MaterialTheme.typography.headlineSmall)
                    Spacer(modifier = Modifier.height(16.dp))
                    if (statusError != null) {
                        Text(stringResource(R.string.error_with_value, statusError), color = MaterialTheme.colorScheme.error)
                    } else if (statusResult != null) {
                        val scrollState = rememberScrollState()
                        Column(modifier = Modifier.height(300.dp).verticalScroll(scrollState)) {
                            statusResult.forEach { (k, v) ->
                                Row(modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
                                    Text("$k: ", fontWeight = FontWeight.Bold, fontSize = 12.sp)
                                    Text(v.toString(), fontSize = 12.sp, fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace)
                                }
                            }
                        }
                    }
                    Spacer(modifier = Modifier.height(24.dp))
                    TextButton(onClick = onClearStatus, modifier = Modifier.align(Alignment.End)) {
                        Text(stringResource(R.string.close_button_caps))
                    }
                }
            }
        }
    }

    if (walletToRename != null) {
        androidx.compose.ui.window.Dialog(onDismissRequest = { walletToRename = null }) {
            Surface(
                shape = RoundedCornerShape(16.dp),
                color = MaterialTheme.colorScheme.surface,
                tonalElevation = 8.dp,
            ) {
                Column(modifier = Modifier.padding(24.dp)) {
                    Text(stringResource(R.string.rename_wallet_title), style = MaterialTheme.typography.headlineSmall)
                    Spacer(modifier = Modifier.height(16.dp))
                    GajuTextField(
                        value = newName,
                        onValueChange = { newName = it },
                        label = stringResource(R.string.new_name_label),
                    )
                    Spacer(modifier = Modifier.height(24.dp))
                    Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
                        TextButton(onClick = { walletToRename = null }) { Text(stringResource(R.string.cancel)) }
                        Spacer(modifier = Modifier.width(8.dp))
                        TextButton(
                            onClick = { 
                                walletToRename?.let { onRenameWallet(it.id, newName) }
                                walletToRename = null
                            }
                        ) { Text(stringResource(R.string.save_button_caps)) }
                    }
                }
            }
        }
    }

    if (walletForNewEndpoint != null) {
        val placeholderHost = if (walletForNewEndpoint?.networkId == "groot.testnet") "groot.testnet.gajumaru.io" else "groot.mainnet.gajumaru.io"
        androidx.compose.ui.window.Dialog(onDismissRequest = { walletForNewEndpoint = null }) {
            Surface(
                shape = RoundedCornerShape(16.dp),
                color = MaterialTheme.colorScheme.surface,
                tonalElevation = 8.dp,
            ) {
                Column(modifier = Modifier.padding(24.dp)) {
                    Text(stringResource(R.string.add_endpoint_title), style = MaterialTheme.typography.headlineSmall)
                    Spacer(modifier = Modifier.height(16.dp))
                    GajuTextField(
                        value = newHost,
                        onValueChange = { newHost = it },
                        label = stringResource(R.string.host_label),
                        singleLine = true,
                        placeholder = placeholderHost,
                    )
                    Spacer(modifier = Modifier.height(16.dp))
                    GajuTextField(
                        value = newPort,
                        onValueChange = { newPort = it },
                        label = stringResource(R.string.port_label),
                        singleLine = true,
                        placeholder = "3013"
                    )
                    Spacer(modifier = Modifier.height(16.dp))
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        androidx.compose.material3.Switch(
                            checked = newUseTls,
                            onCheckedChange = { newUseTls = it }
                        )
                        Spacer(Modifier.width(12.dp))
                        Text(stringResource(R.string.use_tls_label), style = MaterialTheme.typography.bodyMedium)
                    }
                    Spacer(modifier = Modifier.height(24.dp))
                    Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
                        TextButton(onClick = { walletForNewEndpoint = null }) { Text(stringResource(R.string.cancel)) }
                        Spacer(modifier = Modifier.width(8.dp))
                        TextButton(
                            enabled = (newHost.isNotBlank() && newPort.toIntOrNull() != null),
                            onClick = { 
                                walletForNewEndpoint?.let { wallet ->
                                    val port = newPort.toIntOrNull() ?: 3013
                                    onAddEndpoint(wallet.id, newHost, port, newUseTls)
                                }
                                walletForNewEndpoint = null
                                newHost = ""
                                newPort = "3013"
                                newUseTls = false
                            }
                        ) { Text(stringResource(R.string.add_button_caps)) }
                    }
                }
            }
        }
    }

    Scaffold { innerPadding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(MaterialTheme.colorScheme.background)
                .padding(innerPadding)
                .imePadding()
                .padding(horizontal = 24.dp)
                .verticalScroll(rememberScrollState()),
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {
            GajuHeader()
            Text(
                stringResource(R.string.manage_wallets_title),
                style = MaterialTheme.typography.headlineMedium,
                color = MaterialTheme.colorScheme.onBackground
            )
            
            Spacer(modifier = Modifier.height(24.dp))

            wallets.forEach { wallet ->
                WalletManagementCard(
                    wallet = wallet,
                    selectedEndpointIndex = if (selectedEndpoint?.first == wallet.id) selectedEndpoint?.second else null,
                    onRename = { 
                        newName = wallet.name
                        walletToRename = wallet 
                    },
                    onDelete = { onDeleteWallet(wallet.id) },
                    onAddEndpoint = { walletForNewEndpoint = wallet },
                    onDeleteEndpoint = { index ->
                        val newList = wallet.endpoints.toMutableList().apply { removeAt(index) }
                        onUpdateEndpoints(wallet.id, newList)
                        if (selectedEndpoint?.first == wallet.id && selectedEndpoint?.second == index) {
                            selectedEndpoint = null
                        }
                    },
                    onEndpointClick = { index ->
                        selectedEndpoint = if (selectedEndpoint?.first == wallet.id && selectedEndpoint?.second == index) {
                            null
                        } else {
                            wallet.id to index
                        }
                    },
                    onCheckStatus = { index ->
                        onCheckStatus(wallet.id, index)
                    }
                )
                Spacer(modifier = Modifier.height(16.dp))
            }

            Spacer(modifier = Modifier.height(24.dp))

            ManageAction(
                label = stringResource(R.string.add_new_wallet_action),
                icon = R.drawable.ic_add,
                onClick = onAddWallet
            )
            
            Spacer(modifier = Modifier.height(32.dp))
            
            TextButton(onClick = onBack) {
                Text(stringResource(R.string.done_button))
            }
        }
    }
}

@Composable
private fun WalletManagementCard(
    wallet: Wallet,
    selectedEndpointIndex: Int?,
    onRename: () -> Unit,
    onDelete: () -> Unit,
    onAddEndpoint: () -> Unit,
    onDeleteEndpoint: (Int) -> Unit,
    onEndpointClick: (Int) -> Unit,
    onCheckStatus: (Int) -> Unit,
) {
    Surface(
        color = MaterialTheme.colorScheme.surfaceVariant,
        shape = RoundedCornerShape(12.dp),
        modifier = Modifier.fillMaxWidth(),
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Column {
                    Text(
                        text = wallet.name,
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold,
                        modifier = Modifier.clickable { onRename() },
                    )
                    Text(
                        text = wallet.networkId.uppercase(),
                        style = MaterialTheme.typography.labelSmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
                    )
                }
                IconButton(onClick = onDelete) {
                    Icon(
                        painter = painterResource(id = R.drawable.ic_delete),
                        contentDescription = stringResource(R.string.delete_wallet_content_desc),
                        tint = MaterialTheme.colorScheme.error,
                        modifier = Modifier.size(20.dp),
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(16.dp))
            
            Text(
                text = stringResource(R.string.network_endpoints_label),
                style = MaterialTheme.typography.labelSmall,
                color = MaterialTheme.colorScheme.primary.copy(alpha = 0.7f)
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
            wallet.endpoints.forEachIndexed { index, endpoint ->
                val isSelected = selectedEndpointIndex == index
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clip(RoundedCornerShape(8.dp))
                        .background(if (isSelected) MaterialTheme.colorScheme.primary.copy(alpha = 0.08f) else androidx.compose.ui.graphics.Color.Transparent)
                        .clickable { onEndpointClick(index) }
                        .padding(horizontal = 8.dp, vertical = 6.dp)
                ) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text(
                            text = (if (endpoint.useTls) "https://" else "http://") + "${endpoint.host}:${endpoint.port}",
                            style = MaterialTheme.typography.bodySmall.copy(fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace),
                            color = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        if (wallet.endpoints.size > 1) {
                            Icon(
                                painter = painterResource(id = R.drawable.ic_delete),
                                contentDescription = stringResource(R.string.remove_endpoint_content_desc),
                                modifier = Modifier.size(16.dp).clickable { onDeleteEndpoint(index) },
                                tint = MaterialTheme.colorScheme.error.copy(alpha = 0.6f)
                            )
                        }
                    }
                    if (isSelected) {
                        Spacer(Modifier.height(4.dp))
                        TextButton(
                            onClick = { onCheckStatus(index) },
                            contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 12.dp, vertical = 0.dp),
                            modifier = Modifier.height(28.dp).align(Alignment.Start)
                        ) {
                            Icon(painterResource(R.drawable.ic_check_circle), null, modifier = Modifier.size(14.dp))
                            Spacer(Modifier.width(6.dp))
                            Text(stringResource(R.string.check_status_button_caps), fontSize = 10.sp, fontWeight = FontWeight.Bold)
                        }
                    }
                }
            }
            
            TextButton(
                onClick = onAddEndpoint,
                modifier = Modifier.align(Alignment.End)
            ) {
                Icon(painterResource(R.drawable.ic_add), null, modifier = Modifier.size(14.dp))
                Spacer(Modifier.width(4.dp))
                Text(stringResource(R.string.add_endpoint_button_caps), fontSize = 11.sp)
            }
            
            HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp), color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f))
            
            Text(
                text = stringResource(R.string.accounts_count_label, wallet.accounts.size),
                style = MaterialTheme.typography.labelSmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f),
            )
        }
    }
}
