OrderDetailsScreen.kt

/*
 * This file is part of GNU Taler
 * (C) 2026 Taler Systems S.A.
 *
 * GNU Taler is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 3, or (at your option) any later version.
 *
 * GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */

package net.taler.merchantpos.history

import android.content.ActivityNotFoundException
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.widget.Toast

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.OpenInNew
import androidx.compose.material.icons.automirrored.outlined.ReceiptLong
import androidx.compose.material.icons.outlined.CalendarToday
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.ContentCopy
import androidx.compose.material.icons.outlined.Info
import androidx.compose.material.icons.outlined.Link
import androidx.compose.material.icons.outlined.LocalShipping
import androidx.compose.material.icons.outlined.LocationOn
import androidx.compose.material.icons.outlined.Payments
import androidx.compose.material.icons.outlined.Refresh
import androidx.compose.material.icons.outlined.Schedule
import androidx.compose.material.icons.outlined.ShoppingCart
import androidx.compose.material.icons.outlined.Storefront
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
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.ImageBitmap
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.repeatOnLifecycle

import net.taler.common.Amount
import net.taler.common.CurrencySpecification
import net.taler.common.Location
import net.taler.common.TalerUtils.getLocalizedString
import net.taler.common.Timestamp
import net.taler.lib.android.order.OrderDetailAdditionalBlock
import net.taler.lib.android.order.OrderDetailCopyableValue
import net.taler.lib.android.order.OrderDetailDeliveryBlock
import net.taler.lib.android.order.OrderDetailMerchantBlock
import net.taler.lib.android.order.OrderDetailPaymentRow
import net.taler.lib.android.order.OrderDetailPaymentsBlock
import net.taler.lib.android.order.OrderDetailProductRow
import net.taler.lib.android.order.OrderDetailProductsBlock
import net.taler.lib.android.order.OrderDetailReorderBlock
import net.taler.lib.android.order.OrderDetailSummaryBlock
import net.taler.merchantlib.CheckPaymentResponse
import net.taler.merchantlib.MerchantUnit
import net.taler.merchantlib.OrderHistoryEntry
import net.taler.merchantlib.OrderPaymentDetails
import net.taler.merchantpos.MainViewModel
import net.taler.merchantpos.PosDestination
import net.taler.merchantpos.R
import net.taler.merchantpos.checkout.shown
import net.taler.merchantpos.payment.Payment
import net.taler.merchantpos.refund.talerRefundRemaining
import net.taler.merchantpos.showPosError

import java.net.URI
import java.text.DateFormat
import java.util.Date

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonPrimitive

import net.taler.lib.android.order.OrderDetailBalanceStrip as SharedOrderDetailBalanceStrip
import net.taler.lib.android.order.OrderDetailHeader as SharedOrderDetailHeader
import net.taler.lib.android.order.OrderDetailSection as SharedOrderDetailSection
import net.taler.lib.android.order.OrderDetailValue as SharedOrderDetailValue

