package com.anypreta.bountyboard.ui.shared

import androidx.compose.foundation.background
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.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.NotificationsNone
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.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.Notification
import com.anypreta.bountyboard.data.net.NotificationsReadBody
import com.anypreta.bountyboard.di.LocalAppContainer
import com.anypreta.bountyboard.di.containerVMFactory
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.EmptyState
import com.anypreta.bountyboard.ui.components.FilterPill
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 NotificationsViewModel(private val container: AppContainer) : ViewModel() {

    var loading by mutableStateOf(true)
        private set
    var error by mutableStateOf<String?>(null)
        private set
    var notifications by mutableStateOf<List<Notification>>(emptyList())
        private set
    var unread by mutableStateOf(0L)
        private set
    var unreadOnly by mutableStateOf(false)
        private set

    init {
        load()
    }

    fun toggleUnreadOnly() {
        unreadOnly = !unreadOnly
        load()
    }

    fun load() {
        loading = true; error = null
        viewModelScope.launch {
            try {
                val r = container.repo.call {
                    notifications(unread = if (unreadOnly) true else null, cursor = null, limit = 50)
                }
                notifications = r.notifications
                unread = r.unread
            } catch (e: Exception) {
                error = e.message
            } finally {
                loading = false
            }
        }
    }

    fun markRead(ids: List<String>, onChanged: () -> Unit) {
        viewModelScope.launch {
            try {
                container.repo.call { markNotificationsRead(NotificationsReadBody(ids)) }
                load()
                onChanged()
            } catch (e: Exception) {
                error = e.message
            }
        }
    }
}

@Composable
fun NotificationsScreen(onOpenLink: (String) -> Unit, onChanged: () -> Unit) {
    val container = LocalAppContainer.current
    val vm: NotificationsViewModel = viewModel(factory = containerVMFactory(container) { NotificationsViewModel(it) })
    val p = BB.colors

    Column(Modifier.fillMaxWidth()) {
        Row(
            Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp, vertical = 12.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(8.dp),
        ) {
            FilterPill(
                text = if (vm.unreadOnly) "Unread only" else "All",
                showCaret = false,
                onClick = { vm.toggleUnreadOnly() },
            )
            androidx.compose.foundation.layout.Spacer(Modifier.weight(1f))
            BBButton(
                "Mark all read",
                onClick = { vm.markRead(emptyList()) { onChanged() } },
                style = BBButtonStyle.Default,
                small = true,
                enabled = vm.unread > 0,
            )
        }

        ScreenState(loading = vm.loading, error = vm.error, onRetry = { vm.load() }) {
            if (vm.notifications.isEmpty()) {
                EmptyState(
                    title = "You're all caught up",
                    subtitle = "New activity on your tasks and conversations shows up here.",
                    icon = Icons.Outlined.NotificationsNone,
                )
            } else {
                LazyColumn(
                    contentPadding = PaddingValues(16.dp),
                    verticalArrangement = Arrangement.spacedBy(12.dp),
                ) {
                    items(vm.notifications, key = { it.id }) { n ->
                        NotificationRow(n) {
                            if (n.isUnread) {
                                vm.markRead(listOf(n.id)) { onChanged() }
                            }
                            n.link?.let { onOpenLink(it) }
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun NotificationRow(n: Notification, onClick: () -> Unit) {
    val p = BB.colors
    BBCard(modifier = Modifier.fillMaxWidth(), onClick = onClick, padding = PaddingValues(0.dp)) {
        Row(Modifier.height(androidx.compose.foundation.layout.IntrinsicSize.Min)) {
            if (n.isUnread) {
                Box(Modifier.width(4.dp).fillMaxHeight().background(p.accent))
            }
            Column(
                Modifier
                    .fillMaxWidth()
                    .then(if (n.isUnread) Modifier.background(p.surface2) else Modifier)
                    .padding(16.dp),
                verticalArrangement = Arrangement.spacedBy(4.dp),
            ) {
                Text(
                    n.title,
                    style = MaterialTheme.typography.titleSmall,
                    color = p.text,
                    fontWeight = FontWeight.Bold,
                )
                if (n.body.isNotBlank()) {
                    Text(n.body, style = MaterialTheme.typography.bodyMedium, color = p.muted)
                }
                Text(relativeTime(n.createdAt), style = MaterialTheme.typography.labelSmall, color = p.muted)
            }
        }
    }
}
