/*
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
package com.runicgateway.app.ui.player

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
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.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.runicgateway.app.R
import com.runicgateway.app.data.api.dto.VendorDto
import com.runicgateway.app.data.api.dto.VendorListingDto
import com.runicgateway.app.data.api.dto.VendorSaleDto
import com.runicgateway.app.ui.ErrorKind
import com.runicgateway.app.ui.UiState
import com.runicgateway.app.ui.components.ErrorView
import com.runicgateway.app.ui.components.LoadingView
import com.runicgateway.app.ui.components.ShardCard
import java.text.DateFormat
import java.util.Date

/**
 * The player's own player-vendors + recent sales (PLAN.md §6.3), text-only. Vendor
 * shops group under their game account; recent sales list across all linked
 * accounts. A down shard degrades to a per-account retry (§7).
 */
@Composable
fun VendorsScreen(
    modifier: Modifier = Modifier,
    viewModel: VendorsViewModel = hiltViewModel(),
) {
    val state by viewModel.state.collectAsStateWithLifecycle()

    when (val accounts = state.accounts) {
        is UiState.Loading -> LoadingView(modifier)
        is UiState.Error -> ErrorView(accounts.kind, onRetry = viewModel::load, modifier = modifier)
        is UiState.Success -> Column(
            modifier = modifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            SalesCard(state.sales)

            if (accounts.data.isEmpty()) {
                Text(
                    stringResource(R.string.player_vendors_no_accounts),
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
            } else {
                accounts.data.forEach { account ->
                    AccountVendors(
                        account = account,
                        vendors = state.vendors[account] ?: UiState.Loading,
                        onRetry = { viewModel.loadVendors(account) },
                    )
                }
            }
        }
    }
}

@Composable
private fun SalesCard(sales: UiState<List<VendorSaleDto>>) {
    ShardCard(Modifier.fillMaxWidth()) {
        Column(Modifier.padding(16.dp)) {
            Text(stringResource(R.string.player_sales_title), style = MaterialTheme.typography.titleMedium)
            when (sales) {
                is UiState.Loading -> Text(
                    stringResource(R.string.player_roster_loading),
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.padding(top = 8.dp),
                )
                is UiState.Error -> Text(
                    stringResource(R.string.error_server),
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.padding(top = 8.dp),
                )
                is UiState.Success -> {
                    if (sales.data.isEmpty()) {
                        Text(
                            stringResource(R.string.player_sales_empty),
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            modifier = Modifier.padding(top = 8.dp),
                        )
                    } else {
                        sales.data.forEach { SaleRow(it) }
                    }
                }
            }
        }
    }
}

@Composable
private fun SaleRow(sale: VendorSaleDto) {
    Row(Modifier.fillMaxWidth().padding(top = 10.dp), horizontalArrangement = Arrangement.SpaceBetween) {
        Column(Modifier.padding(end = 12.dp)) {
            Text(
                sale.itemType ?: stringResource(R.string.player_char_item),
                style = MaterialTheme.typography.bodyMedium,
            )
            sale.t?.let {
                Text(
                    DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(Date(it)),
                    style = MaterialTheme.typography.labelSmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
            }
        }
        Text(
            stringResource(R.string.player_gold_amount, "%,d".format(sale.price ?: 0L)),
            style = MaterialTheme.typography.bodyMedium,
        )
    }
}

@Composable
private fun AccountVendors(
    account: String,
    vendors: UiState<List<VendorDto>>,
    onRetry: () -> Unit,
) {
    Column {
        Text(
            account,
            style = MaterialTheme.typography.titleSmall,
            color = MaterialTheme.colorScheme.primary,
            modifier = Modifier.padding(vertical = 8.dp),
        )
        when (vendors) {
            is UiState.Loading -> Text(
                stringResource(R.string.player_roster_loading),
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
            )
            is UiState.Error -> VendorError(vendors.kind, onRetry)
            is UiState.Success -> {
                if (vendors.data.isEmpty()) {
                    Text(
                        stringResource(R.string.player_vendors_empty),
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                    )
                } else {
                    vendors.data.forEach { VendorCard(it) }
                }
            }
        }
    }
}

@Composable
private fun VendorError(kind: ErrorKind, onRetry: () -> Unit) {
    Row {
        Text(
            stringResource(if (kind == ErrorKind.SHARD_OFFLINE) R.string.error_shard_offline else R.string.error_server),
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
            modifier = Modifier.weight(1f),
        )
        TextButton(onClick = onRetry) { Text(stringResource(R.string.action_retry)) }
    }
}

@Composable
private fun VendorCard(vendor: VendorDto) {
    ShardCard(Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
        Column(Modifier.padding(16.dp)) {
            Text(
                vendor.shopName ?: stringResource(R.string.player_vendor_fallback),
                style = MaterialTheme.typography.titleMedium,
            )
            val meta = listOfNotNull(
                vendor.holdGold?.let { stringResource(R.string.player_vendor_hold, "%,d".format(it)) },
                vendor.map,
            ).joinToString("  ·  ")
            if (meta.isNotBlank()) {
                Text(meta, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp))
            }
            if (vendor.listings.isNotEmpty()) {
                HorizontalDivider(Modifier.padding(vertical = 8.dp))
                vendor.listings.forEach { ListingRow(it) }
            } else {
                Text(
                    stringResource(R.string.player_vendor_no_listings),
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.padding(top = 8.dp),
                )
            }
        }
    }
}

@Composable
private fun ListingRow(listing: VendorListingDto) {
    Row(Modifier.fillMaxWidth().padding(vertical = 3.dp), horizontalArrangement = Arrangement.SpaceBetween) {
        Text(
            stringResource(R.string.player_listing_item, listing.itemId ?: 0, listing.amount ?: 1),
            style = MaterialTheme.typography.bodySmall,
            modifier = Modifier.weight(1f),
        )
        Text(
            stringResource(R.string.player_gold_amount, "%,d".format(listing.price ?: 0L)),
            style = MaterialTheme.typography.bodySmall,
        )
    }
}