@Composable
internal fun OrderDetailsRoute(
    model: MainViewModel,
    orderId: String,
    onNavigate: (PosDestination) -> Unit,
    onDeleted: () -> Unit,
)
{
    var refresh by remember(orderId) { mutableIntStateOf(0) }
    val history by model.historyManager.items.observeAsState()
    val activePayment by model.paymentManager.payment.observeAsState()
    val pendingRefund by model.refundManager.pendingRefundOrderId.observeAsState()
    val lifecycleOwner = LocalLifecycleOwner.current
    val merchantIdentity by model.configManager.merchantIdentity.observeAsState()
    val units by produceState(emptyMap(), merchantIdentity, refresh) {
        value = emptyMap()
        value = model.historyManager.fetchUnits()
    }
    val result by produceState<OrderDetailsResult>(OrderDetailsResult.Loading, orderId, refresh, lifecycleOwner) {
        // A single owner handles initial entry and returning from payment/refund screens.
        // Fetching here AND observing ON_RESUME separately restarts the initial request.
        lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) {
            value = OrderDetailsResult.Loading
            value = model.historyManager.fetchOrderDetails(orderId)
        }
    }
    // Navigation retains the ID across process recreation; history restores the action metadata.
    LaunchedEffect(orderId) {
        if (history == null &&
            model.configManager.merchantConfig != null)
        {
            model.historyManager.fetchHistory()
        }
    }
    val response = (result as? OrderDetailsResult.Success)?.response
    val item =
        (history as? HistoryResult.Success)
            ?.items
            ?.find { it.orderId == orderId }
            ?.let { if (response != null) it.withPaymentDetails(response) else it }
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    var deleting by remember { mutableStateOf(false) }
    var deleteError by remember { mutableStateOf<String?>(null) }
    deleteError?.let { message ->
        AlertDialog(
            onDismissRequest = { deleteError = null },
            title = { Text(stringResource(R.string.error_delete_order)) },
            text = {
                Text(message)
            },
            confirmButton = {
                TextButton(
                    onClick = { deleteError = null },
                ) { Text(stringResource(android.R.string.ok)) }
            },
        )
    }
    OrderDetailsScreen(
        orderId = orderId,
        item = item,
        result = result,
        currencySpec = model.configManager.currencySpec,
        units = units,
        activePayment = activePayment?.takeIf { it.orderId == orderId },
        hasPendingRefund = pendingRefund == orderId,
        onRefresh = { refresh++ },
        deleting = deleting,
        onDelete = {
            item?.let { order ->
                if (!deleting)
                {
                    scope.launch {
                        deleting = true
                        try
                        {
                            val error = model.historyManager.deleteConfirmedOrder(order)
                            if (error == null)
                            {
                                model.checkoutManager.onBackendOrderDeleted(order.orderId)
                                model.paymentManager.onOrderDeleted(order.orderId)
                                onDeleted()
                            }
                            else
                            {
                                deleteError = error
                            }
                        }
                        finally
                        {
                            deleting = false
                        }
                    }
                }
            }
        },
        onRefundTaler = {
            item?.let { model.refundManager.startRefund(it, preferTaler = true) }
            onNavigate(PosDestination.Refund)
        },
        onRefund = {
            item?.let { model.refundManager.startRefund(it) }
            onNavigate(PosDestination.Refund)
        },
        onShowPayment = {
            item?.let { model.paymentManager.resumePayment(it) }
            onNavigate(PosDestination.ProcessPayment)
        },
        onShowRefund = {
            if (item != null &&
                model.refundManager.resumeRefund(item))
            {
                onNavigate(PosDestination.RefundUri)
            }
            else
            {
                (context as? FragmentActivity)?.showPosError(R.string.refund_state_missing)
                refresh++
            }
        },
    )
}

