/*
 * Copyright 2025 Mifos Initiative
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 *
 * See https://github.com/openMF/mobile-wallet/blob/master/LICENSE.md
 */
package org.mifospay.feature.send.interbank.screens

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.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ListItem
import androidx.compose.material3.ListItemDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import mobile_wallet.feature.send_interbank.generated.resources.Res
import mobile_wallet.feature.send_interbank.generated.resources.feature_send_interbank_account
import mobile_wallet.feature.send_interbank.generated.resources.feature_send_interbank_account_type
import mobile_wallet.feature.send_interbank.generated.resources.feature_send_interbank_balance
import mobile_wallet.feature.send_interbank.generated.resources.feature_send_interbank_choose_account_to_send
import mobile_wallet.feature.send_interbank.generated.resources.feature_send_interbank_no_accounts
import mobile_wallet.feature.send_interbank.generated.resources.feature_send_interbank_no_accounts_available
import mobile_wallet.feature.send_interbank.generated.resources.feature_send_interbank_office
import mobile_wallet.feature.send_interbank.generated.resources.feature_send_interbank_oops
import mobile_wallet.feature.send_interbank.generated.resources.feature_send_interbank_select_account
import mobile_wallet.feature.send_interbank.generated.resources.feature_send_interbank_select_your_account
import org.jetbrains.compose.resources.stringResource
import org.jetbrains.compose.ui.tooling.preview.Preview
import org.mifospay.core.common.CurrencyFormatter
import org.mifospay.core.designsystem.component.MifosCard
import org.mifospay.core.designsystem.component.MifosScaffold
import org.mifospay.core.designsystem.component.MifosTopBar
import org.mifospay.core.designsystem.icon.MifosIcons
import org.mifospay.core.designsystem.theme.MifosTheme
import org.mifospay.core.model.account.Account
import org.mifospay.core.model.savingsaccount.Currency
import org.mifospay.core.model.savingsaccount.Status
import org.mifospay.core.network.model.entity.templates.account.AccountType
import org.mifospay.core.ui.AvatarBox
import org.mifospay.core.ui.EmptyContentScreen
import org.mifospay.core.ui.MifosProgressIndicator
import template.core.base.designsystem.theme.KptTheme

@Composable
fun SelectAccountScreen(
    accounts: List<Account>,
    isLoading: Boolean,
    error: String?,
    onAccountSelected: (Account) -> Unit,
    onBackClick: () -> Unit,
    modifier: Modifier = Modifier,
) {
    MifosScaffold(
        modifier = modifier,
        topBar = {
            MifosTopBar(
                topBarTitle = stringResource(Res.string.feature_send_interbank_select_account),
                backPress = onBackClick,
            )
        },
        containerColor = KptTheme.colorScheme.background,
    ) { paddingValues ->
        when {
            isLoading -> {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues),
                    contentAlignment = Alignment.Center,
                ) {
                    MifosProgressIndicator()
                }
            }

            error != null -> {
                EmptyContentScreen(
                    title = stringResource(Res.string.feature_send_interbank_oops),
                    subTitle = error,
                    iconTint = KptTheme.colorScheme.error,
                    modifier = Modifier.padding(paddingValues),
                )
            }

            accounts.isEmpty() -> {
                EmptyContentScreen(
                    title = stringResource(Res.string.feature_send_interbank_no_accounts),
                    subTitle = stringResource(Res.string.feature_send_interbank_no_accounts_available),
                    modifier = Modifier.padding(paddingValues),
                )
            }

            else -> {
                LazyColumn(
                    modifier = modifier
                        .fillMaxSize()
                        .padding(paddingValues)
                        .padding(KptTheme.spacing.md),
                    verticalArrangement = Arrangement.spacedBy(KptTheme.spacing.md),
                ) {
                    item {
                        Text(
                            text = stringResource(Res.string.feature_send_interbank_select_your_account),
                            style = KptTheme.typography.headlineSmall,
                            fontWeight = FontWeight.SemiBold,
                        )
                        Text(
                            text = stringResource(Res.string.feature_send_interbank_choose_account_to_send),
                            style = KptTheme.typography.bodyMedium,
                            color = KptTheme.colorScheme.onSurfaceVariant,
                            modifier = Modifier.padding(top = KptTheme.spacing.xs),
                        )
                    }

                    items(accounts) { account ->
                        AccountSelectionCard(
                            modifier = Modifier.fillMaxWidth(),
                            account = account,
                            onClick = { onAccountSelected(account) },
                        )
                    }

                    item {
                        Box(modifier = Modifier.padding(vertical = KptTheme.spacing.md))
                    }
                }
            }
        }
    }
}

