package com.bytelyst.platform.ui

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.OpenInNew
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import coil.compose.AsyncImage
import com.bytelyst.platform.*
import kotlinx.coroutines.launch

/**
 * In-App Message Banner — Jetpack Compose component for top/bottom banner display.
 * Part of ByteLystPlatformSDK.
 */
@Composable
fun InAppMessageBanner(
    client: BLBroadcastClient,
    position: BannerPosition = BannerPosition.TOP,
    modifier: Modifier = Modifier
) {
    val scope = rememberCoroutineScope()
    val context = LocalContext.current
    var messages by remember { mutableStateOf<List<InAppMessage>>(emptyList()) }
    var unreadCount by remember { mutableIntStateOf(0) }

    LaunchedEffect(client) {
        // Initial load
        val result = client.getMessages()
        result.onSuccess { list ->
            messages = list
            unreadCount = messages.count { it.status == "UNREAD" }
        }

        // Start polling
        client.startPolling(60000L) { updatedMessages ->
            messages = updatedMessages
            unreadCount = updatedMessages.count { it.status == "UNREAD" }
        }
    }

    val bannerMessages = messages.filter {
        it.status == "UNREAD" && (it.style == "BANNER" || it.style == "TOAST")
    }

    if (bannerMessages.isEmpty()) return

    Column(
        modifier = modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp)
            .padding(
                top = if (position == BannerPosition.TOP) 16.dp else 0.dp,
                bottom = if (position == BannerPosition.BOTTOM) 16.dp else 0.dp
            ),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        bannerMessages.forEach { message ->
            BannerCard(
                message = message,
                onDismiss = {
                    scope.launch {
                        client.markDismissed(message.id)
                        messages = messages.filter { it.id != message.id }
                    }
                },
                onTap = {
                    scope.launch {
                        client.trackClick(message.id)
                        message.ctaUrl?.let { url ->
                            // Open URL
                            val intent = android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url))
                            context.startActivity(intent)
                        }
                        client.markRead(message.id)
                        messages = messages.map {
                            if (it.id == message.id) it.copy(status = "READ")
                            else it
                        }
                    }
                }
            )
        }
    }
}

enum class BannerPosition {
    TOP, BOTTOM
}

@Composable
private fun BannerCard(
    message: InAppMessage,
    onDismiss: () -> Unit,
    onTap: () -> Unit
) {
    val backgroundColor = when (message.priority.uppercase()) {
        "URGENT" -> MaterialTheme.colorScheme.errorContainer
        "HIGH" -> Color(0xFFFFF3E0) // Orange-ish
        else -> MaterialTheme.colorScheme.surface
    }

    Card(
        modifier = Modifier
            .fillMaxWidth()
            .shadow(4.dp, RoundedCornerShape(12.dp))
            .clickable { onTap() },
        shape = RoundedCornerShape(12.dp),
        colors = CardDefaults.cardColors(containerColor = backgroundColor)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            verticalAlignment = Alignment.Top
        ) {
            if (message.imageUrl != null) {
                AsyncImage(
                    model = message.imageUrl,
                    contentDescription = null,
                    modifier = Modifier
                        .size(48.dp)
                        .clip(RoundedCornerShape(8.dp)),
                    contentScale = ContentScale.Crop
                )
            }

            Column(
                modifier = Modifier.weight(1f),
                verticalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                Text(
                    text = message.title,
                    style = MaterialTheme.typography.titleMedium,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )

                message.body?.let { body ->
                    Text(
                        text = body,
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        maxLines = 2,
                        overflow = TextOverflow.Ellipsis
                    )
                }

                if (message.ctaText != null) {
                    Text(
                        text = "Tap to open →",
                        style = MaterialTheme.typography.labelMedium,
                        color = MaterialTheme.colorScheme.primary
                    )
                }
            }

            if (message.dismissible) {
                IconButton(
                    onClick = onDismiss,
                    modifier = Modifier.size(32.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Close,
                        contentDescription = "Dismiss",
                        tint = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
        }
    }
}

/**
 * Broadcast Modal — Jetpack Compose component for modal/fullscreen broadcast display.
 */
@Composable
fun BroadcastModal(
    client: BLBroadcastClient,
    modifier: Modifier = Modifier
) {
    val scope = rememberCoroutineScope()
    val context = LocalContext.current
    var currentMessage by remember { mutableStateOf<InAppMessage?>(null) }
    var showDialog by remember { mutableStateOf(false) }

    LaunchedEffect(client) {
        // Start polling for modal messages
        client.startPolling(30000L) { messages ->
            val modalMessages = messages.filter {
                it.status == "UNREAD" && (it.style == "MODAL" || it.style == "FULLSCREEN")
            }
            if (modalMessages.isNotEmpty() && currentMessage == null) {
                currentMessage = modalMessages.first()
                showDialog = true
            }
        }
    }

    if (showDialog && currentMessage != null) {
        val message = currentMessage!!

        Dialog(
            onDismissRequest = {
                if (message.dismissible) {
                    scope.launch {
                        client.markDismissed(message.id)
                    }
                    showDialog = false
                    currentMessage = null
                }
            }
        ) {
            Surface(
                modifier = modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                shape = RoundedCornerShape(16.dp),
                color = MaterialTheme.colorScheme.surface
            ) {
                Column(
                    modifier = Modifier.padding(24.dp),
                    verticalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    // Header with image
                    if (message.imageUrl != null) {
                        AsyncImage(
                            model = message.imageUrl,
                            contentDescription = null,
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(160.dp)
                                .clip(RoundedCornerShape(12.dp)),
                            contentScale = ContentScale.Crop
                        )
                    }

                    Text(
                        text = message.title,
                        style = MaterialTheme.typography.headlineSmall,
                        modifier = Modifier.fillMaxWidth()
                    )

                    message.body?.let { body ->
                        Text(
                            text = body,
                            style = MaterialTheme.typography.bodyLarge,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            modifier = Modifier.fillMaxWidth()
                        )
                    }

                    // Action buttons
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.End,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        if (message.dismissible) {
                            TextButton(
                                onClick = {
                                    scope.launch {
                                        client.markDismissed(message.id)
                                    }
                                    showDialog = false
                                    currentMessage = null
                                }
                            ) {
                                Text("Dismiss")
                            }
                        }

                        if (message.ctaText != null) {
                            Button(
                                onClick = {
                                    scope.launch {
                                        client.trackClick(message.id)
                                        message.ctaUrl?.let { url ->
                                            val intent = android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url))
                                            context.startActivity(intent)
                                        }
                                        client.markRead(message.id)
                                    }
                                    showDialog = false
                                    currentMessage = null
                                }
                            ) {
                                Text(message.ctaText)
                                Spacer(modifier = Modifier.width(4.dp))
                                Icon(
                                    imageVector = Icons.Default.OpenInNew,
                                    contentDescription = null,
                                    modifier = Modifier.size(16.dp)
                                )
                            }
                        } else {
                            Button(
                                onClick = {
                                    scope.launch {
                                        client.markRead(message.id)
                                    }
                                    showDialog = false
                                    currentMessage = null
                                }
                            ) {
                                Text("Got it")
                            }
                        }
                    }
                }
            }
        }
    }
}