/** Uses the available window width, so rotation and split-screen follow the same layout rules. */
@Composable
internal fun OrderDetailsScreen(
    orderId: String,
    item: OrderHistoryEntry?,
    result: OrderDetailsResult,
    currencySpec: CurrencySpecification? = null,
    activePayment: Payment? = null,
    hasPendingRefund: Boolean = false,
    onRefresh: () -> Unit = {},
    onRefund: () -> Unit = {},
    onRefundTaler: () -> Unit = onRefund,
    onDelete: () -> Unit = {},
    deleting: Boolean = false,
    onShowPayment: () -> Unit = {},
    onShowRefund: () -> Unit = {},
    units: Map<String, MerchantUnit> = emptyMap(),
)
{
    val response = (result as? OrderDetailsResult.Success)?.response
    val details = response?.paymentDetails
    val total =
        item?.totalAmount ?: details?.amount?.let { taler ->
            details.amountExternal.fold(taler) { sum, payment -> sum + payment.amount }
        }
    val status =
        when
        {
            item != null ->
            {
                if (response is CheckPaymentResponse.Claimed &&
                    !item.hasAnyRefund &&
                    !hasPendingRefund)
                {
                    HistoryStatus.PaymentClaimed
                }
                else
                {
                    historyStatus(item, hasPendingRefund, activePayment)
                }
            }

            response is CheckPaymentResponse.Paid ->
            {
                when
                {
                    response.refundPending -> HistoryStatus.RefundPending
                    response.refunded || response.refundsExternal.isNotEmpty() -> HistoryStatus.Refunded
                    else -> HistoryStatus.Paid
                }
            }

            response is CheckPaymentResponse.Claimed ->
            {
                HistoryStatus.PaymentClaimed
            }

            response is CheckPaymentResponse.Unpaid ->
            {
                HistoryStatus.Unpaid
            }

            else ->
            {
                null
            }
        }
    var deleteStep by rememberSaveable(orderId) { mutableIntStateOf(0) }
    if (deleteStep != 0)
    {
        AlertDialog(
            onDismissRequest = { deleteStep = 0 },
            title = {
                Text(
                    stringResource(
                        if (deleteStep ==
                            1)
                        {
                            R.string.order_delete
                        }
                        else
                        {
                            R.string.order_delete_final_title
                        },
                    ),
                )
            },
            text = {
                Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                    Text(orderId)
                    Text(
                        stringResource(
                            if (deleteStep ==
                                1)
                            {
                                R.string.order_delete_warning
                            }
                            else
                            {
                                R.string.order_delete_final_warning
                            },
                        ),
                    )
                }
            },
            confirmButton = {
                Button(
                    onClick = {
                        if (deleteStep == 1)
                        {
                            deleteStep = 2
                        }
                        else
                        {
                            deleteStep = 0
                            onDelete()
                        }
                    },
                    colors =
                        ButtonDefaults.buttonColors(
                            containerColor =
                                if (deleteStep ==
                                    2)
                                {
                                    MaterialTheme.colorScheme.error
                                }
                                else
                                {
                                    MaterialTheme.colorScheme.primary
                                },
                        ),
                ) {
                    Text(stringResource(if (deleteStep == 1) R.string.order_delete_continue else R.string.order_delete))
                }
            },
            dismissButton = {
                TextButton(
                    onClick = { deleteStep = 0 },
                ) { Text(stringResource(android.R.string.cancel)) }
            },
        )
    }
    val scroll = rememberScrollState()
    BoxWithConstraints(Modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter) {
        val wide = maxWidth.coerceAtMost(1200.dp) / LocalDensity.current.fontScale >= 760.dp
        Column(
            Modifier
                .widthIn(max = 1200.dp)
                .fillMaxWidth()
                .verticalScroll(scroll)
                .padding(if (wide) 24.dp else 20.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp),
        ) {
            OrderHeader(orderId, item, details, total, status, currencySpec, wide, onRefresh)
            if (result is OrderDetailsResult.Success)
            {
                val talerAmount = item?.amount ?: details?.amount
                val isPaid = response?.paid ?: (item?.paid == true)
                talerAmount?.takeIf { !isPaid && !it.isZero() }?.let { amount ->
                    OrderBalanceStrip(
                        amount = amount,
                        spec = currencySpec,
                    )
                }
            }
            when (result)
            {
                OrderDetailsResult.Loading ->
                {
                    LinearProgressIndicator(Modifier.fillMaxWidth())
                    Text(stringResource(R.string.order_details_loading), style = MaterialTheme.typography.bodyMedium)
                }

                is OrderDetailsResult.Error ->
                {
                    DetailSection(Icons.Outlined.Info, stringResource(R.string.order_details_unavailable)) {
                        Text(stringResource(R.string.order_details_load_error))
                        result.message?.takeIf { it.isNotBlank() }?.let {
                            Text(it, style = MaterialTheme.typography.bodySmall)
                        }
                        OutlinedButton(onClick = onRefresh) { Text(stringResource(R.string.order_details_retry)) }
                    }
                }

                is OrderDetailsResult.Success ->
                {
                    if (item != null)
                    {
                        FlowRow(
                            horizontalArrangement = Arrangement.spacedBy(4.dp),
                            verticalArrangement = Arrangement.spacedBy(8.dp),
                        ) {
                            if (!hasPendingRefund &&
                                !item.talerRefundRemaining().isZero())
                            {
                                Button(
                                    onClick = onRefundTaler,
                                    enabled = !deleting,
                                    contentPadding = PaddingValues(horizontal = 8.dp),
                                ) {
                                    Text(
                                        stringResource(R.string.refund_taler_button),
                                        maxLines = 1,
                                        overflow = TextOverflow.Ellipsis,
                                    )
                                }
                            }
                            if (item.hasPendingRefund ||
                                hasPendingRefund)
                            {
                                OutlinedButton(
                                    onClick = onShowRefund,
                                    enabled = !deleting,
                                    contentPadding = PaddingValues(horizontal = 8.dp),
                                ) {
                                    Text(
                                        stringResource(R.string.history_show_refund),
                                        maxLines = 1,
                                        overflow = TextOverflow.Ellipsis,
                                    )
                                }
                            }
                            if (item.paid &&
                                (item.hasExternalPayments ||
                                    item.refundable))
                            {
                                OutlinedButton(
                                    onClick = onRefund,
                                    enabled = !deleting,
                                    contentPadding = PaddingValues(horizontal = 8.dp),
                                ) {
                                    Text(
                                        stringResource(R.string.history_refund),
                                        maxLines = 1,
                                        overflow = TextOverflow.Ellipsis,
                                    )
                                }
                            }
                            if (!item.paid &&
                                activePayment?.paid != true)
                            {
                                OutlinedButton(
                                    onClick = onShowPayment,
                                    enabled = !deleting,
                                    contentPadding = PaddingValues(horizontal = 8.dp),
                                ) {
                                    Text(
                                        stringResource(R.string.history_show_payment),
                                        maxLines = 1,
                                        overflow = TextOverflow.Ellipsis,
                                    )
                                }
                            }
                            OutlinedButton(
                                onClick = { deleteStep = 1 },
                                enabled = !item.paid && activePayment?.paid != true && !deleting,
                                contentPadding = PaddingValues(horizontal = 8.dp),
                                colors =
                                    ButtonDefaults.outlinedButtonColors(
                                        disabledContainerColor = MaterialTheme.colorScheme.surfaceVariant,
                                        disabledContentColor = MaterialTheme.colorScheme.onSurfaceVariant,
                                    ),
                                border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
                            ) {
                                Text(
                                    stringResource(R.string.order_details_delete_action),
                                    maxLines = 1,
                                    overflow = TextOverflow.Ellipsis,
                                )
                            }
                        }
                        if (deleting) LinearProgressIndicator(Modifier.fillMaxWidth())
                    }
                    if (details == null)
                    {
                        DetailSection(Icons.Outlined.Info, stringResource(R.string.order_details_title)) {
                            Text(stringResource(R.string.order_details_not_provided))
                        }
                    }
                    if (wide)
                    {
                        Row(horizontalArrangement = Arrangement.spacedBy(20.dp)) {
                            Column(Modifier.weight(1.15f), verticalArrangement = Arrangement.spacedBy(16.dp)) {
                                OrderPayments(item, details, currencySpec, response?.paid == true)
                                OrderSummary(item, details)
                                OrderProducts(details, total, currencySpec, units)
                            }
                            Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(16.dp)) {
                                OrderSupportingDetails(details)
                            }
                        }
                    }
                    else
                    {
                        OrderPayments(item, details, currencySpec, response?.paid == true)
                        OrderSummary(item, details)
                        OrderProducts(details, total, currencySpec, units)
                        OrderSupportingDetails(details)
                    }
                }
            }
        }
    }
}

