package com.seven.ikar.kotlin.feature.discover

import android.Manifest
import android.content.pm.PackageManager
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
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.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
import androidx.compose.material.icons.outlined.Group
import androidx.compose.material.icons.outlined.Menu
import androidx.compose.material.icons.outlined.Speaker
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import com.seven.ikar.kotlin.core.contacts.DiscoverUserItem
import com.seven.ikar.kotlin.ui.AvatarView
import com.seven.ikar.kotlin.ui.IkarCenteredHeader
import com.seven.ikar.kotlin.ui.IkarHeaderIconBubble
import com.seven.ikar.kotlin.ui.IkarRowDivider
import com.seven.ikar.kotlin.ui.IkarScreenSurface
import com.seven.ikar.kotlin.ui.IkarSearchCard
import com.seven.ikar.kotlin.ui.IkarSectionCard
import com.seven.ikar.kotlin.ui.IkarToggleRow
import com.seven.ikar.kotlin.ui.formatDiscoverPresence
import com.seven.ikar.kotlin.ui.formatPresenceColor
import com.seven.ikar.kotlin.ui.theme.TelegramBlue
import com.seven.ikar.kotlin.ui.theme.TelegramBluePanel
import com.seven.ikar.kotlin.ui.theme.TelegramInkMuted

@Composable
fun DiscoverScreen(
    state: DiscoverUiState,
    onBackClick: () -> Unit,
    onQueryChanged: (String) -> Unit,
    onRefreshClick: () -> Unit,
    onUserClick: (DiscoverUserItem) -> Unit,
    onBeginGroupSelection: () -> Unit,
    onBeginChannelSelection: () -> Unit,
    onCancelSelection: () -> Unit,
    onChannelBackClick: () -> Unit,
    onChannelTitleChanged: (String) -> Unit,
    onChannelDescriptionChanged: (String) -> Unit,
    onChannelVisibilityChanged: (ChannelVisibility) -> Unit,
    onChannelPublicUsernameChanged: (String) -> Unit,
    onChannelSignaturesChanged: (Boolean) -> Unit,
    onContinueChannelWizard: () -> Unit,
    onCompleteSelection: () -> Unit
) {
    val context = LocalContext.current
    val permissionLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
        if (granted) {
            onRefreshClick()
        }
    }
    val hasContactsPermission =
        ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED
    val isChannelWizard = state.channelWizardStep != null
    val showContacts = state.selectionMode != null || state.channelWizardStep == null

    LaunchedEffect(hasContactsPermission) {
        if (hasContactsPermission) {
            onRefreshClick()
        }
    }

    IkarScreenSurface(modifier = Modifier.fillMaxSize()) {
        Column(modifier = Modifier.fillMaxSize()) {
            Column(
                modifier = Modifier.padding(start = 18.dp, top = 16.dp, end = 18.dp, bottom = 12.dp),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                IkarCenteredHeader(
                    title = when {
                        isChannelWizard -> "Новый канал"
                        state.selectionMode == DiscoverSelectionMode.Group -> "Новая группа"
                        else -> "Новое сообщение"
                    },
                    left = {
                        IkarHeaderIconBubble(
                            onClick = if (isChannelWizard) onChannelBackClick else onBackClick
                        ) {
                            Icon(Icons.AutoMirrored.Outlined.ArrowBack, contentDescription = "Назад", tint = MaterialTheme.colorScheme.onSurface)
                        }
                    },
                    right = {
                        if (!isChannelWizard && state.selectionMode == null) {
                            IkarHeaderIconBubble {
                                Icon(Icons.Outlined.Menu, contentDescription = null, tint = MaterialTheme.colorScheme.onSurface)
                            }
                        }
                    }
                )

                if (!hasContactsPermission && showContacts) {
                    IkarPermissionCard(onGrantClick = { permissionLauncher.launch(Manifest.permission.READ_CONTACTS) })
                }

                if (showContacts) {
                    IkarSearchCard(
                        value = state.query,
                        onValueChange = onQueryChanged,
                        placeholder = if (state.selectionMode == DiscoverSelectionMode.Channel) "Поиск подписчиков" else "Поиск контактов"
                    )
                }

                when (state.channelWizardStep) {
                    ChannelWizardStep.Details -> ChannelDetailsStep(
                        state = state,
                        onTitleChanged = onChannelTitleChanged,
                        onDescriptionChanged = onChannelDescriptionChanged,
                        onCancelClick = onCancelSelection,
                        onNextClick = onContinueChannelWizard
                    )

                    ChannelWizardStep.Type -> ChannelTypeStep(
                        state = state,
                        onVisibilityChanged = onChannelVisibilityChanged,
                        onPublicUsernameChanged = onChannelPublicUsernameChanged,
                        onSignaturesChanged = onChannelSignaturesChanged,
                        onBackClick = onChannelBackClick,
                        onNextClick = onContinueChannelWizard
                    )

                    ChannelWizardStep.Subscribers -> SelectionBanner(
                        title = "Добавить подписчиков",
                        subtitle = "Можно создать канал сейчас и пригласить людей позже.",
                        selectedCount = state.selectedUserIds.size,
                        actionText = if (state.isLoading) "Создание..." else "Создать",
                        onBackClick = onChannelBackClick,
                        onActionClick = onCompleteSelection,
                        enabled = !state.isLoading
                    )

                    null -> {
                        if (state.selectionMode == null) {
                            IkarSectionCard(padding = PaddingValues(0.dp)) {
                                DiscoverActionRow(
                                    icon = Icons.Outlined.Group,
                                    title = "Создать группу",
                                    subtitle = "Выбрать участников и открыть общий чат.",
                                    onClick = onBeginGroupSelection
                                )
                                IkarRowDivider(startIndent = 56.dp)
                                DiscoverActionRow(
                                    icon = Icons.Outlined.Speaker,
                                    title = "Создать канал",
                                    subtitle = "Открыть канал и пригласить подписчиков.",
                                    onClick = onBeginChannelSelection
                                )
                            }
                        } else {
                            SelectionBanner(
                                title = "Новая группа",
                                subtitle = "Выберите участников",
                                selectedCount = state.selectedUserIds.size,
                                actionText = if (state.isLoading) "Создание..." else "Создать",
                                onBackClick = onCancelSelection,
                                onActionClick = onCompleteSelection,
                                enabled = !state.isLoading
                            )
                        }
                    }
                }

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

            if (showContacts) {
                ContactsSection(
                    modifier = Modifier.weight(1f),
                    state = state,
                    onUserClick = onUserClick
                )
            }
        }
    }
}

