package com.fabledsword.minstrel.settings.ui

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.fabledsword.minstrel.models.ListenBrainzStatus

@Composable
fun ListenBrainzCard(viewModel: ListenBrainzViewModel = hiltViewModel()) {
    val state by viewModel.state.collectAsStateWithLifecycle()
    ElevatedCard(modifier = Modifier.fillMaxWidth()) {
        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp),
        ) {
            Text(
                text = "ListenBrainz",
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.onSurface,
            )
            Text(
                text = "Send your plays to ListenBrainz so you can keep your " +
                    "scrobble history portable. Get a token at " +
                    "listenbrainz.org/profile — it's stored encrypted on " +
                    "the server and never read back.",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
            )
            if (state.isLoading) {
                Box(
                    modifier = Modifier.fillMaxWidth().padding(16.dp),
                    contentAlignment = Alignment.Center,
                ) { CircularProgressIndicator() }
            } else {
                ListenBrainzForm(
                    status = state.status,
                    tokenInput = state.tokenInput,
                    isSaving = state.isSaving,
                    message = state.message,
                    onTokenChange = viewModel::setTokenInput,
                    onSaveToken = viewModel::saveToken,
                    onSetEnabled = viewModel::setEnabled,
                )
            }
        }
    }
}

@Composable
private fun ListenBrainzForm(
    status: ListenBrainzStatus?,
    tokenInput: String,
    isSaving: Boolean,
    message: String?,
    onTokenChange: (String) -> Unit,
    onSaveToken: () -> Unit,
    onSetEnabled: (Boolean) -> Unit,
) {
    TokenField(
        tokenInput = tokenInput,
        tokenSet = status?.tokenSet == true,
        onChange = onTokenChange,
    )
    Spacer(Modifier.height(4.dp))
    SaveTokenButton(
        isSaving = isSaving,
        enabled = !isSaving && tokenInput.isNotBlank(),
        onClick = onSaveToken,
    )
    EnabledRow(status = status, isSaving = isSaving, onSetEnabled = onSetEnabled)
    if (message != null) {
        Text(
            text = message,
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
        )
    }
}

@Composable
private fun TokenField(tokenInput: String, tokenSet: Boolean, onChange: (String) -> Unit) {
    OutlinedTextField(
        value = tokenInput,
        onValueChange = onChange,
        label = { Text(if (tokenSet) "Replace token" else "Token") },
        placeholder = { Text(if (tokenSet) "Token saved" else "") },
        modifier = Modifier.fillMaxWidth(),
        singleLine = true,
        visualTransformation = PasswordVisualTransformation(),
    )
}

@Composable
private fun SaveTokenButton(isSaving: Boolean, enabled: Boolean, onClick: () -> Unit) {
    Button(
        onClick = onClick,
        enabled = enabled,
        modifier = Modifier.fillMaxWidth(),
    ) {
        if (isSaving) {
            CircularProgressIndicator(
                modifier = Modifier.size(16.dp),
                strokeWidth = 2.dp,
                color = MaterialTheme.colorScheme.onPrimary,
            )
            Spacer(Modifier.size(8.dp))
        }
        Text(if (isSaving) "Saving…" else "Save token")
    }
}

@Composable
private fun EnabledRow(
    status: ListenBrainzStatus?,
    isSaving: Boolean,
    onSetEnabled: (Boolean) -> Unit,
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween,
    ) {
        Column(modifier = Modifier.padding(end = 12.dp)) {
            Text(
                text = "Send my plays to ListenBrainz",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurface,
            )
            if (status?.lastScrobbledAt != null) {
                Text(
                    text = "Last scrobble: ${status.lastScrobbledAt}",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
            }
        }
        Switch(
            checked = status?.enabled == true,
            onCheckedChange = onSetEnabled,
            enabled = !isSaving && status?.tokenSet == true,
        )
    }
}