@Composable
private fun AccountSelectionCard(
    account: Account,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
) {
    MifosCard(
        colors = CardDefaults.cardColors(KptTheme.colorScheme.background),
        shape = KptTheme.shapes.medium,
        modifier = modifier
            .clickable(onClick = onClick)
            .fillMaxWidth()
            .padding(KptTheme.spacing.xs),
    ) {
        val accountBalance = CurrencyFormatter.format(
            balance = account.balance,
            currencyCode = account.currency.code,
            maximumFractionDigits = null,
        )
        ListItem(
            headlineContent = {
                Text(
                    text = account.clientName,
                    fontWeight = FontWeight.SemiBold,
                )
            },
            supportingContent = {
                Column(
                    verticalArrangement = Arrangement.spacedBy(4.dp),
                ) {
                    Text(
                        text = stringResource(
                            Res.string.feature_send_interbank_balance,
                            accountBalance,
                        ),
                        style = KptTheme.typography.bodySmall,
                    )
                    Text(
                        text = stringResource(
                            Res.string.feature_send_interbank_account,
                            account.name,
                            account.number,
                        ),
                        style = KptTheme.typography.bodySmall,
                    )
                    Text(
                        text = stringResource(
                            Res.string.feature_send_interbank_office,
                            account.officeName ?: "",
                        ),
                        style = KptTheme.typography.bodySmall,
                    )
                    Text(
                        text = stringResource(
                            Res.string.feature_send_interbank_account_type,
                            account.accountType?.value ?: "",
                        ),
                        style = KptTheme.typography.bodySmall,
                    )
                    Spacer(modifier = Modifier.height(KptTheme.spacing.xs))
                }
            },
            leadingContent = {
                AvatarBox(
                    icon = MifosIcons.Bank,
                    backgroundColor = KptTheme.colorScheme.primaryContainer,
                )
            },
            colors = ListItemDefaults.colors(
                containerColor = Color.Transparent,
            ),
        )
    }
}

@Preview
@Composable
fun SelectAccountScreenPreview() {
    MifosTheme {
        val mockAccounts = listOf(
            Account(
                id = 1L,
                name = "WALLET",
                clientName = "ALEJANDRO ESCUTIA",
                number = "00000002",
                balance = 5000.50,
                productId = 1L,
                officeName = "SAN JUAN OZOLOTEPEC",
                accountType = org.mifospay.core.model.savingsaccount.AccountType(
                    id = 1L,
                    code = "savingsAccountType.savings",
                    value = "Savings",
                ),
                currency = Currency(
                    code = "USD",
                    name = "US Dollar",
                    displaySymbol = "$",
                    displayLabel = "US Dollar ($)",
                    decimalPlaces = 2,
                    inMultiplesOf = 10,
                    nameCode = "USD",
                ),
                status = Status(
                    id = 300,
                    code = "savingsAccountStatusType.active",
                    value = "Active",
                    submittedAndPendingApproval = false,
                    approved = true,
                    rejected = false,
                    withdrawnByApplicant = false,
                    active = true,
                    closed = false,
                    prematureClosed = false,
                    transferInProgress = false,
                    transferOnHold = false,
                    matured = false,
                ),
            ),
            Account(
                id = 2L,
                name = "WALLET",
                number = "00000003",
                clientName = "JUAN PEREZ",
                balance = 3200.75,
                productId = 1L,
                officeName = "SAN JUAN OZOLOTEPEC",
                accountType = org.mifospay.core.model.savingsaccount.AccountType(
                    id = 1L,
                    code = "savingsAccountType.savings",
                    value = "Savings",
                ),
                currency = Currency(
                    code = "USD",
                    name = "US Dollar",
                    displaySymbol = "$",
                    displayLabel = "US Dollar ($)",
                    decimalPlaces = 2,
                    inMultiplesOf = 10,
                    nameCode = "USD",
                ),
                status = Status(
                    id = 300,
                    code = "savingsAccountStatusType.active",
                    value = "Active",
                    submittedAndPendingApproval = false,
                    approved = true,
                    rejected = false,
                    withdrawnByApplicant = false,
                    active = true,
                    closed = false,
                    prematureClosed = false,
                    transferInProgress = false,
                    transferOnHold = false,
                    matured = false,
                ),
            ),
        )

        SelectAccountScreen(
            accounts = mockAccounts,
            isLoading = false,
            error = null,
            onAccountSelected = {},
            onBackClick = {},
        )
    }
}

@Preview
@Composable
fun SelectAccountScreenLoadingPreview() {
    MifosTheme {
        SelectAccountScreen(
            accounts = emptyList(),
            isLoading = true,
            error = null,
            onAccountSelected = {},
            onBackClick = {},
        )
    }
}

@Preview
@Composable
fun SelectAccountScreenErrorPreview() {
    MifosTheme {
        SelectAccountScreen(
            accounts = emptyList(),
            isLoading = false,
            error = "Failed to load accounts. Please try again.",
            onAccountSelected = {},
            onBackClick = {},
        )
    }
}
