package com.rosetta.messenger.ui.chats

import androidx.compose.foundation.background
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.Row
import androidx.compose.foundation.layout.Spacer
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.CircleShape
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.unit.dp
import androidx.compose.ui.unit.sp
import com.rosetta.messenger.repository.AvatarRepository
import com.rosetta.messenger.ui.icons.TelegramIcons
import com.rosetta.messenger.ui.components.AppleEmojiText
import com.rosetta.messenger.ui.components.AvatarImage
import com.rosetta.messenger.ui.onboarding.PrimaryBlue
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

@Composable
fun ChatItem(
    chat: Chat,
    isDarkTheme: Boolean,
    avatarRepository: AvatarRepository? = null,
    isMuted: Boolean = false,
    onClick: () -> Unit
) {
    val textColor = if (isDarkTheme) Color.White else Color.Black
    val secondaryTextColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666)
    val dividerColor = if (isDarkTheme) Color(0xFF3A3A3A) else Color(0xFFE8E8E8)

    Column {
        Row(
            modifier =
                Modifier.fillMaxWidth()
                    .clickable(onClick = onClick)
                    .padding(
                        horizontal = TELEGRAM_DIALOG_AVATAR_START,
                        vertical = TELEGRAM_DIALOG_VERTICAL_PADDING
                    ),
            verticalAlignment = Alignment.CenterVertically
        ) {
            AvatarImage(
                publicKey = chat.publicKey,
                avatarRepository = avatarRepository,
                size = TELEGRAM_DIALOG_AVATAR_SIZE,
                isDarkTheme = isDarkTheme,
                showOnlineIndicator = true,
                isOnline = chat.isOnline,
                displayName = chat.name,
                enableBlurPrewarm = true
            )

            Spacer(modifier = Modifier.width(TELEGRAM_DIALOG_AVATAR_GAP))

            Column(modifier = Modifier.weight(1f)) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    AppleEmojiText(
                        text = chat.name,
                        fontSize = 16.sp,
                        fontWeight = FontWeight.SemiBold,
                        color = textColor,
                        maxLines = 1,
                        overflow = android.text.TextUtils.TruncateAt.END,
                        modifier = Modifier.weight(1f),
                        enableLinks = false
                    )

                    if (isMuted) {
                        Spacer(modifier = Modifier.width(4.dp))
                        Icon(
                            painter = TelegramIcons.Mute,
                            contentDescription = "Muted",
                            tint = secondaryTextColor,
                            modifier = Modifier.size(14.dp)
                        )
                    }

                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Icon(
                            painter = TelegramIcons.Done,
                            contentDescription = null,
                            tint = PrimaryBlue,
                            modifier = Modifier.size(16.dp)
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        Text(
                            text = formatTime(chat.lastMessageTime),
                            fontSize = 13.sp,
                            color = secondaryTextColor
                        )
                    }
                }

                Spacer(modifier = Modifier.height(4.dp))

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    AppleEmojiText(
                        text = chat.lastMessage,
                        fontSize = 14.sp,
                        color = secondaryTextColor,
                        maxLines = 1,
                        overflow = android.text.TextUtils.TruncateAt.END,
                        modifier = Modifier.weight(1f),
                        enableLinks = false
                    )

                    Row(verticalAlignment = Alignment.CenterVertically) {
                        if (chat.isPinned) {
                            Icon(
                                painter = TelegramIcons.Pin,
                                contentDescription = "Pinned",
                                tint = secondaryTextColor.copy(alpha = 0.6f),
                                modifier = Modifier.size(16.dp).padding(end = 4.dp)
                            )
                        }

                        if (chat.unreadCount > 0) {
                            Box(
                                modifier =
                                    Modifier.background(PrimaryBlue, CircleShape).padding(
                                        horizontal = 8.dp,
                                        vertical = 2.dp
                                    ),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(
                                    text =
                                        if (chat.unreadCount > 99) "99+"
                                        else chat.unreadCount.toString(),
                                    fontSize = 12.sp,
                                    fontWeight = FontWeight.SemiBold,
                                    color = Color.White
                                )
                            }
                        }
                    }
                }
            }
        }

        Divider(
            modifier = Modifier.padding(start = 84.dp),
            color = dividerColor,
            thickness = 0.5.dp
        )
    }
}

private val timeFormatCache =
    ThreadLocal.withInitial { SimpleDateFormat("HH:mm", Locale.getDefault()) }
private val weekFormatCache =
    ThreadLocal.withInitial { SimpleDateFormat("EEE", Locale.getDefault()) }
private val monthFormatCache =
    ThreadLocal.withInitial { SimpleDateFormat("MMM d", Locale.getDefault()) }
private val yearFormatCache =
    ThreadLocal.withInitial { SimpleDateFormat("dd.MM.yy", Locale.getDefault()) }

internal fun formatTime(date: Date): String {
    val now = Calendar.getInstance()
    val messageTime = Calendar.getInstance().apply { time = date }

    return when {
        now.get(Calendar.DATE) == messageTime.get(Calendar.DATE) -> {
            timeFormatCache.get()?.format(date) ?: ""
        }
        now.get(Calendar.DATE) - messageTime.get(Calendar.DATE) == 1 -> {
            "Yesterday"
        }
        now.get(Calendar.WEEK_OF_YEAR) == messageTime.get(Calendar.WEEK_OF_YEAR) -> {
            weekFormatCache.get()?.format(date) ?: ""
        }
        now.get(Calendar.YEAR) == messageTime.get(Calendar.YEAR) -> {
            monthFormatCache.get()?.format(date) ?: ""
        }
        else -> {
            yearFormatCache.get()?.format(date) ?: ""
        }
    }
}
