package com.anypreta.bountyboard.ui.developer

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.EmojiEvents
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import com.anypreta.bountyboard.data.AppContainer
import com.anypreta.bountyboard.data.model.LeaderboardEntry
import com.anypreta.bountyboard.di.LocalAppContainer
import com.anypreta.bountyboard.di.containerVMFactory
import com.anypreta.bountyboard.ui.components.BBAvatar
import com.anypreta.bountyboard.ui.components.BBCard
import com.anypreta.bountyboard.ui.components.BountyChip
import com.anypreta.bountyboard.ui.components.EmptyState
import com.anypreta.bountyboard.ui.components.ScreenState
import com.anypreta.bountyboard.ui.theme.BB
import com.anypreta.bountyboard.ui.theme.Fraunces
import kotlinx.coroutines.launch

class LeaderboardViewModel(private val container: AppContainer) : ViewModel() {

    var loading by mutableStateOf(true)
        private set
    var error by mutableStateOf<String?>(null)
        private set
    var entries by mutableStateOf<List<LeaderboardEntry>>(emptyList())
        private set

    init {
        load()
    }

    fun load() {
        loading = true; error = null
        viewModelScope.launch {
            try {
                val r = container.repo.call { leaderboard() }
                entries = r.items()
            } catch (e: Exception) {
                error = e.message
            } finally {
                loading = false
            }
        }
    }
}

@Composable
fun LeaderboardScreen(onOpenProfile: (String) -> Unit) {
    val container = LocalAppContainer.current
    val vm: LeaderboardViewModel = viewModel(factory = containerVMFactory(container) { LeaderboardViewModel(it) })

    ScreenState(loading = vm.loading, error = vm.error, onRetry = { vm.load() }) {
        if (vm.entries.isEmpty()) {
            EmptyState(
                title = "No rankings yet",
                subtitle = "Once developers start completing bounties, the leaderboard will fill in here.",
                icon = Icons.Outlined.EmojiEvents,
            )
        } else {
            LazyColumn(
                contentPadding = PaddingValues(16.dp),
                verticalArrangement = Arrangement.spacedBy(14.dp),
            ) {
                itemsIndexed(vm.entries, key = { _, e -> e.developerId.ifEmpty { e.name } }) { index, entry ->
                    LeaderboardRow(
                        entry = entry,
                        rank = if (entry.rank > 0) entry.rank else index + 1,
                        onClick = { onOpenProfile(entry.developerId) },
                    )
                }
            }
        }
    }
}

@Composable
private fun LeaderboardRow(entry: LeaderboardEntry, rank: Int, onClick: () -> Unit) {
    val p = BB.colors
    val rankColor = if (rank in 1..3) p.accent else p.muted
    BBCard(modifier = Modifier.fillMaxWidth(), onClick = onClick) {
        Row(
            Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(14.dp),
        ) {
            Box(Modifier.width(40.dp), contentAlignment = Alignment.Center) {
                Text(
                    rank.toString(),
                    fontFamily = Fraunces,
                    fontWeight = FontWeight.Bold,
                    style = MaterialTheme.typography.headlineMedium,
                    color = rankColor,
                )
            }
            BBAvatar(name = entry.name, fileId = entry.avatarFileId, size = 40.dp)
            Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
                Text(
                    entry.name.ifBlank { "Unknown" },
                    style = MaterialTheme.typography.titleMedium,
                    color = p.text,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                )
                Text(
                    "${entry.tasksCompleted} task${if (entry.tasksCompleted == 1) "" else "s"}",
                    style = MaterialTheme.typography.labelSmall,
                    color = p.muted,
                )
            }
            BountyChip(entry.totalBounty)
        }
    }
}
