package com.rosetta.messenger.ui.chats

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
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.navigationBars
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.rosetta.messenger.R
import com.rosetta.messenger.data.EncryptedAccount
import com.rosetta.messenger.data.MessageRepository
import com.rosetta.messenger.data.resolveAccountDisplayName
import com.rosetta.messenger.repository.AvatarRepository
import com.rosetta.messenger.ui.components.AvatarImage
import com.rosetta.messenger.ui.components.VerifiedBadge
import com.rosetta.messenger.ui.icons.TelegramIcons
import com.rosetta.messenger.ui.onboarding.PrimaryBlue
import com.rosetta.messenger.update.UpdateState
import compose.icons.TablerIcons
import compose.icons.tablericons.ChevronDown
import compose.icons.tablericons.Download
import compose.icons.tablericons.X

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun ChatsDrawerHeaderAndAccounts(
    isDarkTheme: Boolean,
    drawerBackgroundColor: Color,
    accountPublicKey: String,
    accountVerified: Int,
    allAccounts: List<EncryptedAccount>,
    effectiveCurrentPublicKey: String,
    sidebarAccountName: String,
    sidebarAccountUsername: String,
    avatarRepository: AvatarRepository?,
    accountsSectionExpanded: Boolean,
    onAccountsSectionExpandedChange: (Boolean) -> Unit,
    onProfileClick: () -> Unit,
    onCurrentAccountLongPress: () -> Unit,
    onSwitchAccount: (String) -> Unit,
    onAccountLongPress: (EncryptedAccount) -> Unit,
    onAddAccountClick: () -> Unit,
    onThemeToggleClick: () -> Unit,
    onThemeToggleCenterChanged: (Offset) -> Unit
) {
    Box(modifier = Modifier.fillMaxWidth()) {
        Box(
            modifier =
                Modifier.matchParentSize().background(
                    if (isDarkTheme) Color(0xFF2A2A2A) else Color(0xFF228BE6)
                )
        )

        Column(
            modifier =
                Modifier.fillMaxWidth()
                    .statusBarsPadding()
                    .padding(top = 16.dp, start = 20.dp, end = 20.dp, bottom = 12.dp)
        ) {
            val isOfficialByKey = MessageRepository.isSystemAccount(accountPublicKey)
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = androidx.compose.foundation.layout.Arrangement.SpaceBetween,
                verticalAlignment = Alignment.Top
            ) {
                Box(
                    modifier =
                        Modifier.size(72.dp).clip(CircleShape).combinedClickable(
                            onClick = onProfileClick,
                            onLongClick = onCurrentAccountLongPress
                        ),
                    contentAlignment = Alignment.Center
                ) {
                    AvatarImage(
                        publicKey = effectiveCurrentPublicKey,
                        avatarRepository = avatarRepository,
                        size = 72.dp,
                        isDarkTheme = isDarkTheme,
                        displayName = sidebarAccountName.ifEmpty { sidebarAccountUsername }
                    )
                }

                IconButton(
                    onClick = onThemeToggleClick,
                    modifier =
                        Modifier.size(48.dp).onGloballyPositioned {
                            val pos = it.positionInRoot()
                            onThemeToggleCenterChanged(
                                Offset(
                                    x = pos.x + it.size.width / 2f,
                                    y = pos.y + it.size.height / 2f
                                )
                            )
                        }
                ) {
                    Icon(
                        painter =
                            painterResource(
                                id =
                                    if (isDarkTheme) R.drawable.day_theme_filled
                                    else R.drawable.night_mode
                            ),
                        contentDescription = if (isDarkTheme) "Light Mode" else "Dark Mode",
                        tint = Color.White,
                        modifier = Modifier.size(28.dp)
                    )
                }
            }

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

            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Column(modifier = Modifier.weight(1f)) {
                    if (sidebarAccountName.isNotEmpty()) {
                        Row(
                            horizontalArrangement = androidx.compose.foundation.layout.Arrangement.Start,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                text = sidebarAccountName,
                                fontSize = 15.sp,
                                fontWeight = FontWeight.Bold,
                                color = Color.White
                            )
                            if (accountVerified > 0 || isOfficialByKey) {
                                Spacer(modifier = Modifier.width(4.dp))
                                VerifiedBadge(
                                    verified = if (accountVerified > 0) accountVerified else 1,
                                    size = 15,
                                    modifier = Modifier.offset(y = 1.dp),
                                    isDarkTheme = isDarkTheme,
                                    badgeTint = if (isDarkTheme) PrimaryBlue else Color.White
                                )
                            }
                        }
                    }

                    if (sidebarAccountUsername.isNotEmpty()) {
                        Spacer(modifier = Modifier.height(2.dp))
                        Text(
                            text = "@$sidebarAccountUsername",
                            fontSize = 13.sp,
                            color = Color.White.copy(alpha = 0.7f)
                        )
                    }
                }

                val arrowRotation by animateFloatAsState(
                    targetValue = if (accountsSectionExpanded) 180f else 0f,
                    animationSpec = tween(300),
                    label = "arrowRotation"
                )
                IconButton(
                    onClick = { onAccountsSectionExpandedChange(!accountsSectionExpanded) },
                    modifier = Modifier.size(40.dp)
                ) {
                    Icon(
                        imageVector = TablerIcons.ChevronDown,
                        contentDescription = if (accountsSectionExpanded) "Collapse" else "Expand",
                        tint = Color.White,
                        modifier = Modifier.size(20.dp).graphicsLayer { rotationZ = arrowRotation }
                    )
                }
            }
        }
    }

    AnimatedVisibility(
        visible = accountsSectionExpanded,
        enter = expandVertically(animationSpec = tween(250)) + fadeIn(animationSpec = tween(250)),
        exit = shrinkVertically(animationSpec = tween(250)) + fadeOut(animationSpec = tween(200))
    ) {
        Column(modifier = Modifier.fillMaxWidth()) {
            allAccounts.take(3).forEach { account ->
                val isCurrentAccount = account.publicKey == effectiveCurrentPublicKey
                val displayName =
                    resolveAccountDisplayName(
                        account.publicKey,
                        account.name,
                        account.username
                    )
                Row(
                    modifier =
                        Modifier.fillMaxWidth().height(48.dp).combinedClickable(
                            onClick = {
                                if (!isCurrentAccount) {
                                    onSwitchAccount(account.publicKey)
                                }
                            },
                            onLongClick = { onAccountLongPress(account) }
                        ).padding(start = 14.dp, end = 16.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Box(modifier = Modifier.size(36.dp), contentAlignment = Alignment.Center) {
                        AvatarImage(
                            publicKey = account.publicKey,
                            avatarRepository = avatarRepository,
                            size = 36.dp,
                            isDarkTheme = isDarkTheme,
                            displayName = displayName
                        )
                        if (isCurrentAccount) {
                            Box(
                                modifier =
                                    Modifier.align(Alignment.BottomEnd).size(14.dp).background(
                                        color = drawerBackgroundColor,
                                        shape = CircleShape
                                    ).padding(1.5.dp).background(
                                        color = Color(0xFF50A7EA),
                                        shape = CircleShape
                                    ),
                                contentAlignment = Alignment.Center
                            ) {
                                Icon(
                                    painter = TelegramIcons.Done,
                                    contentDescription = null,
                                    tint = Color.White,
                                    modifier = Modifier.size(8.dp).offset(x = 0.3.dp, y = 0.dp)
                                )
                            }
                        }
                    }

                    Spacer(modifier = Modifier.width(22.dp))

                    Text(
                        text = displayName,
                        fontSize = 15.sp,
                        fontWeight = FontWeight.Bold,
                        color =
                            if (isDarkTheme) Color(0xFFF4FFFFFF.toInt()) else Color(0xFF444444),
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                        modifier = Modifier.weight(1f)
                    )
                }
            }

            Row(
                modifier =
                    Modifier.fillMaxWidth().height(48.dp).clickable(onClick = onAddAccountClick)
                        .padding(start = 14.dp, end = 16.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Box(modifier = Modifier.size(36.dp), contentAlignment = Alignment.Center) {
                    Icon(
                        painter = TelegramIcons.Add,
                        contentDescription = "Add Account",
                        tint = if (isDarkTheme) Color(0xFF828282) else Color(0xFF889198),
                        modifier = Modifier.size(22.dp)
                    )
                }

                Spacer(modifier = Modifier.width(22.dp))

                Text(
                    text = "Add Account",
                    fontSize = 15.sp,
                    fontWeight = FontWeight.Bold,
                    color = if (isDarkTheme) Color(0xFFF4FFFFFF.toInt()) else Color(0xFF444444),
                    maxLines = 1
                )
            }

            Divider(
                color = if (isDarkTheme) Color(0xFF2A2A2A) else Color(0xFFE8E8E8),
                thickness = 0.5.dp
            )
        }
    }
}

@Composable
fun ChatsDrawerFooter(
    isDarkTheme: Boolean,
    appVersion: String,
    updateState: UpdateState,
    onUpdateClick: (UpdateState) -> Unit
) {
    Column(
        modifier =
            Modifier.fillMaxWidth().windowInsetsPadding(
                WindowInsets.navigationBars.only(WindowInsetsSides.Bottom)
            )
    ) {
        val showUpdateBanner =
            updateState is UpdateState.UpdateAvailable ||
                updateState is UpdateState.Downloading ||
                updateState is UpdateState.ReadyToInstall

        Divider(
            color = if (isDarkTheme) Color(0xFF2A2A2A) else Color(0xFFE8E8E8),
            thickness = 0.5.dp
        )

        if (!showUpdateBanner) {
            Row(
                modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 12.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "Rosetta v$appVersion",
                    fontSize = 12.sp,
                    color = if (isDarkTheme) Color(0xFF666666) else Color(0xFF999999)
                )
            }
            Spacer(modifier = Modifier.height(16.dp))
        }

        if (showUpdateBanner) {
            Box(
                modifier =
                    Modifier.fillMaxWidth().height(50.dp).background(
                        Brush.horizontalGradient(
                            colors = listOf(Color(0xFF69BF72), Color(0xFF53B3AD))
                        )
                    ).clickable { onUpdateClick(updateState) },
                contentAlignment = Alignment.CenterStart
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        imageVector =
                            when (updateState) {
                                is UpdateState.Downloading -> TablerIcons.X
                                else -> TablerIcons.Download
                            },
                        contentDescription = null,
                        tint = Color.White,
                        modifier = Modifier.size(22.dp)
                    )
                    Spacer(modifier = Modifier.width(12.dp))
                    Text(
                        text =
                            when (updateState) {
                                is UpdateState.Downloading -> "Downloading... ${updateState.progress}%"
                                is UpdateState.ReadyToInstall -> "Install Update"
                                is UpdateState.UpdateAvailable -> "Update Rosetta"
                                else -> ""
                            },
                        color = Color.White,
                        fontSize = 15.sp,
                        fontWeight = FontWeight.Bold,
                        modifier = Modifier.weight(1f)
                    )
                    if (updateState is UpdateState.UpdateAvailable) {
                        Text(
                            text = updateState.version,
                            color = Color.White.copy(alpha = 0.8f),
                            fontSize = 13.sp,
                            fontWeight = FontWeight.Medium
                        )
                    }
                    if (updateState is UpdateState.Downloading) {
                        CircularProgressIndicator(
                            progress = updateState.progress / 100f,
                            modifier = Modifier.size(20.dp),
                            color = Color.White,
                            trackColor = Color.White.copy(alpha = 0.3f),
                            strokeWidth = 2.dp
                        )
                    }
                }
            }
            Spacer(modifier = Modifier.height(12.dp))
        }
    }
}