@Composable
private fun ChannelDetailsStep(
    state: DiscoverUiState,
    onTitleChanged: (String) -> Unit,
    onDescriptionChanged: (String) -> Unit,
    onCancelClick: () -> Unit,
    onNextClick: () -> Unit
) {
    IkarSectionCard {
        WizardStepIndicator(currentStep = 1)
        Row(
            horizontalArrangement = Arrangement.spacedBy(14.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Surface(
                modifier = Modifier.size(64.dp),
                color = TelegramBluePanel,
                shape = CircleShape
            ) {
                Box(contentAlignment = Alignment.Center) {
                    Icon(Icons.Outlined.Speaker, contentDescription = null, tint = TelegramBlue, modifier = Modifier.size(30.dp))
                }
            }
            Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(10.dp)) {
                OutlinedTextField(
                    value = state.channelTitle,
                    onValueChange = onTitleChanged,
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    label = { Text("Название канала") }
                )
                OutlinedTextField(
                    value = state.channelDescription,
                    onValueChange = onDescriptionChanged,
                    modifier = Modifier.fillMaxWidth(),
                    minLines = 3,
                    maxLines = 4,
                    label = { Text("Описание") }
                )
            }
        }
        StepActions(
            backText = "Отмена",
            nextText = "Далее",
            onBackClick = onCancelClick,
            onNextClick = onNextClick,
            nextEnabled = state.channelTitle.isNotBlank()
        )
    }
}

