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.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
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.text.BasicTextField
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.clickable
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Edit
import androidx.compose.material.icons.outlined.Info
import androidx.compose.material.icons.outlined.Phone
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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 com.seven.ikar.kotlin.ui.AvatarView
import com.seven.ikar.kotlin.ui.IkarSectionCard
import com.seven.ikar.kotlin.ui.IkarSimpleHeader
import com.seven.ikar.kotlin.ui.IkarScreenSurface
import com.seven.ikar.kotlin.ui.theme.TelegramBlue
import com.seven.ikar.kotlin.ui.theme.TelegramDanger
import com.seven.ikar.kotlin.ui.theme.TelegramInkMuted
import com.seven.ikar.kotlin.ui.theme.TelegramSurface

@Composable
fun AccountSettingsScreen(
    state: ProfileUiState,
    onBackClick: () -> Unit,
    onDisplayNameChanged: (String) -> Unit,
    onAboutChanged: (String) -> Unit,
    onSaveClick: () -> Unit,
    onDeleteAvatarClick: () -> Unit,
    onAvatarSelected: (Uri) -> Unit
) {
    val avatarPicker = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
        if (uri != null) {
            onAvatarSelected(uri)
        }
    }

    IkarScreenSurface(modifier = Modifier.fillMaxSize()) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .windowInsetsPadding(WindowInsets.safeDrawing.only(WindowInsetsSides.Vertical))
                .verticalScroll(rememberScrollState())
                .padding(horizontal = 18.dp, vertical = 16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            IkarSimpleHeader(title = "Аккаунт", onBackClick = onBackClick)

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

                    Button(
                        onClick = {
                            avatarPicker.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
                        }
                    ) {
                        Text(if (state.avatarUrl.isNullOrBlank()) "Добавить фото профиля" else "Изменить фото профиля")
                    }

                    if (!state.avatarUrl.isNullOrBlank()) {
                        Text(
                            text = "Удалить фото",
                            modifier = Modifier
                                .padding(top = 2.dp)
                                .clickable(onClick = onDeleteAvatarClick),
                            style = MaterialTheme.typography.titleMedium.copy(color = TelegramDanger),
                            fontWeight = FontWeight.SemiBold
                        )
                        Text(
                            text = "Нажмите на надпись, чтобы удалить текущее фото",
                            color = TelegramInkMuted,
                            style = MaterialTheme.typography.bodySmall
                        )
                    }
                }
            }

            IkarSectionCard {
                IkarInfoLine(
                    icon = Icons.Outlined.Phone,
                    title = state.phoneNumber.ifBlank { "Номер не загружен" },
                    subtitle = "Нажмите, чтобы изменить номер телефона"
                )

                androidx.compose.foundation.layout.Spacer(modifier = Modifier.padding(top = 12.dp))
                androidx.compose.foundation.layout.Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(start = 54.dp)
                        .height(1.dp)
                        .background(com.seven.ikar.kotlin.ui.theme.TelegramBorder)
                )
                androidx.compose.foundation.layout.Spacer(modifier = Modifier.padding(top = 12.dp))

                IkarInfoLine(
                    icon = Icons.Outlined.Info,
                    title = "Указать день рождения",
                    subtitle = "Поля дня рождения и его видимости будут добавлены отдельно."
                )
            }

            IkarSectionCard {
                Text("Ваше имя", style = MaterialTheme.typography.labelLarge, color = TelegramBlue)
                androidx.compose.foundation.layout.Spacer(modifier = Modifier.padding(top = 10.dp))
                IkarTextInput(
                    value = state.displayName,
                    onValueChange = onDisplayNameChanged,
                    placeholder = "Введите отображаемое имя"
                )
            }

            IkarSectionCard {
                Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                    Text("О себе", style = MaterialTheme.typography.labelLarge, color = TelegramBlue)
                    Text("${state.about.length}/200", style = MaterialTheme.typography.bodySmall, color = TelegramInkMuted)
                }
                androidx.compose.foundation.layout.Spacer(modifier = Modifier.padding(top = 10.dp))
                IkarTextInput(
                    value = state.about,
                    onValueChange = onAboutChanged,
                    placeholder = "Напишите что-нибудь о себе...",
                    minLines = 4
                )
                androidx.compose.foundation.layout.Spacer(modifier = Modifier.padding(top = 8.dp))
                Text(
                    "Вы можете добавить несколько строк о себе. Сейчас это поле сохраняется в профиле Ikar.",
                    color = TelegramInkMuted,
                    style = MaterialTheme.typography.bodySmall
                )
            }

            IkarSectionCard {
                Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
                    Surface(
                        modifier = Modifier.size(40.dp),
                        color = Color(0xFFEFF6FD),
                        shape = androidx.compose.foundation.shape.CircleShape
                    ) {
                        androidx.compose.foundation.layout.Box(contentAlignment = androidx.compose.ui.Alignment.Center) {
                            androidx.compose.material3.Icon(Icons.Outlined.Edit, contentDescription = null, tint = TelegramBlue)
                        }
                    }
                    Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
                        Text("Добавить личный канал", style = MaterialTheme.typography.titleLarge)
                        Text(
                            "Этот сценарий будет доведён отдельным экраном. Сейчас основной профиль уже перенесён.",
                            style = MaterialTheme.typography.bodySmall,
                            color = TelegramInkMuted
                        )
                    }
                }
            }

            Button(
                onClick = onSaveClick,
                enabled = !state.isLoading && !state.isSaving,
                modifier = Modifier.fillMaxWidth()
            ) {
                Text(if (state.isSaving) "Сохранение..." else "Сохранить")
            }

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

@Composable
private fun IkarInfoLine(
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    title: String,
    subtitle: String
) {
    Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
        Surface(
            modifier = Modifier.size(32.dp),
            color = TelegramSurface,
            shape = androidx.compose.foundation.shape.CircleShape
        ) {
            androidx.compose.foundation.layout.Box(contentAlignment = androidx.compose.ui.Alignment.Center) {
                androidx.compose.material3.Icon(icon, contentDescription = null, tint = TelegramInkMuted)
            }
        }
        Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
            Text(title, style = MaterialTheme.typography.titleLarge)
            Text(subtitle, style = MaterialTheme.typography.bodySmall, color = TelegramInkMuted)
        }
    }
}

@Composable
private fun IkarTextInput(
    value: String,
    onValueChange: (String) -> Unit,
    placeholder: String,
    minLines: Int = 1
) {
    Surface(
        modifier = Modifier.fillMaxWidth(),
        color = TelegramSurface,
        shape = androidx.compose.foundation.shape.RoundedCornerShape(18.dp)
    ) {
        BasicTextField(
            value = value,
            onValueChange = onValueChange,
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 14.dp, vertical = 12.dp),
            textStyle = MaterialTheme.typography.bodyLarge.copy(color = MaterialTheme.colorScheme.onSurface),
            minLines = minLines,
            decorationBox = { innerTextField ->
                if (value.isBlank()) {
                    Text(placeholder, color = TelegramInkMuted, style = MaterialTheme.typography.bodyLarge)
                }
                innerTextField()
            }
        )
    }
}
