package com.anypreta.bountyboard.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Inbox
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.SubcomposeAsyncImage
import coil.request.ImageRequest
import com.anypreta.bountyboard.di.LocalAppContainer
import com.anypreta.bountyboard.ui.theme.BB
import com.anypreta.bountyboard.ui.theme.Fraunces
import com.anypreta.bountyboard.ui.theme.KickerStyle

@Composable
fun BBAvatar(
    name: String,
    fileId: String?,
    modifier: Modifier = Modifier,
    size: Dp = 32.dp,
) {
    val p = BB.colors
    val container = LocalAppContainer.current
    val context = LocalContext.current
    val shape = RoundedCornerShape((p.radius + 1).dp)
    val initials = remember(name) { computeInitials(name) }
    Box(
        modifier = modifier
            .size(size)
            .clip(shape)
            .background(p.accent)
            .border(1.dp, p.border, shape),
        contentAlignment = Alignment.Center,
    ) {
        if (!fileId.isNullOrEmpty()) {
            SubcomposeAsyncImage(
                model = ImageRequest.Builder(context).data(container.fileUrl(fileId)).build(),
                imageLoader = container.imageLoader,
                contentDescription = name,
                modifier = Modifier.fillMaxSize(),
                loading = { InitialsLabel(initials, size, p.onAccent) },
                error = { InitialsLabel(initials, size, p.onAccent) },
            )
        } else {
            InitialsLabel(initials, size, p.onAccent)
        }
    }
}

@Composable
private fun InitialsLabel(initials: String, size: Dp, color: Color) {
    Text(
        initials,
        fontFamily = Fraunces,
        fontWeight = FontWeight.Bold,
        color = color,
        fontSize = (size.value * 0.4f).sp,
    )
}

private fun computeInitials(name: String): String {
    val parts = name.trim().split(Regex("\\s+")).filter { it.isNotEmpty() }
    return when {
        parts.isEmpty() -> "?"
        parts.size == 1 -> parts[0].take(2).uppercase()
        else -> (parts[0].take(1) + parts.last().take(1)).uppercase()
    }
}

@Composable
fun Kicker(text: String, modifier: Modifier = Modifier) {
    Text(text.uppercase(), style = KickerStyle, color = BB.colors.muted, modifier = modifier)
}

@Composable
fun DiamondBrand(text: String, modifier: Modifier = Modifier) {
    val p = BB.colors
    Row(modifier, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
        Text("◈", color = p.accent, fontFamily = Fraunces, fontWeight = FontWeight.Bold, style = MaterialTheme.typography.titleLarge)
        Text(text, color = p.text, fontFamily = Fraunces, fontWeight = FontWeight.Bold, style = MaterialTheme.typography.titleLarge)
    }
}

@Composable
fun SectionLabel(text: String, modifier: Modifier = Modifier) {
    Text(text.uppercase(), style = MaterialTheme.typography.labelSmall, color = BB.colors.muted, modifier = modifier)
}

@Composable
fun Hairline(modifier: Modifier = Modifier) {
    Box(
        modifier
            .fillMaxWidth()
            .height(1.dp)
            .background(BB.colors.border.copy(alpha = 0.6f)),
    )
}

@Composable
fun LoadingBox(modifier: Modifier = Modifier) {
    Box(modifier.fillMaxSize().padding(48.dp), contentAlignment = Alignment.Center) {
        CircularProgressIndicator(color = BB.colors.accent, strokeWidth = 2.dp)
    }
}

@Composable
fun EmptyState(
    title: String,
    subtitle: String? = null,
    icon: ImageVector = Icons.Outlined.Inbox,
    modifier: Modifier = Modifier,
    action: (@Composable () -> Unit)? = null,
) {
    val p = BB.colors
    Column(
        modifier.fillMaxWidth().padding(40.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(10.dp),
    ) {
        Icon(icon, null, tint = p.muted.copy(alpha = 0.6f), modifier = Modifier.size(48.dp))
        Text(title, style = MaterialTheme.typography.headlineSmall, color = p.text, textAlign = TextAlign.Center)
        if (subtitle != null) {
            Text(subtitle, style = MaterialTheme.typography.bodyMedium, color = p.muted, textAlign = TextAlign.Center)
        }
        if (action != null) {
            Spacer(Modifier.height(4.dp))
            action()
        }
    }
}

enum class MessageKind { Error, Ok, Info }

@Composable
fun MessageBox(text: String, kind: MessageKind = MessageKind.Error, modifier: Modifier = Modifier) {
    val p = BB.colors
    val color = when (kind) {
        MessageKind.Error -> p.err
        MessageKind.Ok -> p.ok
        MessageKind.Info -> p.accent
    }
    Row(
        modifier
            .fillMaxWidth()
            .height(IntrinsicSize.Min)
            .clip(RoundedCornerShape(p.radius.dp))
            .background(color.copy(alpha = 0.08f))
            .border(1.dp, color.copy(alpha = 0.5f), RoundedCornerShape(p.radius.dp)),
    ) {
        Box(Modifier.width(4.dp).fillMaxHeight().background(color))
        Text(
            text,
            style = MaterialTheme.typography.bodyMedium,
            color = color,
            modifier = Modifier.padding(12.dp),
        )
    }
}

@Composable
fun ConfirmDialog(
    title: String,
    message: String,
    confirmText: String = "Confirm",
    danger: Boolean = false,
    onConfirm: () -> Unit,
    onDismiss: () -> Unit,
) {
    val p = BB.colors
    AlertDialog(
        onDismissRequest = onDismiss,
        containerColor = p.surface,
        titleContentColor = p.text,
        textContentColor = p.muted,
        title = { Text(title, style = MaterialTheme.typography.headlineSmall, color = p.text) },
        text = { Text(message, style = MaterialTheme.typography.bodyMedium, color = p.muted) },
        confirmButton = {
            BBButton(
                confirmText,
                onClick = onConfirm,
                style = if (danger) BBButtonStyle.Danger else BBButtonStyle.Primary,
                small = true,
            )
        },
        dismissButton = {
            BBButton("Cancel", onClick = onDismiss, style = BBButtonStyle.Ghost, small = true)
        },
    )
}
