package com.anypreta.bountyboard.ui.messaging

import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import android.net.Uri
import android.provider.OpenableColumns
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.AttachFile
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.InsertDriveFile
import androidx.compose.material.icons.outlined.Send
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
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.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.anypreta.bountyboard.data.AppContainer
import com.anypreta.bountyboard.data.model.Message
import com.anypreta.bountyboard.data.model.MessageAttachment
import com.anypreta.bountyboard.data.net.SendMessageBody
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.ScreenState
import com.anypreta.bountyboard.ui.theme.BB
import com.anypreta.bountyboard.ui.util.clockTime
import com.anypreta.bountyboard.ui.util.htmlToPlain
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.toRequestBody

class ConversationViewModel(
    private val container: AppContainer,
    private val conversationId: String,
) : ViewModel() {

    var loading by mutableStateOf(true)
        private set
    var error by mutableStateOf<String?>(null)
        private set
    var sending by mutableStateOf(false)
        private set
    var messages by mutableStateOf<List<Message>>(emptyList())
        private set

    private val nameCache = mutableMapOf<String, String>()
    var names by mutableStateOf<Map<String, String>>(emptyMap())
        private set

    init {
        load()
        // Live: merge messages pushed over the WebSocket for this conversation.
        viewModelScope.launch {
            container.live.chatMessages.collect { m ->
                if (m.conversationId == conversationId) {
                    mergeMessage(m)
                    markRead()
                }
            }
        }
    }

    private fun mergeMessage(m: Message) {
        if (messages.any { it.id == m.id }) return
        messages = (messages + m).sortedBy { it.id }
        resolveNames(setOf(m.senderId))
    }

    fun load() {
        loading = true; error = null
        viewModelScope.launch {
            try {
                val r = container.repo.call { messages(conversationId, cursor = null, limit = 50) }
                messages = r.messages.sortedBy { it.id }
                resolveNames(messages.map { it.senderId }.toSet())
                markRead()
            } catch (e: Exception) {
                error = e.message
            } finally {
                loading = false
            }
        }
    }

    private fun resolveNames(ids: Set<String>) {
        val missing = ids.filter { it.isNotBlank() && !nameCache.containsKey(it) }
        if (missing.isEmpty()) return
        viewModelScope.launch {
            missing.forEach { id ->
                try {
                    val card = container.repo.call { userCard(id) }.card
                    nameCache[id] = card.name.ifBlank { "User" }
                } catch (_: Exception) {
                    nameCache[id] = "User"
                }
            }
            names = nameCache.toMap()
        }
    }

    fun nameFor(id: String): String = names[id] ?: "User"

    fun markRead() {
        viewModelScope.launch {
            try {
                container.repo.call { markConversationRead(conversationId) }
            } catch (_: Exception) {
            }
        }
    }

    fun uploadFile(bytes: ByteArray, name: String, mime: String, onDone: (MessageAttachment?) -> Unit) {
        viewModelScope.launch {
            try {
                val body = bytes.toRequestBody(mime.toMediaTypeOrNull())
                val part = MultipartBody.Part.createFormData("file", name, body)
                val r = container.repo.call { uploadFile(part, null) }
                onDone(
                    MessageAttachment(
                        fileId = r.fileId,
                        name = r.name,
                        mimeType = r.mimeType,
                        size = r.size,
                        isImage = r.isImage,
                    ),
                )
            } catch (e: Exception) {
                error = e.message
                onDone(null)
            }
        }
    }

    fun send(text: String, attachments: List<String>, onSent: () -> Unit) {
        if (text.isBlank() && attachments.isEmpty()) return
        sending = true
        viewModelScope.launch {
            try {
                container.repo.call {
                    sendMessage(conversationId, SendMessageBody(body = text.trim(), attachments = attachments))
                }
                val r = container.repo.call { messages(conversationId, cursor = null, limit = 50) }
                messages = r.messages.sortedBy { it.id }
                resolveNames(messages.map { it.senderId }.toSet())
                onSent()
            } catch (e: Exception) {
                error = e.message
            } finally {
                sending = false
            }
        }
    }
}