@Composable
private fun OrderBalanceStrip(
    amount: Amount,
    spec: CurrencySpecification?,
)
{
    SharedOrderDetailBalanceStrip(
        label = stringResource(R.string.order_details_balance),
        amount = amount.shown(spec),
    )
}

@Composable
private fun OrderHeader(
    orderId: String,
    item: OrderHistoryEntry?,
    details: OrderPaymentDetails?,
    total: Amount?,
    status: HistoryStatus?,
    spec: CurrencySpecification?,
    wide: Boolean,
    onRefresh: () -> Unit,
)
{
    SharedOrderDetailHeader(
        merchantName = details?.merchant?.name ?: stringResource(R.string.order_details_title),
        total = total?.shown(spec),
        leadingIcon = Icons.Outlined.Storefront,
        wide = wide,
        orderIdDisplay = { _ ->
            CopyableValue(stringResource(R.string.order_details_order_id), orderId, compactAction = true)
        },
        statusAndMetadata = {
            status?.let { HistoryStatusBadge(it) }
            (details?.timestamp ?: item?.timestamp)?.let {
                Text(
                    formatOrderTimestamp(it),
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
            }
        },
        trailingActions = {
            IconButton(onClick = onRefresh) {
                Icon(Icons.Outlined.Refresh, stringResource(R.string.history_refresh))
            }
        },
        footer = {
            if (item?.hasAnyRefund == true &&
                !item.totalRefundAmount.isZero())
            {
                DetailValue(stringResource(R.string.order_details_refund_total), item.totalRefundAmount.shown(spec))
            }
        },
    )
}

@Composable
private fun OrderSummary(
    item: OrderHistoryEntry?,
    details: OrderPaymentDetails?,
)
{
    val summary = details?.summary?.let { getLocalizedString(details.summaryI18n, it) } ?: item?.summary
    if (!summary.isNullOrBlank())
    {
        OrderDetailSummaryBlock(
            Icons.AutoMirrored.Outlined.ReceiptLong,
            stringResource(R.string.order_details_summary),
        ) {
            SelectionContainer { Text(summary, style = MaterialTheme.typography.bodyMedium) }
            details?.fulfillmentMessage?.takeIf { it.isNotBlank() }?.let {
                Text(
                    getLocalizedString(details.fulfillmentMessageI18n, it),
                    style = MaterialTheme.typography.bodyMedium,
                )
            }
        }
    }
}

@Composable
private fun OrderProducts(
    details: OrderPaymentDetails?,
    total: Amount?,
    spec: CurrencySpecification?,
    units: Map<String, MerchantUnit>,
)
{
    if (details == null) return
    var preview by remember { mutableStateOf<Pair<String, ImageBitmap>?>(null) }
    preview?.let { (name, bitmap) ->
        Dialog(onDismissRequest = { preview = null }, properties = DialogProperties(usePlatformDefaultWidth = false)) {
            BoxWithConstraints(Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.Center) {
                Surface(
                    Modifier.widthIn(max = 640.dp).fillMaxWidth().heightIn(max = maxHeight),
                    shape = RoundedCornerShape(16.dp),
                ) {
                    Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            Text(
                                name,
                                Modifier.weight(1f),
                                style = MaterialTheme.typography.titleMedium,
                                maxLines = 2,
                                overflow = TextOverflow.Ellipsis,
                            )
                            IconButton(
                                onClick = { preview = null },
                            ) { Icon(Icons.Outlined.Close, stringResource(R.string.product_image_close)) }
                        }
                        Image(
                            bitmap,
                            name,
                            Modifier.fillMaxWidth().weight(1f, fill = false),
                            contentScale = ContentScale.Fit,
                        )
                    }
                }
            }
        }
    }
    OrderDetailProductsBlock(
        icon = Icons.Outlined.ShoppingCart,
        title = stringResource(R.string.order_details_products),
        productCount = details.products.size,
        emptyMessage = stringResource(R.string.order_details_no_products),
        totalLabel = total?.let { stringResource(R.string.checkout_total) },
        total = total?.shown(spec),
    ) { index ->
        val product = details.products[index]
        val description = getLocalizedString(product.descriptionI18n, product.description)
        val name = product.productName?.takeIf { it.isNotBlank() } ?: description
        val bitmap by produceState<ImageBitmap?>(null, product.image) {
            value = withContext(Dispatchers.Default) { decodeProductImage(product.image) }
        }
        val thumbnail: (@Composable () -> Unit)? =
            bitmap?.let { image ->
                {
                    Image(
                        image,
                        stringResource(R.string.product_image_open, name),
                        Modifier.size(48.dp).clip(RoundedCornerShape(8.dp)).clickable { preview = name to image },
                        contentScale = ContentScale.Fit,
                    )
                }
            }
        // A sold-product price is a line total, never multiplied by its quantity again.
        OrderDetailProductRow(
            name = name,
            description = description,
            quantity = product.quantityLabel(units),
            unitPrice =
                product.unitPrice(total?.currency)?.let { unitPrice ->
                    val amount = unitPrice.amount.shown(spec)
                    val labelled =
                        if (product.pricesAreNet)
                        {
                            stringResource(
                                R.string.order_details_net_price,
                                amount,
                            )
                        }
                        else
                        {
                            amount
                        }
                    if (unitPrice.approximate) "≈ $labelled" else labelled
                },
            price =
                product.priceForCurrency(total?.currency)?.let { price ->
                    if (product.pricesAreNet)
                    {
                        stringResource(R.string.order_details_net_price, price.shown(spec))
                    }
                    else
                    {
                        price.shown(spec)
                    }
                },
            thumbnail = thumbnail,
        )
    }
}

