package com.seven.ikar.kotlin.feature.profile

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
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.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
import androidx.compose.material.icons.outlined.Refresh
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
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.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.seven.ikar.kotlin.ui.AuthenticatedAsyncImage
import com.seven.ikar.kotlin.ui.AvatarView
import com.seven.ikar.kotlin.ui.IkarHeaderIconBubble
import com.seven.ikar.kotlin.ui.IkarRowDivider
import com.seven.ikar.kotlin.ui.IkarRoundedTag
import com.seven.ikar.kotlin.ui.IkarScreenSurface
import com.seven.ikar.kotlin.ui.IkarSectionCard
import com.seven.ikar.kotlin.ui.formatPresence
import com.seven.ikar.kotlin.ui.theme.TelegramBlue
import com.seven.ikar.kotlin.ui.theme.TelegramDanger
import com.seven.ikar.kotlin.ui.theme.TelegramInkMuted

@Composable
fun PeerProfileScreen(
    state: PeerProfileUiState,
    onBackClick: () -> Unit,
    onRefreshClick: () -> Unit
) {
    val user = state.user
    val displayName = user?.displayName?.takeIf { it.isNotBlank() }
        ?: user?.phoneNumber?.takeIf { !it.isNullOrBlank() }
        ?: "Профиль"
    val usernameText = user?.username?.takeIf { it.isNotBlank() }?.let { "@$it" } ?: "Без имени пользователя"
    val aboutText = user?.about?.takeIf { it.isNotBlank() }
    val statusText = user?.let(::formatPresence) ?: "был давно"
    var showAvatarPreview by rememberSaveable(state.userId) { mutableStateOf(false) }

    IkarScreenSurface(modifier = Modifier.fillMaxSize()) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .windowInsetsPadding(WindowInsets.safeDrawing.only(WindowInsetsSides.Vertical))
                .verticalScroll(rememberScrollState())
                .padding(horizontal = 18.dp, vertical = 18.dp),
            verticalArrangement = Arrangement.spacedBy(18.dp)
        ) {
            Box(
                modifier = Modifier.fillMaxWidth(),
                contentAlignment = Alignment.Center
            ) {
                IkarHeaderIconBubble(
                    modifier = Modifier.align(Alignment.CenterStart),
                    onClick = onBackClick
                ) {
                    Icon(
                        imageVector = Icons.AutoMirrored.Outlined.ArrowBack,
                        contentDescription = "Назад",
                        tint = MaterialTheme.colorScheme.onSurface
                    )
                }
                Text(
                    text = "Профиль",
                    style = MaterialTheme.typography.displayLarge,
                    maxLines = 1
                )
                IkarHeaderIconBubble(
                    modifier = Modifier.align(Alignment.CenterEnd),
                    onClick = onRefreshClick
                ) {
                    Icon(
                        imageVector = Icons.Outlined.Refresh,
                        contentDescription = "Обновить",
                        tint = MaterialTheme.colorScheme.onSurface
                    )
                }
            }

            Column(
                modifier = Modifier.fillMaxWidth(),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.spacedBy(10.dp)
            ) {
                Box(
                    modifier = Modifier
                        .clip(CircleShape)
                        .clickable(
                            enabled = !state.avatarUrl.isNullOrBlank(),
                            interactionSource = remember { MutableInteractionSource() },
                            indication = null
                        ) {
                            showAvatarPreview = true
                        }
                ) {
                    AvatarView(
                        imageUrl = state.avatarUrl,
                        title = displayName,
                        accessToken = state.accessToken,
                        size = 112.dp
                    )
                }

                Text(
                    text = displayName,
                    style = MaterialTheme.typography.displayLarge,
                    fontWeight = FontWeight.SemiBold
                )
                Text(
                    text = statusText,
                    style = MaterialTheme.typography.bodyMedium,
                    color = TelegramInkMuted
                )
                if (user?.isBot == true) {
                    IkarRoundedTag(text = "Бот")
                }
            }

            IkarSectionCard {
                PeerProfileInfo(
                    value = user?.phoneNumber?.takeIf { it.isNotBlank() } ?: "Телефон не указан",
                    subtitle = "Телефон"
                )
                IkarRowDivider(startIndent = 0.dp)
                PeerProfileInfo(value = usernameText, subtitle = "Имя пользователя")
                IkarRowDivider(startIndent = 0.dp)
                PeerProfileInfo(value = statusText, subtitle = "Статус")
            }

            aboutText?.let {
                IkarSectionCard {
                    PeerProfileInfo(value = it, subtitle = "О себе")
                }
            }

            state.errorMessage?.let {
                Text(it, color = TelegramDanger, style = MaterialTheme.typography.bodyMedium)
            }

            Spacer(modifier = Modifier.height(24.dp))
        }

        if (state.isLoading && user == null) {
            CircularProgressIndicator(
                modifier = Modifier.align(Alignment.Center),
                color = TelegramBlue
            )
        }

        if (showAvatarPreview && !state.avatarUrl.isNullOrBlank()) {
            PeerAvatarPreview(
                imageUrl = state.avatarUrl,
                accessToken = state.accessToken,
                title = displayName,
                onDismiss = { showAvatarPreview = false }
            )
        }
    }
}

@Composable
private fun PeerProfileInfo(
    value: String,
    subtitle: String
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 12.dp),
        verticalArrangement = Arrangement.spacedBy(2.dp)
    ) {
        Text(value, style = MaterialTheme.typography.titleLarge)
        Text(subtitle, style = MaterialTheme.typography.bodySmall, color = TelegramInkMuted)
    }
}

@Composable
private fun PeerAvatarPreview(
    imageUrl: String,
    accessToken: String?,
    title: String,
    onDismiss: () -> Unit
) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Black.copy(alpha = 0.55f))
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = null,
                onClick = onDismiss
            )
    ) {
        Surface(
            modifier = Modifier
                .align(Alignment.TopCenter)
                .fillMaxWidth()
                .fillMaxHeight(0.4f)
                .clickable(
                    interactionSource = remember { MutableInteractionSource() },
                    indication = null,
                    onClick = {}
                ),
            shape = RoundedCornerShape(bottomStart = 28.dp, bottomEnd = 28.dp),
            color = Color.Black
        ) {
            AuthenticatedAsyncImage(
                imageUrl = imageUrl,
                accessToken = accessToken,
                contentDescription = title,
                modifier = Modifier.fillMaxSize(),
                contentScale = ContentScale.Crop
            )
        }

        TextButton(
            modifier = Modifier
                .align(Alignment.TopEnd)
                .statusBarsPadding()
                .padding(top = 10.dp, end = 12.dp),
            onClick = onDismiss
        ) {
            Text("Закрыть", color = Color.White)
        }
    }
}