@Composable
fun ConversationScreen(conversationId: String, onOpenProfile: (String) -> Unit) {
    val container = LocalAppContainer.current
    val vm: ConversationViewModel = viewModel(
        key = "conv_$conversationId",
        factory = containerVMFactory(container) { ConversationViewModel(it, conversationId) },
    )
    val me by container.session.user.collectAsStateWithLifecycle()
    val p = BB.colors
    val ctx = LocalContext.current
    val listState = rememberLazyListState()

    var input by remember { mutableStateOf("") }
    val pending = remember { mutableStateListOf<MessageAttachment>() }
    var uploading by remember { mutableStateOf(false) }

    val launcher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
        if (uri != null) {
            val bytes = ctx.contentResolver.openInputStream(uri)?.use { it.readBytes() }
            if (bytes != null) {
                val name = queryName(ctx, uri)
                val mime = ctx.contentResolver.getType(uri) ?: "application/octet-stream"
                uploading = true
                vm.uploadFile(bytes, name, mime) { att ->
                    uploading = false
                    if (att != null) pending.add(att)
                }
            }
        }
    }

    LaunchedEffect(vm.messages.size) {
        if (vm.messages.isNotEmpty()) {
            listState.animateScrollToItem(vm.messages.size - 1)
        }
    }

    Column(Modifier.fillMaxSize()) {
        Box(Modifier.weight(1f).fillMaxWidth()) {
            ScreenState(loading = vm.loading, error = vm.error, onRetry = { vm.load() }) {
                LazyColumn(
                    state = listState,
                    modifier = Modifier.fillMaxSize(),
                    contentPadding = PaddingValues(16.dp),
                    verticalArrangement = Arrangement.spacedBy(10.dp),
                ) {
                    items(vm.messages, key = { it.id }) { msg ->
                        MessageBubble(
                            message = msg,
                            mine = msg.senderId == me?.id,
                            senderName = vm.nameFor(msg.senderId),
                            onOpenProfile = onOpenProfile,
                            fileUrl = { container.fileUrl(it) },
                        )
                    }
                }
            }
        }

        InputBar(
            value = input,
            onValueChange = { input = it },
            pending = pending,
            uploading = uploading,
            sending = vm.sending,
            onAttach = { launcher.launch("*/*") },
            onRemoveAttachment = { pending.remove(it) },
            onSend = {
                vm.send(input, pending.map { it.fileId }) {
                    input = ""
                    pending.clear()
                }
            },
        )
    }
}

@Composable
private fun MessageBubble(
    message: Message,
    mine: Boolean,
    senderName: String,
    onOpenProfile: (String) -> Unit,
    fileUrl: (String) -> String,
) {
    val p = BB.colors
    val uriHandler = LocalUriHandler.current
    val ctx = LocalContext.current
    val container = LocalAppContainer.current
    val shape = RoundedCornerShape(p.radius.dp)

    Row(
        Modifier.fillMaxWidth(),
        horizontalArrangement = if (mine) Arrangement.End else Arrangement.Start,
    ) {
        Column(
            modifier = Modifier.widthIn(max = 280.dp),
            horizontalAlignment = if (mine) Alignment.End else Alignment.Start,
        ) {
            if (!mine) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(6.dp),
                    modifier = Modifier.clickable { onOpenProfile(message.senderId) }.padding(bottom = 3.dp),
                ) {
                    BBAvatar(senderName, null, size = 22.dp)
                    Text(senderName, style = MaterialTheme.typography.labelSmall, color = p.muted)
                }
            }
            Box(
                Modifier
                    .clip(shape)
                    .background(if (mine) p.accent else p.surface2)
                    .border(1.dp, p.border, shape)
                    .padding(10.dp),
            ) {
                Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
                    message.attachments?.forEach { att ->
                        if (att.isImage) {
                            AsyncImage(
                                model = ImageRequest.Builder(ctx).data(fileUrl(att.fileId)).build(),
                                imageLoader = container.imageLoader,
                                contentDescription = att.name,
                                modifier = Modifier
                                    .widthIn(max = 200.dp)
                                    .size(200.dp)
                                    .clip(RoundedCornerShape(2.dp))
                                    .clickable { uriHandler.openUri(fileUrl(att.fileId)) },
                            )
                        } else {
                            Row(
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.spacedBy(6.dp),
                                modifier = Modifier.clickable { uriHandler.openUri(fileUrl(att.fileId)) },
                            ) {
                                Icon(
                                    Icons.Outlined.InsertDriveFile,
                                    null,
                                    tint = if (mine) p.onAccent else p.accent,
                                    modifier = Modifier.size(16.dp),
                                )
                                Text(
                                    att.name ?: "Attachment",
                                    style = MaterialTheme.typography.bodySmall,
                                    color = if (mine) p.onAccent else p.accent,
                                )
                            }
                        }
                    }
                    if (message.body.isNotBlank()) {
                        com.anypreta.bountyboard.ui.components.RichText(
                            message.body,
                            style = MaterialTheme.typography.bodyMedium,
                            color = if (mine) p.onAccent else p.text,
                            linkColor = if (mine) p.onAccent else p.accent,
                        )
                    }
                }
            }
            message.editedAt?.let {
                Text(
                    "edited ${clockTime(it)}",
                    style = MaterialTheme.typography.labelSmall,
                    color = p.muted,
                    modifier = Modifier.padding(top = 2.dp, start = 2.dp, end = 2.dp),
                )
            }
        }
    }
}