@Composable
private fun OrderPayments(
    item: OrderHistoryEntry?,
    details: OrderPaymentDetails?,
    spec: CurrencySpecification?,
    paid: Boolean,
)
{
    val external = item?.amountExternal ?: details?.amountExternal.orEmpty()
    val taler = item?.amount ?: details?.amount
    if (external.isEmpty() &&
        taler == null)
    {
        return
    }
    OrderDetailPaymentsBlock(
        icon = Icons.Outlined.Payments,
        title = stringResource(R.string.order_details_payments),
        paymentCount = external.size + if (taler != null) 1 else 0,
    ) { index ->
        if (index < external.size)
        {
            val payment = external[index]
            OrderDetailPaymentRow(
                method = payment.method.replaceFirstChar { it.uppercase() },
                amount = payment.amount.shown(spec),
                reference = payment.transactionCode?.takeIf { it.isNotBlank() },
            )
        }
        else
        {
            val amount = requireNotNull(taler)
            OrderDetailPaymentRow(
                amount = (if (paid) amount else Amount.zero(amount.currency)).shown(spec),
                status = if (paid) null else stringResource(R.string.history_status_unpaid),
                methodContent = {
                    Image(
                        painter = painterResource(R.drawable.ic_taler_logo_brand),
                        contentDescription = stringResource(R.string.payment_option_taler),
                        modifier = Modifier.size(width = 54.dp, height = 24.dp),
                    )
                },
            )
        }
    }
}

