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

import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
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.size
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.Edit
import androidx.compose.material.icons.outlined.Image
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
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.res.painterResource
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.seven.ikar.kotlin.R
import com.seven.ikar.kotlin.ui.AvatarView
import com.seven.ikar.kotlin.ui.IkarCenteredHeader
import com.seven.ikar.kotlin.ui.IkarFloatingMainMenu
import com.seven.ikar.kotlin.ui.IkarMainMenuTab
import com.seven.ikar.kotlin.ui.IkarPillCard
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 ProfileScreen(
    state: ProfileUiState,
    onSettingsClick: () -> Unit,
    onLogoutClick: () -> Unit,
    onManageAvatarClick: (Uri) -> Unit,
    onChatsClick: () -> Unit,
    onContactsClick: () -> Unit,
    onProfileClick: () -> Unit,
    onSettingsTabClick: () -> Unit
) {
    val avatarPicker = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
        if (uri != null) {
            onManageAvatarClick(uri)
        }
    }
    val statusText = state.session?.user?.let(::formatPresence) ?: "был давно"

    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)
        ) {
            IkarCenteredHeader(
                title = "Профиль",
                left = {
                    Image(
                        painter = painterResource(id = R.drawable.ikar_logo),
                        contentDescription = "Икар"
                    )
                },
                right = {}
            )

            Column(
                modifier = Modifier.fillMaxWidth(),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.spacedBy(10.dp)
            ) {
                AvatarView(
                    imageUrl = state.avatarUrl,
                    title = state.displayName.ifBlank { state.phoneNumber.ifBlank { "ИКАР" } },
                    size = 108.dp
                )

                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.spacedBy(2.dp)
                ) {
                    Text(
                        text = state.displayName.ifBlank { "Без имени" },
                        style = MaterialTheme.typography.displayLarge,
                        fontWeight = FontWeight.SemiBold
                    )
                    Text(
                        text = statusText,
                        style = MaterialTheme.typography.bodyMedium,
                        color = TelegramInkMuted
                    )
                }
            }

            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(10.dp)
            ) {
                ProfileActionCard(
                    modifier = Modifier.weight(1f),
                    title = "Выбрать фото",
                    iconTint = TelegramBlue,
                    onClick = {
                        avatarPicker.launch(
                            PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
                        )
                    }
                ) { tint ->
                    Icon(
                        imageVector = Icons.Outlined.Image,
                        contentDescription = null,
                        tint = tint,
                        modifier = Modifier.size(30.dp)
                    )
                }
                ProfileActionCard(
                    modifier = Modifier.weight(1f),
                    title = "Изменить",
                    iconTint = TelegramBlue,
                    onClick = onSettingsClick
                ) { tint ->
                    Icon(
                        imageVector = Icons.Outlined.Edit,
                        contentDescription = null,
                        tint = tint,
                        modifier = Modifier.size(30.dp)
                    )
                }
                ProfileActionCard(
                    modifier = Modifier.weight(1f),
                    title = "Выход",
                    iconTint = TelegramDanger,
                    textColor = TelegramDanger,
                    onClick = onLogoutClick
                ) { tint ->
                    Icon(
                        imageVector = Icons.Outlined.Close,
                        contentDescription = null,
                        tint = tint,
                        modifier = Modifier.size(30.dp)
                    )
                }
            }

            IkarSectionCard {
                IkarProfileInfo(
                    value = state.phoneNumber.ifBlank { "Номер не загружен" },
                    subtitle = "Телефон"
                )
                com.seven.ikar.kotlin.ui.IkarRowDivider(startIndent = 0.dp)
                IkarProfileInfo(
                    value = state.displayName.ifBlank { "Без имени" },
                    subtitle = "Отображаемое имя"
                )
                com.seven.ikar.kotlin.ui.IkarRowDivider(startIndent = 0.dp)
                IkarProfileInfo(
                    value = statusText,
                    subtitle = "Состояние"
                )
            }

            state.errorMessage?.let {
                Text(it, color = TelegramDanger, style = MaterialTheme.typography.bodyMedium)
            }
            state.infoMessage?.let {
                Text(
                    text = it,
                    color = TelegramBlue,
                    style = MaterialTheme.typography.bodyMedium,
                    fontWeight = FontWeight.SemiBold
                )
            }

            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 116.dp)
            )
        }

        IkarFloatingMainMenu(
            selectedTab = IkarMainMenuTab.Profile,
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .padding(horizontal = 8.dp, vertical = 18.dp),
            onChatsClick = onChatsClick,
            onContactsClick = onContactsClick,
            onSettingsClick = onSettingsTabClick,
            onProfileClick = onProfileClick
        )
    }
}

@Composable
private fun IkarProfileInfo(
    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 ProfileActionCard(
    title: String,
    iconTint: Color,
    modifier: Modifier = Modifier,
    textColor: Color? = null,
    onClick: () -> Unit,
    icon: @Composable (Color) -> Unit
) {
    val resolvedTextColor = textColor ?: MaterialTheme.colorScheme.onSurface
    IkarPillCard(
        modifier = modifier.height(104.dp),
        onClick = onClick,
        contentPadding = PaddingValues(horizontal = 8.dp, vertical = 10.dp)
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(42.dp),
            contentAlignment = Alignment.Center
        ) {
            icon(iconTint)
        }
        Text(
            text = title,
            modifier = Modifier.fillMaxWidth(),
            style = MaterialTheme.typography.labelMedium.copy(
                fontSize = 11.sp,
                lineHeight = 11.sp
            ),
            color = resolvedTextColor,
            textAlign = TextAlign.Center,
            maxLines = 1,
            softWrap = false
        )
    }
}
