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

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
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.text.style.TextOverflow
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.HouseDto
import com.runicgateway.app.ui.components.PillTone
import com.runicgateway.app.ui.components.ShardCard
import com.runicgateway.app.ui.components.StatusPill

/** The public "falling houses" (IDOC) board (PLAN.md §6.2), live via `house.decay`. */
@Composable
fun HousesScreen(
    modifier: Modifier = Modifier,
    viewModel: HousesViewModel = hiltViewModel(),
) {
    val state by viewModel.state.collectAsStateWithLifecycle()
    val connected by viewModel.connected.collectAsStateWithLifecycle()

    LiveBoardScreen(
        emptyMessage = stringResource(R.string.houses_empty),
        state = state,
        connected = connected,
        onRetry = viewModel::load,
        key = { it.serial },
        modifier = modifier,
    ) { house -> HouseCard(house) }
}

@Composable
private fun HouseCard(house: HouseDto) {
    ShardCard(Modifier.fillMaxWidth()) {
        Column(Modifier.padding(16.dp)) {
            Row(Modifier.fillMaxWidth()) {
                Text(
                    text = house.name?.takeIf { it.isNotBlank() }
                        ?: house.region
                        ?: stringResource(R.string.houses_fallback_name),
                    style = MaterialTheme.typography.titleMedium,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    modifier = Modifier.weight(1f),
                )
                StatusPill(
                    text = stringResource(R.string.houses_idoc_badge),
                    tone = PillTone.Danger,
                )
            }
            val where = listOfNotNull(
                house.region,
                house.map,
                house.x?.let { "(${house.x}, ${house.y})" },
            ).joinToString(" · ")
            if (where.isNotBlank()) {
                Text(
                    text = where,
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.padding(top = 6.dp),
                )
            }
        }
    }
}
