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

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.Button
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
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.TrustedDeviceDto
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

/**
 * Account → Trusted Devices (TRUSTED_DEVICES_MFA.md): the devices allowed to skip
 * the TOTP step at login. Trust the current device, revoke one, or untrust all. The
 * server re-checks ownership on every call; this screen just renders the outcomes.
 */
@Composable
fun TrustedDevicesScreen(
    modifier: Modifier = Modifier,
    viewModel: TrustedDevicesViewModel = hiltViewModel(),
) {
    val state by viewModel.state.collectAsStateWithLifecycle()

    Column(
        modifier = modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
            .padding(16.dp),
    ) {
        Text(
            stringResource(R.string.trusted_devices_title),
            style = MaterialTheme.typography.titleLarge,
        )
        Text(
            stringResource(R.string.trusted_devices_subtitle),
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
            modifier = Modifier.padding(top = 4.dp),
        )

        state.feedback?.let { fb ->
            Text(
                text = stringResource(fb.messageRes),
                color = if (fb.ok) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.error,
                style = MaterialTheme.typography.bodyMedium,
                modifier = Modifier.padding(top = 12.dp),
            )
        }

        when (val devices = state.devices) {
            is UiState.Loading -> LoadingView(Modifier.padding(top = 32.dp))
            is UiState.Error -> ErrorView(devices.kind, onRetry = viewModel::load, modifier = Modifier.padding(top = 32.dp))
            is UiState.Success -> {
                if (devices.data.isEmpty()) {
                    Text(
                        stringResource(R.string.trusted_devices_empty),
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.padding(top = 24.dp),
                    )
                } else {
                    devices.data.forEach { device ->
                        TrustedDeviceRow(device, state.busy, onRevoke = { viewModel.revoke(device.id) })
                    }
                }

                HorizontalDivider(Modifier.padding(vertical = 20.dp))

                Button(
                    onClick = viewModel::trustThisDevice,
                    enabled = !state.busy,
                    modifier = Modifier.fillMaxWidth(),
                ) { Text(stringResource(R.string.trusted_devices_trust_this)) }

                if (devices.data.isNotEmpty()) {
                    OutlinedButton(
                        onClick = viewModel::revokeAll,
                        enabled = !state.busy,
                        modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
                    ) { Text(stringResource(R.string.trusted_devices_untrust_all)) }
                }
            }
        }
    }
}

@Composable
private fun TrustedDeviceRow(device: TrustedDeviceDto, busy: Boolean, onRevoke: () -> Unit) {
    ShardCard(Modifier.fillMaxWidth().padding(top = 12.dp)) {
        Row(
            Modifier.fillMaxWidth().padding(16.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Column(Modifier.weight(1f)) {
                Text(
                    text = device.deviceName?.takeIf { it.isNotBlank() }
                        ?: device.platform?.replaceFirstChar { it.uppercase() }
                        ?: stringResource(R.string.trusted_devices_unknown),
                    style = MaterialTheme.typography.bodyLarge,
                )
                device.lastUsedAt?.let {
                    Text(
                        stringResource(R.string.trusted_devices_last_used, it),
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                    )
                }
            }
            TextButton(onClick = onRevoke, enabled = !busy) {
                Text(stringResource(R.string.trusted_devices_revoke))
            }
        }
    }
}