@Composable
private fun ChannelTypeStep(
    state: DiscoverUiState,
    onVisibilityChanged: (ChannelVisibility) -> Unit,
    onPublicUsernameChanged: (String) -> Unit,
    onSignaturesChanged: (Boolean) -> Unit,
    onBackClick: () -> Unit,
    onNextClick: () -> Unit
) {
    val isPublic = state.channelVisibility == ChannelVisibility.Public
    IkarSectionCard {
        WizardStepIndicator(currentStep = 2)
        ChannelVisibilityRow(
            title = "Публичный канал",
            subtitle = "Канал будет виден в поиске и доступен по короткой ссылке.",
            selected = isPublic,
            onClick = { onVisibilityChanged(ChannelVisibility.Public) }
        )
        IkarRowDivider(startIndent = 0.dp)
        ChannelVisibilityRow(
            title = "Приватный канал",
            subtitle = "Войти можно будет по приглашению или invite-ссылке.",
            selected = state.channelVisibility == ChannelVisibility.Private,
            onClick = { onVisibilityChanged(ChannelVisibility.Private) }
        )
        if (isPublic) {
            OutlinedTextField(
                value = state.channelPublicUsername,
                onValueChange = onPublicUsernameChanged,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 10.dp),
                singleLine = true,
                prefix = { Text("@") },
                label = { Text("Публичная ссылка") },
                supportingText = { Text("Минимум 5 символов: латиница, цифры и _") }
            )
        }
        IkarToggleRow(
            title = "Подписи администраторов",
            subtitle = "Имя автора будет показано рядом с публикацией.",
            checked = state.channelSignaturesEnabled,
            onCheckedChange = onSignaturesChanged,
            leading = {
                Icon(Icons.Outlined.Speaker, contentDescription = null, tint = TelegramInkMuted)
            }
        )
        StepActions(
            backText = "Назад",
            nextText = "Далее",
            onBackClick = onBackClick,
            onNextClick = onNextClick,
            nextEnabled = !isPublic || state.channelPublicUsername.length >= 5
        )
    }
}

@Composable
private fun ChannelVisibilityRow(
    title: String,
    subtitle: String,
    selected: Boolean,
    onClick: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .padding(vertical = 12.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        RadioButton(selected = selected, onClick = onClick)
        Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
            Text(title, style = MaterialTheme.typography.titleLarge)
            Text(subtitle, style = MaterialTheme.typography.bodySmall, color = TelegramInkMuted)
        }
    }
}

@Composable
private fun SelectionBanner(
    title: String,
    subtitle: String,
    selectedCount: Int,
    actionText: String,
    onBackClick: () -> Unit,
    onActionClick: () -> Unit,
    enabled: Boolean
) {
    Surface(
        modifier = Modifier.fillMaxWidth(),
        color = TelegramBluePanel,
        shape = RoundedCornerShape(20.dp)
    ) {
        Row(
            modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp),
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                Icons.AutoMirrored.Outlined.ArrowBack,
                contentDescription = "Назад",
                tint = TelegramBlue,
                modifier = Modifier.clickable(enabled = enabled, onClick = onBackClick)
            )
            Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
                Text(title, style = MaterialTheme.typography.titleMedium, color = TelegramBlue)
                Text(subtitle, style = MaterialTheme.typography.bodySmall, color = TelegramInkMuted)
            }
            Text(selectedCount.toString(), style = MaterialTheme.typography.titleMedium)
            Button(onClick = onActionClick, enabled = enabled) {
                Text(actionText)
            }
        }
    }
}

@Composable
private fun StepActions(
    backText: String,
    nextText: String,
    onBackClick: () -> Unit,
    onNextClick: () -> Unit,
    nextEnabled: Boolean
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.End,
        verticalAlignment = Alignment.CenterVertically
    ) {
        TextButton(onClick = onBackClick) {
            Text(backText)
        }
        Button(onClick = onNextClick, enabled = nextEnabled) {
            Text(nextText)
        }
    }
}

