package com.anypreta.bountyboard.ui.consultant

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Groups
import androidx.compose.material.icons.outlined.Search
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.PoolDeveloper
import com.anypreta.bountyboard.data.net.PoolAddBody
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.BBButton
import com.anypreta.bountyboard.ui.components.BBButtonStyle
import com.anypreta.bountyboard.ui.components.BBCard
import com.anypreta.bountyboard.ui.components.BBTextField
import com.anypreta.bountyboard.ui.components.EmptyState
import com.anypreta.bountyboard.ui.components.ScreenState
import com.anypreta.bountyboard.ui.theme.BB
import kotlinx.coroutines.launch

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

    Column(Modifier.fillMaxWidth()) {
        BBTextField(
            value = vm.query,
            onValueChange = { vm.query = it },
            label = "Search developers",
            placeholder = "Name or email…",
            leadingIcon = Icons.Outlined.Search,
            modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
        )

        ScreenState(loading = vm.loading, error = vm.error, onRetry = { vm.load() }) {
            val filtered = vm.filtered()
            if (filtered.isEmpty()) {
                EmptyState(
                    title = if (vm.query.isBlank()) "No developers" else "No matches",
                    subtitle = if (vm.query.isBlank()) {
                        "Developers you add to your pool can see and claim your published tasks."
                    } else {
                        "No developers match \"${vm.query}\"."
                    },
                    icon = Icons.Outlined.Groups,
                )
            } else {
                LazyColumn(
                    contentPadding = PaddingValues(16.dp),
                    verticalArrangement = Arrangement.spacedBy(12.dp),
                ) {
                    items(filtered, key = { it.id }) { dev ->
                        DeveloperRow(
                            dev = dev,
                            onOpenProfile = { onOpenProfile(dev.id) },
                            onToggle = { if (dev.inPool) vm.remove(dev.id) else vm.add(dev.id) },
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun DeveloperRow(
    dev: PoolDeveloper,
    onOpenProfile: () -> Unit,
    onToggle: () -> Unit,
) {
    val p = BB.colors
    BBCard(modifier = Modifier.fillMaxWidth()) {
        Row(
            Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            Row(
                modifier = Modifier.weight(1f).clickable(onClick = onOpenProfile),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(12.dp),
            ) {
                BBAvatar(dev.name, dev.avatarFileId, size = 40.dp)
                Column(Modifier.weight(1f)) {
                    Text(
                        dev.name.ifBlank { dev.email },
                        style = MaterialTheme.typography.titleSmall,
                        color = p.text,
                        fontWeight = FontWeight.Bold,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                    )
                    Text(
                        dev.email,
                        style = MaterialTheme.typography.bodySmall,
                        color = p.muted,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                    )
                }
            }
            if (dev.inPool) {
                BBButton("Remove", onClick = onToggle, style = BBButtonStyle.Ghost, small = true)
            } else {
                BBButton("Add to pool", onClick = onToggle, style = BBButtonStyle.Primary, small = true)
            }
        }
    }
}

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

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

    var query by mutableStateOf("")

    init {
        load()
    }

    fun filtered(): List<PoolDeveloper> {
        val q = query.trim().lowercase()
        if (q.isEmpty()) return developers
        return developers.filter {
            it.name.lowercase().contains(q) || it.email.lowercase().contains(q)
        }
    }

    fun load() {
        loading = true; error = null
        viewModelScope.launch {
            try {
                developers = container.repo.call { pool() }.developers
            } catch (e: Exception) {
                error = e.message
            } finally {
                loading = false
            }
        }
    }

    fun add(id: String) {
        viewModelScope.launch {
            try {
                container.repo.action { addToPool(PoolAddBody(id)) }
                load()
            } catch (e: Exception) {
                error = e.message
            }
        }
    }

    fun remove(id: String) {
        viewModelScope.launch {
            try {
                container.repo.action { removeFromPool(id) }
                load()
            } catch (e: Exception) {
                error = e.message
            }
        }
    }
}
