package com.rosetta.messenger.ui.chats

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Divider
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.graphics.Color
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.sp
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.LottieConstants
import com.airbnb.lottie.compose.animateLottieCompositionAsState
import com.airbnb.lottie.compose.rememberLottieComposition
import com.rosetta.messenger.R
import com.rosetta.messenger.repository.AvatarRepository
import com.rosetta.messenger.ui.onboarding.PrimaryBlue

@Composable
internal fun EmptyRequestsState(isDarkTheme: Boolean, modifier: Modifier = Modifier) {
    val secondaryTextColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666)
    val backgroundColor = if (isDarkTheme) Color(0xFF1A1A1A) else Color(0xFFF2F2F7)

    val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.no_requests))
    val progress by animateLottieCompositionAsState(
        composition = composition,
        iterations = LottieConstants.IterateForever
    )

    Column(
        modifier = modifier.fillMaxSize().background(backgroundColor),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = androidx.compose.foundation.layout.Arrangement.Center
    ) {
        LottieAnimation(
            composition = composition,
            progress = { progress },
            modifier = Modifier.size(160.dp)
        )

        androidx.compose.foundation.layout.Spacer(modifier = Modifier.height(20.dp))

        Text(
            text = "No Requests",
            fontSize = 18.sp,
            fontWeight = FontWeight.SemiBold,
            color = secondaryTextColor,
            textAlign = TextAlign.Center
        )

        androidx.compose.foundation.layout.Spacer(modifier = Modifier.height(8.dp))

        Text(
            text = "New message requests will appear here",
            fontSize = 15.sp,
            color = secondaryTextColor.copy(alpha = 0.7f),
            textAlign = TextAlign.Center
        )
    }
}

/** 📬 Экран со списком Requests (без хедера - хедер в основном TopAppBar) */
@Composable
fun RequestsScreen(
    requests: List<DialogUiModel>,
    isDarkTheme: Boolean,
    onRequestClick: (DialogUiModel) -> Unit,
    avatarRepository: AvatarRepository? = null,
    blockedUsers: Set<String> = emptySet(),
    pinnedChats: Set<String> = emptySet(),
    isDrawerOpen: Boolean = false,
    onTogglePin: (String) -> Unit = {},
    onDeleteDialog: (String) -> Unit = {},
    onBlockUser: (String) -> Unit = {},
    onUnblockUser: (String) -> Unit = {}
) {
    val backgroundColor = if (isDarkTheme) Color(0xFF1A1A1A) else Color(0xFFF2F2F7)
    val dividerColor = if (isDarkTheme) Color(0xFF3A3A3A) else Color(0xFFE8E8E8)
    val textColor = if (isDarkTheme) Color.White else Color.Black
    val secondaryTextColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666)

    var swipedItemKey by remember { mutableStateOf<String?>(null) }

    LaunchedEffect(isDrawerOpen) {
        if (isDrawerOpen) {
            swipedItemKey = null
        }
    }

    var dialogToDelete by remember { mutableStateOf<DialogUiModel?>(null) }
    var dialogToBlock by remember { mutableStateOf<DialogUiModel?>(null) }
    var dialogToUnblock by remember { mutableStateOf<DialogUiModel?>(null) }

    Column(modifier = Modifier.fillMaxSize().background(backgroundColor)) {
        if (requests.isEmpty()) {
            EmptyRequestsState(isDarkTheme = isDarkTheme)
        } else {
            LazyColumn(modifier = Modifier.fillMaxSize()) {
                items(
                    requests,
                    key = { it.opponentKey },
                    contentType = { "request" }
                ) { request ->
                    val isBlocked = blockedUsers.contains(request.opponentKey)
                    val isPinned = pinnedChats.contains(request.opponentKey)

                    SwipeableDialogItem(
                        dialog = request,
                        isDarkTheme = isDarkTheme,
                        isTyping = false,
                        isBlocked = isBlocked,
                        isSavedMessages = false,
                        avatarRepository = avatarRepository,
                        isDrawerOpen = isDrawerOpen,
                        isSwipedOpen = swipedItemKey == request.opponentKey,
                        onSwipeStarted = { swipedItemKey = request.opponentKey },
                        onSwipeClosed = {
                            if (swipedItemKey == request.opponentKey) swipedItemKey = null
                        },
                        onClick = {
                            swipedItemKey = null
                            onRequestClick(request)
                        },
                        onDelete = { dialogToDelete = request },
                        onBlock = { dialogToBlock = request },
                        onUnblock = { dialogToUnblock = request },
                        isPinned = isPinned,
                        onPin = { onTogglePin(request.opponentKey) }
                    )

                    if (request != requests.last()) {
                        Divider(
                            modifier = Modifier.padding(start = 84.dp),
                            color = dividerColor,
                            thickness = 0.5.dp
                        )
                    }
                }
            }
        }
    }

    dialogToDelete?.let { dialog ->
        AlertDialog(
            onDismissRequest = { dialogToDelete = null },
            containerColor = if (isDarkTheme) Color(0xFF2C2C2E) else Color.White,
            title = {
                Text("Delete Chat", fontWeight = FontWeight.Bold, color = textColor)
            },
            text = {
                Text(
                    "Are you sure you want to delete this chat? This action cannot be undone.",
                    color = secondaryTextColor
                )
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        val opponentKey = dialog.opponentKey
                        dialogToDelete = null
                        onDeleteDialog(opponentKey)
                    }
                ) { Text("Delete", color = Color(0xFFFF3B30)) }
            },
            dismissButton = {
                TextButton(onClick = { dialogToDelete = null }) {
                    Text("Cancel", color = PrimaryBlue)
                }
            }
        )
    }

    dialogToBlock?.let { dialog ->
        AlertDialog(
            onDismissRequest = { dialogToBlock = null },
            containerColor = if (isDarkTheme) Color(0xFF2C2C2E) else Color.White,
            title = {
                Text(
                    "Block ${dialog.opponentTitle.ifEmpty { "User" }}",
                    fontWeight = FontWeight.Bold,
                    color = textColor
                )
            },
            text = {
                Text(
                    "Are you sure you want to block this user? They won't be able to send you messages.",
                    color = secondaryTextColor
                )
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        val opponentKey = dialog.opponentKey
                        dialogToBlock = null
                        onBlockUser(opponentKey)
                    }
                ) { Text("Block", color = Color(0xFFFF3B30)) }
            },
            dismissButton = {
                TextButton(onClick = { dialogToBlock = null }) {
                    Text("Cancel", color = PrimaryBlue)
                }
            }
        )
    }

    dialogToUnblock?.let { dialog ->
        AlertDialog(
            onDismissRequest = { dialogToUnblock = null },
            containerColor = if (isDarkTheme) Color(0xFF2C2C2E) else Color.White,
            title = {
                Text(
                    "Unblock ${dialog.opponentTitle.ifEmpty { "User" }}",
                    fontWeight = FontWeight.Bold,
                    color = textColor
                )
            },
            text = {
                Text(
                    "Are you sure you want to unblock this user? They will be able to send you messages again.",
                    color = secondaryTextColor
                )
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        val opponentKey = dialog.opponentKey
                        dialogToUnblock = null
                        onUnblockUser(opponentKey)
                    }
                ) { Text("Unblock", color = Color(0xFF34C759)) }
            },
            dismissButton = {
                TextButton(onClick = { dialogToUnblock = null }) {
                    Text("Cancel", color = PrimaryBlue)
                }
            }
        )
    }
}