@Composable
private fun WizardStepIndicator(currentStep: Int) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        (1..3).forEach { step ->
            Surface(
                modifier = Modifier
                    .height(4.dp)
                    .weight(1f),
                color = if (step <= currentStep) TelegramBlue else TelegramBluePanel,
                shape = RoundedCornerShape(2.dp)
            ) {}
        }
        Text(
            "$currentStep/3",
            style = MaterialTheme.typography.labelMedium,
            color = TelegramInkMuted,
            fontWeight = FontWeight.SemiBold
        )
    }
}

@Composable
private fun ContactsSection(
    modifier: Modifier = Modifier,
    state: DiscoverUiState,
    onUserClick: (DiscoverUserItem) -> Unit
) {
    IkarSectionCard(
        modifier = modifier
            .fillMaxWidth()
            .padding(horizontal = 18.dp)
            .padding(bottom = 24.dp),
        padding = PaddingValues(0.dp)
    ) {
        Text(
            "Сортировка по времени захода",
            modifier = Modifier.padding(start = 18.dp, top = 16.dp, end = 18.dp, bottom = 8.dp),
            style = MaterialTheme.typography.labelLarge,
            color = TelegramBlue
        )

        LazyColumn {
            if (state.items.isEmpty()) {
                item {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = 24.dp, vertical = 28.dp),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        Text("Контакты не найдены", style = MaterialTheme.typography.headlineMedium)
                        Text(
                            "Разрешите доступ к контактам и убедитесь, что нужные люди зарегистрированы по номеру телефона.",
                            color = TelegramInkMuted,
                            style = MaterialTheme.typography.bodyMedium
                        )
                    }
                }
            } else {
                items(state.items, key = { it.id }) { item ->
                    DiscoverUserRow(
                        item = item,
                        isSelected = state.selectedUserIds.contains(item.id),
                        onClick = { onUserClick(item) }
                    )
                }
            }
        }
    }
}

@Composable
private fun IkarPermissionCard(onGrantClick: () -> Unit) {
    IkarSectionCard {
        Text("Нужен доступ к контактам", style = MaterialTheme.typography.headlineMedium)
        Text(
            "Без него не получится показать знакомых из телефонной книги.",
            style = MaterialTheme.typography.bodyMedium,
            color = TelegramInkMuted
        )
        Spacer(modifier = Modifier.padding(top = 8.dp))
        Button(onClick = onGrantClick) {
            Text("Разрешить доступ")
        }
    }
}

@Composable
private fun DiscoverActionRow(
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    title: String,
    subtitle: String,
    onClick: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .padding(horizontal = 18.dp, vertical = 16.dp),
        horizontalArrangement = Arrangement.spacedBy(14.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Icon(icon, contentDescription = null, tint = TelegramBlue, modifier = Modifier.size(24.dp))
        Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
            Text(title, style = MaterialTheme.typography.headlineMedium)
            Text(subtitle, style = MaterialTheme.typography.bodySmall, color = TelegramInkMuted)
        }
    }
}

@Composable
private fun DiscoverUserRow(
    item: DiscoverUserItem,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    Column {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .clickable(onClick = onClick)
                .padding(horizontal = 18.dp, vertical = 12.dp),
            horizontalArrangement = Arrangement.spacedBy(14.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Box {
                AvatarView(imageUrl = item.avatarUrl, title = item.displayName, size = 54.dp)
                if (isSelected) {
                    Surface(
                        modifier = Modifier
                            .align(Alignment.BottomEnd)
                            .size(20.dp),
                        color = TelegramBlue,
                        shape = CircleShape
                    ) {
                        Box(contentAlignment = Alignment.Center) {
                            Text("✓", color = Color.White, style = MaterialTheme.typography.labelSmall)
                        }
                    }
                }
            }
            Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
                Text(item.displayName, style = MaterialTheme.typography.titleLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
                Text(
                    formatDiscoverPresence(item),
                    style = MaterialTheme.typography.bodySmall,
                    color = formatPresenceColor(item)
                )
            }
        }
        IkarRowDivider(startIndent = 86.dp)
    }
}
