PaymentOptionDetailFragment.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.paymentoptions

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
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.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
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.platform.ComposeView
import androidx.compose.ui.platform.ViewCompositionStrategy
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels

import net.taler.merchantpos.MainViewModel
import net.taler.merchantpos.R
import net.taler.merchantpos.compose.PosOutlinedCard
import net.taler.merchantpos.compose.PosTheme

class PaymentOptionDetailFragment : Fragment()
{
    private val viewModel: MainViewModel by activityViewModels()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View =
        ComposeView(requireContext()).apply {
            setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
            val manager = viewModel.paymentOptions
            val optionId = requireArguments().getString(ARG_OPTION_ID).orEmpty()
            val option = manager.option(optionId)
            setContent {
                val summary by manager.summary.observeAsState(PaymentOptionsSummary())
                if (option == null)
                {
                    PosTheme {
                        Text(
                            text = stringResource(R.string.payment_option_unknown),
                            modifier = Modifier.padding(20.dp),
                        )
                    }
                }
                else
                {
                    val state =
                        summary.options.firstOrNull { it.id == optionId }
                            ?: PaymentOptionState(optionId)
                    PaymentOptionDetailScreen(
                        option = option,
                        state = state,
                        actions =
                            PaymentOptionActions(
                                setEnabled = { manager.setEnabled(optionId, it) },
                                refresh = manager::refresh,
                                reportFailure = manager::reportActionFailure,
                            ),
                    )
                }
            }
        }

    companion object
    {
        private const val ARG_OPTION_ID = "optionId"

        fun create(optionId: String) =
            PaymentOptionDetailFragment().apply {
                arguments = bundleOf(ARG_OPTION_ID to optionId)
            }
    }
}

@Composable
private fun PaymentOptionDetailScreen(
    option: PaymentOption,
    state: PaymentOptionState,
    actions: PaymentOptionActions,
)
{
    val name = stringResource(option.nameRes)
    val configured = option.isConfigured()
    var pending by remember { mutableStateOf<Int?>(null) }
    PosTheme {
        pending?.let { noticeRes ->
            ActivationNoticeDialog(
                noticeRes = noticeRes,
                onConfirm = {
                    pending = null
                    actions.setEnabled(true)
                },
                onDismiss = { pending = null },
            )
        }
        LazyColumn(
            modifier =
                Modifier
                    .fillMaxSize()
                    .padding(20.dp),
            verticalArrangement = Arrangement.spacedBy(14.dp),
        ) {
            item {
                DetailCard {
                    Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
                        Text(name, style = MaterialTheme.typography.titleMedium, modifier = Modifier.weight(1f))
                        if (!option.alwaysEnabled)
                        {
                            Switch(
                                checked = state.enabled,
                                onCheckedChange = { enable ->
                                    val notice = option.activationNoticeRes
                                    if (enable &&
                                        notice != null)
                                    {
                                        pending = notice
                                    }
                                    else
                                    {
                                        actions.setEnabled(enable)
                                    }
                                },
                                enabled = configured,
                                modifier = Modifier.semantics { contentDescription = name },
                            )
                        }
                    }
                    Text(
                        text = stringResource(option.descriptionRes),
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                    )
                    PaymentOptionDetails(
                        if (configured)
                        {
                            state
                        }
                        else
                        {
                            state.copy(status = PaymentOptionStatus.NotConfigured)
                        },
                    )
                }
            }
            items(if (option.id == TALER_OPTION_ID) emptyList() else state.devices, key = { it.id }) { device ->
                DeviceCard(device)
            }
            if (option.hasSettings)
            {
                item {
                    DetailCard(title = stringResource(option.settingsTitleRes)) {
                        option.DetailContent(state, actions)
                    }
                }
            }
        }
    }
}

/** Production payment-option detail UI with inert actions for offline screenshots. */
@Composable
internal fun PaymentOptionDetailScreenshotContent(
    option: PaymentOption,
    state: PaymentOptionState,
)
{
    PaymentOptionDetailScreen(
        option = option,
        state = state,
        actions =
            PaymentOptionActions(
                setEnabled = {},
                refresh = {},
                reportFailure = {},
            ),
    )
}

@Composable
private fun DetailCard(
    title: String? = null,
    content: @Composable () -> Unit,
)
{
    PosOutlinedCard(contentPadding = PaddingValues(16.dp)) { contentPadding ->
        Column(
            modifier = Modifier.padding(contentPadding),
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            if (title != null) Text(title, style = MaterialTheme.typography.titleMedium)
            content()
        }
    }
}