/*
 * 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 android.content.ClipData
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
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.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsPadding
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.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.ClipEntry
import androidx.compose.ui.platform.LocalClipboard
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.launch
import androidx.compose.ui.res.stringResource
import swiss.qpq.gajumobile.R
import swiss.qpq.gajumobile.ui.components.GajuButton
import swiss.qpq.gajumobile.ui.components.GajuHeader
import swiss.qpq.gajumobile.ui.components.GajuTextField
import swiss.qpq.gajumaru.core.encoding.QR
import swiss.qpq.gajumaru.core.formatting.GajuFormat
import java.math.BigInteger
import java.net.URLEncoder

@Composable
fun QRReceiveScreen(
    account: swiss.qpq.gajumobile.data.models.Account,
    networkId: String,
    balanceFormat: GajuFormat.Type,
    balanceUnit: GajuFormat.Unit,
    onDone: () -> Unit,
) {
    var amountStr by remember { mutableStateOf(value = "") }
    var payload by remember { mutableStateOf(value = "") }
    var isGenerated by remember { mutableStateOf(value = false) }
    val clipboard = LocalClipboard.current
    val scope = rememberCoroutineScope()
    val gridsUrlLabel = stringResource(R.string.grids_url_label_clipboard)

    val amountPucks = remember(amountStr) {
        try {
            if (amountStr.isBlank()) BigInteger.ZERO else BigInteger(GajuFormat.read(amountStr))
        } catch (_: Exception) {
            BigInteger.ZERO
        }
    }

    val formattedAmount = remember(amountPucks, balanceFormat, balanceUnit) {
        GajuFormat.amount(GajuFormat.standardSpec(balanceFormat, balanceUnit), amountPucks)
    }

    val generatedUrl = remember(amountPucks, payload, account.gajuId, networkId) {
        try {
            val baseUrl = "grids://$networkId/1/s/${account.gajuId}"
            val queryParams = mutableListOf<String>()
            
            if (amountPucks > BigInteger.ZERO) {
                queryParams.add("a=$amountPucks")
            }
            
            if (payload.isNotBlank()) {
                val p = URLEncoder.encode(payload, "UTF-8")
                queryParams.add("p=$p")
            }
            
            if (queryParams.isEmpty()) {
                baseUrl
            } else {
                baseUrl + "?" + queryParams.joinToString("&")
            }
        } catch (_: Exception) {
            ""
        }
    }

    val qrMatrix = remember(generatedUrl) {
        if (generatedUrl.isNotEmpty()) {
            try { QR.encode(generatedUrl) } catch (_: Exception) { null }
        } else {
            null
        }
    }

    Scaffold(
        modifier = Modifier.fillMaxSize(),
        bottomBar = {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .windowInsetsPadding(WindowInsets.navigationBars)
                    .padding(24.dp),
            ) {
                GajuButton(
                    text = if (isGenerated) stringResource(id = R.string.edit_button_caps) else stringResource(id = R.string.back_button_caps),
                    onClick = { if (isGenerated) isGenerated = false else onDone() },
                    modifier = Modifier.weight(1f),
                    containerColor = MaterialTheme.colorScheme.secondary,
                    contentColor = MaterialTheme.colorScheme.onSecondary,
                )
                Spacer(modifier = Modifier.width(16.dp))
                GajuButton(
                    text = if (isGenerated) stringResource(id = R.string.done_button_caps) else stringResource(id = R.string.generate_button_caps),
                    onClick = { if (isGenerated) onDone() else isGenerated = true },
                    modifier = Modifier.weight(1f),
                )
            }
        },
    ) { innerPadding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(MaterialTheme.colorScheme.background)
                .padding(innerPadding)
                .padding(horizontal = 24.dp)
                .verticalScroll(rememberScrollState()),
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {
            GajuHeader()
            
            Text(
                text = if (isGenerated) stringResource(id = R.string.transfer_request_title) else stringResource(id = R.string.receive_title),
                color = MaterialTheme.colorScheme.onBackground,
                fontSize = 24.sp,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.padding(vertical = 16.dp),
            )

            if (!isGenerated) {
                // Input Phase
                Column(modifier = Modifier.fillMaxWidth()) {
                    Text(stringResource(id = R.string.recipient_label), color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 14.sp)
                    Spacer(modifier = Modifier.height(4.dp))
                    Surface(
                        color = MaterialTheme.colorScheme.surfaceVariant,
                        shape = RoundedCornerShape(8.dp),
                        modifier = Modifier.fillMaxWidth(),
                    ) {
                        Column(modifier = Modifier.padding(12.dp)) {
                            Text(
                                text = account.label,
                                color = MaterialTheme.colorScheme.primary,
                                fontWeight = FontWeight.Bold,
                                fontSize = 16.sp,
                            )
                            Text(
                                text = account.gajuId,
                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                                fontSize = 12.sp,
                                fontFamily = FontFamily.Monospace,
                            )
                        }
                    }
                }

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

                // Amount (String input)
                val unitLabel = if (balanceUnit == GajuFormat.Unit.GAJU) "GAJU" else "PUCK"
                GajuTextField(
                    value = amountStr,
                    onValueChange = { amountStr = it },
                    label = stringResource(id = R.string.requested_amount_label),
                    placeholder = stringResource(id = R.string.requested_amount_placeholder),
                    modifier = Modifier.fillMaxWidth(),
                    trailingIcon = { Text(unitLabel, color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.Bold, fontSize = 12.sp) },
                    singleLine = true,
                )

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

                GajuTextField(
                    value = payload,
                    onValueChange = { payload = it },
                    label = stringResource(id = R.string.payload_optional_label),
                    placeholder = stringResource(id = R.string.payload_optional_placeholder),
                    modifier = Modifier.fillMaxWidth(),
                )
            } else {
                // Display Phase
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(MaterialTheme.colorScheme.surfaceVariant, RoundedCornerShape(12.dp))
                        .padding(16.dp),
                ) {
                    DetailRow(label = stringResource(id = R.string.recipient_label), value = account.label)
                    Text(
                        text = account.gajuId,
                        color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f),
                        fontSize = 11.sp,
                        fontFamily = FontFamily.Monospace,
                    )
                    HorizontalDivider(
                        modifier = Modifier.padding(vertical = 8.dp),
                        color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f),
                    )
                    DetailRow(label = stringResource(id = R.string.amount_label), value = formattedAmount)
                    if (payload.isNotBlank()) {
                        HorizontalDivider(
                            modifier = Modifier.padding(vertical = 8.dp),
                            color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f),
                        )
                        DetailRow(label = stringResource(id = R.string.message_label), value = payload)
                    }
                }

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

                Surface(
                    modifier = Modifier.size(280.dp),
                    color = Color.White,
                    shape = RoundedCornerShape(16.dp),
                ) {
                    Box(contentAlignment = Alignment.Center, modifier = Modifier.padding(16.dp)) {
                        if (qrMatrix != null) {
                            QRCanvas(qrMatrix)
                        } else {
                            Icon(
                                painter = painterResource(id = R.drawable.ic_qr_code), 
                                contentDescription = stringResource(id = R.string.qr_code_content_desc),
                                modifier = Modifier.size(180.dp),
                                tint = Color.Black.copy(alpha = 0.1f),
                            )
                        }
                    }
                }

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

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween,
                ) {
                    Text(
                        text = stringResource(id = R.string.grids_url_label),
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        fontSize = 14.sp,
                    )
                    Icon(
                        painter = painterResource(id = R.drawable.ic_content_copy),
                        contentDescription = stringResource(id = R.string.copy_url_content_desc),
                        modifier = Modifier
                            .size(20.dp)
                            .clickable {
                                scope.launch {
                                    clipboard.setClipEntry(ClipEntry(ClipData.newPlainText(gridsUrlLabel, generatedUrl)))
                                }
                            },
                        tint = MaterialTheme.colorScheme.primary,
                    )
                }
                Spacer(modifier = Modifier.height(8.dp))
                Surface(
                    color = MaterialTheme.colorScheme.surfaceVariant,
                    shape = RoundedCornerShape(8.dp),
                    modifier = Modifier.fillMaxWidth(),
                ) {
                    Text(
                        text = generatedUrl,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        fontSize = 12.sp,
                        fontFamily = FontFamily.Monospace,
                        modifier = Modifier.padding(12.dp),
                    )
                }

                Spacer(modifier = Modifier.height(24.dp))
                Text(
                    text = stringResource(id = R.string.scan_to_send_hint),
                    color = MaterialTheme.colorScheme.onBackground,
                    fontSize = 14.sp,
                    fontWeight = FontWeight.Light,
                )
            }
            
            Spacer(modifier = Modifier.height(32.dp))
        }
    }
}

@Composable
fun DetailRow(label: String, value: String) {
    Column(modifier = Modifier.fillMaxWidth()) {
        Text(text = label, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.primary.copy(alpha = 0.7f))
        Text(text = value, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, fontWeight = FontWeight.Bold)
    }
}

@Composable
fun QRCanvas(matrix: Array<BooleanArray>) {
    val size = matrix.size
    Canvas(modifier = Modifier.fillMaxSize()) {
        val cellSize = this.size.width / size
        val offsetX = (this.size.width - (cellSize * size)) / 2
        val offsetY = (this.size.height - (cellSize * size)) / 2

        for (y in 0 until size) {
            for (x in 0 until size) {
                if (matrix[y][x]) {
                    drawRect(
                        color = Color.Black,
                        topLeft = androidx.compose.ui.geometry.Offset(offsetX + (x * cellSize), offsetY + (y * cellSize)),
                        size = androidx.compose.ui.geometry.Size(cellSize, cellSize),
                    )
                }
            }
        }
    }
}