@Composable
private fun OrderSupportingDetails(details: OrderPaymentDetails?)
{
    if (details == null) return
    val delivery = details.deliveryLocation?.orderAddress().orEmpty()
    if (delivery.isNotBlank() ||
        details.deliveryDate != null ||
        details.maxPickupTime != null)
    {
        OrderDetailDeliveryBlock(Icons.Outlined.LocalShipping, stringResource(R.string.order_details_delivery)) {
            if (delivery.isNotBlank())
            {
                DetailValue(
                    stringResource(R.string.order_details_delivery_location),
                    delivery,
                    Icons.Outlined.LocationOn,
                )
            }
            details.deliveryDate?.let {
                DetailValue(
                    stringResource(R.string.order_details_delivery_date),
                    formatOrderTimestamp(it),
                    Icons.Outlined.CalendarToday,
                )
            }
            details.maxPickupTime?.let {
                DetailValue(
                    stringResource(R.string.order_details_pickup_time),
                    formatOrderTimestamp(it),
                    Icons.Outlined.Schedule,
                )
            }
        }
    }
    details.publicReorderUrl?.takeIf { it.isNotBlank() }?.let { url ->
        OrderDetailReorderBlock(Icons.Outlined.Link, stringResource(R.string.order_details_reorder)) {
            Text(stringResource(R.string.order_details_reorder_hint), style = MaterialTheme.typography.bodyMedium)
            CopyableValue(stringResource(R.string.order_details_reorder_link), url, isLink = isOrderWebUrl(url))
        }
    }
    val extras =
        details.extra
            .orEmpty()
            .filterKeys { !it.startsWith("$") }
            .filterValues { it !is JsonNull }
    val fulfillmentUrl = details.fulfillmentUrl?.takeIf { it.isNotBlank() }
    if (extras.isNotEmpty() ||
        fulfillmentUrl != null ||
        details.payDeadline != null ||
        details.refundDeadline != null)
    {
        OrderDetailAdditionalBlock(Icons.Outlined.Info, stringResource(R.string.order_details_additional)) {
            fulfillmentUrl?.let { url ->
                CopyableValue(stringResource(R.string.order_details_fulfillment_link), url, isLink = isOrderWebUrl(url))
            }
            details.payDeadline?.let {
                DetailValue(
                    stringResource(R.string.order_details_pay_deadline),
                    formatOrderTimestamp(it),
                )
            }
            details.refundDeadline?.let {
                DetailValue(stringResource(R.string.order_details_refund_deadline), formatOrderTimestamp(it))
            }
            extras.forEach { (key, value) ->
                DetailValue(key.replace('_', ' '), if (value is JsonPrimitive) value.content else value.toString())
            }
        }
    }
    details.merchant?.let { merchant ->
        OrderDetailMerchantBlock(Icons.Outlined.Storefront, stringResource(R.string.order_details_merchant)) {
            Text(merchant.name, style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Medium)
            merchant.address
                ?.orderAddress()
                ?.takeIf {
                    it.isNotBlank()
                }?.let { Text(it, style = MaterialTheme.typography.bodyMedium) }
            merchant.jurisdiction?.orderAddress()?.takeIf { it.isNotBlank() }?.let {
                DetailValue(stringResource(R.string.order_details_jurisdiction), it)
            }
            merchant.email?.takeIf { it.isNotBlank() }?.let {
                CopyableValue(
                    stringResource(R.string.order_details_email),
                    it,
                )
            }
            merchant.website?.takeIf { it.isNotBlank() }?.let {
                CopyableValue(stringResource(R.string.order_details_website), it, isLink = isOrderWebUrl(it))
            }
        }
    }
}