@Composable
private fun InputBar(
    value: String,
    onValueChange: (String) -> Unit,
    pending: List<MessageAttachment>,
    uploading: Boolean,
    sending: Boolean,
    onAttach: () -> Unit,
    onRemoveAttachment: (MessageAttachment) -> Unit,
    onSend: () -> Unit,
) {
    val p = BB.colors
    Column(
        Modifier
            .fillMaxWidth()
            .background(p.surface)
            .padding(horizontal = 12.dp, vertical = 8.dp),
        verticalArrangement = Arrangement.spacedBy(6.dp),
    ) {
        if (pending.isNotEmpty() || uploading) {
            Row(
                Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(6.dp),
                verticalAlignment = Alignment.CenterVertically,
            ) {
                pending.forEach { att ->
                    Row(
                        Modifier
                            .clip(RoundedCornerShape(p.radius.dp))
                            .background(p.surface2)
                            .border(1.dp, p.border, RoundedCornerShape(p.radius.dp))
                            .padding(start = 8.dp, end = 4.dp, top = 3.dp, bottom = 3.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(4.dp),
                    ) {
                        Text(att.name ?: "file", style = MaterialTheme.typography.labelSmall, color = p.text)
                        Icon(
                            Icons.Outlined.Close,
                            "Remove",
                            tint = p.muted,
                            modifier = Modifier.size(14.dp).clickable { onRemoveAttachment(att) },
                        )
                    }
                }
                if (uploading) {
                    CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp, color = p.accent)
                }
            }
        }
        Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
            IconButton(onClick = onAttach) {
                Icon(Icons.Outlined.AttachFile, "Attach", tint = p.muted)
            }
            OutlinedTextField(
                value = value,
                onValueChange = onValueChange,
                modifier = Modifier.weight(1f),
                placeholder = { Text("Message…", color = p.muted, style = MaterialTheme.typography.bodyMedium) },
                maxLines = 4,
                shape = RoundedCornerShape(p.radius.dp),
                textStyle = MaterialTheme.typography.bodyLarge,
                colors = OutlinedTextFieldDefaults.colors(
                    focusedBorderColor = p.accent,
                    unfocusedBorderColor = p.border,
                    focusedContainerColor = p.bg,
                    unfocusedContainerColor = p.bg,
                    cursorColor = p.accent,
                    focusedTextColor = p.text,
                    unfocusedTextColor = p.text,
                ),
            )
            val canSend = (value.isNotBlank() || pending.isNotEmpty()) && !sending
            IconButton(onClick = onSend, enabled = canSend) {
                if (sending) {
                    CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp, color = p.accent)
                } else {
                    Icon(Icons.Outlined.Send, "Send", tint = if (canSend) p.accent else p.muted)
                }
            }
        }
    }
}

private fun queryName(ctx: android.content.Context, uri: Uri): String {
    var name = "upload"
    try {
        ctx.contentResolver.query(uri, null, null, null, null)?.use { cursor ->
            val idx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
            if (idx >= 0 && cursor.moveToFirst()) {
                cursor.getString(idx)?.let { if (it.isNotBlank()) name = it }
            }
        }
    } catch (_: Exception) {
    }
    return name
}
