package com.seven.ikar.kotlin.feature.contacts

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.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.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.Menu
import androidx.compose.material.icons.outlined.PersonAddAlt1
import androidx.compose.material.icons.outlined.PhoneInTalk
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
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.IkarFab
import com.seven.ikar.kotlin.ui.IkarFloatingMainMenu
import com.seven.ikar.kotlin.ui.IkarMainMenuTab
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.formatDiscoverPresence
import com.seven.ikar.kotlin.ui.formatPresenceColor
import com.seven.ikar.kotlin.ui.theme.TelegramBlue
import com.seven.ikar.kotlin.ui.theme.TelegramInkMuted

@Composable
fun ContactsScreen(
    state: ContactsUiState,
    items: List<DiscoverUserItem>,
    onQueryChanged: (String) -> Unit,
    onContactClick: (DiscoverUserItem) -> Unit,
    onRefresh: () -> Unit,
    onChatsClick: () -> Unit,
    onContactsClick: () -> Unit,
    onSettingsClick: () -> Unit,
    onProfileClick: () -> Unit,
    onOpenNewMessageClick: () -> Unit
) {
    val context = LocalContext.current
    val permissionLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
        if (granted) {
            onRefresh()
        }
    }
    val hasContactsPermission =
        ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED

    LaunchedEffect(hasContactsPermission) {
        if (hasContactsPermission) {
            onRefresh()
        }
    }

    IkarScreenSurface(modifier = Modifier.fillMaxSize()) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .windowInsetsPadding(WindowInsets.safeDrawing.only(WindowInsetsSides.Vertical))
        ) {
            Column(
                modifier = Modifier.padding(start = 18.dp, top = 16.dp, end = 18.dp, bottom = 12.dp),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text("Контакты", style = MaterialTheme.typography.headlineLarge)
                    Icon(Icons.Outlined.Menu, contentDescription = null, tint = MaterialTheme.colorScheme.onSurface)
                }

                if (!hasContactsPermission) {
                    IkarSectionCard {
                        Text("Нужен доступ к контактам", style = MaterialTheme.typography.headlineMedium)
                        Text(
                            "Разрешите доступ к телефонной книге, чтобы видеть знакомых из контактов.",
                            style = MaterialTheme.typography.bodyMedium,
                            color = TelegramInkMuted
                        )
                        androidx.compose.foundation.layout.Spacer(modifier = Modifier.padding(top = 8.dp))
                        androidx.compose.material3.Button(onClick = { permissionLauncher.launch(Manifest.permission.READ_CONTACTS) }) {
                            Text("Разрешить доступ")
                        }
                    }
                }

                IkarSearchCard(
                    value = state.query,
                    onValueChange = onQueryChanged,
                    placeholder = "Поиск контактов"
                )

                IkarSectionCard(padding = androidx.compose.foundation.layout.PaddingValues(0.dp)) {
                    ContactsActionRow(
                        icon = Icons.Outlined.PersonAddAlt1,
                        title = "Пригласить друзей",
            subtitle = "Поделиться ссылкой на Икар."
                    )
                    IkarRowDivider(startIndent = 56.dp)
                    ContactsActionRow(
                        icon = Icons.Outlined.PhoneInTalk,
                        title = "Недавние звонки",
            subtitle = "История звонков внутри Икар."
                    )
                }

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

            Box(modifier = Modifier.weight(1f).fillMaxWidth()) {
                IkarSectionCard(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(horizontal = 18.dp),
                    padding = androidx.compose.foundation.layout.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 (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(items, key = { it.id }) { item ->
                                ContactsUserRow(item = item, onClick = { onContactClick(item) })
                            }
                        }
                        item { Box(modifier = Modifier.padding(bottom = 132.dp)) }
                    }
                }

                IkarFab(
                    icon = Icons.Outlined.Add,
                    contentDescription = "Новое сообщение",
                    modifier = Modifier
                        .align(Alignment.BottomEnd)
                        .padding(end = 20.dp, bottom = 126.dp),
                    onClick = onOpenNewMessageClick
                )
            }
        }

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

@Composable
private fun ContactsActionRow(
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    title: String,
    subtitle: String
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 18.dp, vertical = 16.dp),
        horizontalArrangement = Arrangement.spacedBy(14.dp)
    ) {
        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 ContactsUserRow(
    item: DiscoverUserItem,
    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
        ) {
            AvatarView(imageUrl = item.avatarUrl, title = item.displayName, size = 54.dp)
            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)
    }
}