@Composable
private fun DetailSection(
    icon: ImageVector,
    title: String,
    content: @Composable ColumnScope.() -> Unit,
)
{
    SharedOrderDetailSection(icon, title, content = content)
}

@Composable
private fun DetailValue(
    label: String,
    value: String,
    icon: ImageVector? = null,
)
{
    SharedOrderDetailValue(label, value, icon)
}

@Composable
private fun CopyableValue(
    label: String,
    value: String,
    isLink: Boolean = false,
    compactAction: Boolean = false,
)
{
    val context = LocalContext.current
    OrderDetailCopyableValue(
        label = label,
        value = value,
        isLink = isLink,
        compactAction = compactAction,
        openAction = {
            IconButton(onClick = { openOrderUrl(context, value) }) {
                Icon(Icons.AutoMirrored.Outlined.OpenInNew, stringResource(R.string.order_details_open_link))
            }
        },
        copyAction = {
            IconButton(
                onClick = {
                    context
                        .getSystemService(
                            ClipboardManager::class.java,
                        ).setPrimaryClip(ClipData.newPlainText(label, value))
                    Toast.makeText(context, R.string.order_details_copied, Toast.LENGTH_SHORT).show()
                },
                modifier = if (compactAction) Modifier.size(48.dp) else Modifier
            ) {
                Icon(Icons.Outlined.ContentCopy, stringResource(R.string.order_details_copy, label))
            }
        },
    )
}

internal fun Location.orderAddress(): String =
    buildList {
        addAll(addressLines.orEmpty())
        addAll(listOfNotNull(buildingName, listOfNotNull(street, buildingNumber).joinToString(" ")))
        add(listOfNotNull(postCode, town).joinToString(" "))
        addAll(listOfNotNull(townLocation, district, countrySubdivision, country))
    }.filter { it.isNotBlank() }.distinct().joinToString("\n")

@Composable
private fun formatOrderTimestamp(timestamp: Timestamp): String =
    if (timestamp == Timestamp.never())
    {
        stringResource(R.string.never_expires)
    }
    else
    {
        DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(Date(timestamp.ms))
    }

internal fun isOrderWebUrl(value: String): Boolean =
    runCatching {
        val uri = URI(value)
        (uri.scheme.equals("https", true) || uri.scheme.equals("http", true)) && !uri.host.isNullOrBlank()
    }.getOrDefault(false)

private fun openOrderUrl(
    context: Context,
    url: String,
)
{
    if (!isOrderWebUrl(url)) return
    try
    {
        context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
    }
    catch (_: ActivityNotFoundException)
    {
        Toast.makeText(context, R.string.order_details_open_failed, Toast.LENGTH_SHORT).show()
    }
}