package com.anypreta.bountyboard.ui.messaging

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.heightIn
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.Forum
import androidx.compose.material.icons.outlined.Search
import androidx.compose.material3.AlertDialog
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.remember
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.ConversationSummary
import com.anypreta.bountyboard.data.model.User
import com.anypreta.bountyboard.data.net.CreateConversationBody
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.BBBadge
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 com.anypreta.bountyboard.ui.util.relativeTime
import kotlinx.coroutines.launch

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

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

    var searchResults by mutableStateOf<List<User>>(emptyList())
        private set
    var searching by mutableStateOf(false)
        private set

    init {
        load()
    }

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

    fun search(q: String) {
        if (q.isBlank()) {
            searchResults = emptyList()
            return
        }
        searching = true
        viewModelScope.launch {
            try {
                searchResults = container.repo.call { users(q.trim()) }.users
            } catch (_: Exception) {
                searchResults = emptyList()
            } finally {
                searching = false
            }
        }
    }

    fun startDm(userId: String, onDone: (String) -> Unit) {
        viewModelScope.launch {
            try {
                val r = container.repo.call {
                    createConversation(CreateConversationBody(kind = "dm", participantIds = listOf(userId)))
                }
                onDone(r.conversation.id)
            } catch (e: Exception) {
                error = e.message
            }
        }
    }
}

@Composable
fun MessagesScreen(onOpenConversation: (String) -> Unit) {
    val container = LocalAppContainer.current
    val vm: MessagesViewModel = viewModel(factory = containerVMFactory(container) { MessagesViewModel(it) })
    val p = BB.colors

    var showNew by remember { mutableStateOf(false) }

    Column(Modifier.fillMaxWidth()) {
        Box(Modifier.padding(horizontal = 16.dp, vertical = 12.dp)) {
            BBButton(
                "New message",
                onClick = { showNew = true },
                style = BBButtonStyle.Primary,
                modifier = Modifier.fillMaxWidth(),
            )
        }

        ScreenState(loading = vm.loading, error = vm.error, onRetry = { vm.load() }) {
            if (vm.conversations.isEmpty()) {
                EmptyState(
                    title = "No conversations yet",
                    subtitle = "Start a direct message to coordinate on tasks.",
                    icon = Icons.Outlined.Forum,
                )
            } else {
                LazyColumn(
                    contentPadding = PaddingValues(16.dp),
                    verticalArrangement = Arrangement.spacedBy(12.dp),
                ) {
                    items(vm.conversations, key = { it.id }) { conv ->
                        ConversationRow(conv) { onOpenConversation(conv.id) }
                    }
                }
            }
        }
    }

    if (showNew) {
        NewMessageDialog(
            vm = vm,
            onDismiss = { showNew = false },
            onPicked = { userId ->
                vm.startDm(userId) { convId ->
                    showNew = false
                    onOpenConversation(convId)
                }
            },
        )
    }
}

@Composable
private fun ConversationRow(conv: ConversationSummary, onClick: () -> Unit) {
    val p = BB.colors
    val title = conv.title ?: "Conversation"
    BBCard(modifier = Modifier.fillMaxWidth(), onClick = onClick) {
        Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
            BBAvatar(title, null, size = 40.dp)
            Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
                Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
                    Text(
                        title,
                        style = MaterialTheme.typography.titleMedium,
                        color = p.text,
                        fontWeight = FontWeight.Bold,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                        modifier = Modifier.weight(1f, fill = false),
                    )
                    if (conv.kind != "dm") BBBadge(conv.kind, color = p.accent)
                }
            }
            Column(horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(4.dp)) {
                Text(relativeTime(conv.lastMessageAt), style = MaterialTheme.typography.labelSmall, color = p.muted)
                if (conv.unread > 0) {
                    BBBadge(conv.unread.toString(), color = p.err, filled = true)
                }
            }
        }
    }
}

@Composable
private fun NewMessageDialog(
    vm: MessagesViewModel,
    onDismiss: () -> Unit,
    onPicked: (String) -> Unit,
) {
    val p = BB.colors
    var query by remember { mutableStateOf("") }

    AlertDialog(
        onDismissRequest = onDismiss,
        containerColor = p.surface,
        title = { Text("New message", style = MaterialTheme.typography.headlineSmall, color = p.text) },
        text = {
            Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                BBTextField(
                    value = query,
                    onValueChange = { query = it; vm.search(it) },
                    label = "Search people",
                    placeholder = "Name or email…",
                    leadingIcon = Icons.Outlined.Search,
                    modifier = Modifier.fillMaxWidth(),
                )
                LazyColumn(
                    modifier = Modifier.heightIn(max = 320.dp),
                    verticalArrangement = Arrangement.spacedBy(2.dp),
                ) {
                    items(vm.searchResults, key = { it.id }) { user ->
                        UserPickRow(user) { onPicked(user.id) }
                    }
                }
            }
        },
        confirmButton = {},
        dismissButton = {
            BBButton("Close", onClick = onDismiss, style = BBButtonStyle.Ghost, small = true)
        },
    )
}

@Composable
private fun UserPickRow(user: User, onClick: () -> Unit) {
    val p = BB.colors
    Row(
        Modifier
            .fillMaxWidth()
            .padding(vertical = 6.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(10.dp),
    ) {
        BBAvatar(user.name, user.avatarFileId, size = 36.dp)
        Column(Modifier.weight(1f)) {
            Text(user.name, style = MaterialTheme.typography.bodyMedium, color = p.text, fontWeight = FontWeight.Bold, maxLines = 1, overflow = TextOverflow.Ellipsis)
            Text(user.email, style = MaterialTheme.typography.labelSmall, color = p.muted, maxLines = 1, overflow = TextOverflow.Ellipsis)
        }
        BBButton("Message", onClick = onClick, style = BBButtonStyle.Primary, small = true)
    }
}
