package ru.forbion.f7cloud.feature.contacts

import androidx.compose.foundation.background
import androidx.compose.foundation.border
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.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.foundation.text.BasicTextField
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
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.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import coil.request.ImageRequest
import ru.forbion.f7cloud.core.auth.AuthSession
import ru.forbion.f7cloud.core.designsystem.F7Colors
import ru.forbion.f7cloud.core.designsystem.F7CreateButton
import ru.forbion.f7cloud.core.designsystem.F7ModuleScreen

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ContactsScreen(
    session: AuthSession,
    modifier: Modifier = Modifier,
    createRequest: Int = 0,
    onUnauthorized: () -> Unit = {},
) {
    val context = LocalContext.current
    val vm: ContactsViewModel = viewModel(factory = ContactsViewModelFactory(context))
    val state by vm.state.collectAsState()

    LaunchedEffect(session.serverUrl, session.username, session.davUserId) {
        vm.load(session)
    }
    LaunchedEffect(createRequest) {
        if (createRequest > 0) vm.openAddSheet()
    }
    LaunchedEffect(state.unauthorized) {
        if (state.unauthorized) onUnauthorized()
    }

    F7ModuleScreen(
        modifier = modifier,
        loading = state.loading && state.contacts.isEmpty(),
        error = state.error,
        onErrorRetry = { vm.refresh(session, force = true) },
    ) {
        // Поиск + кнопка создания контакта (создание раньше вызывалось из нижней
        // панели, теперь — из шапки, панель стала навигационной)
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 8.dp),
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            ContactsSearchBar(
                serverUrl = session.serverUrl,
                query = state.searchQuery,
                onQueryChange = vm::setSearchQuery,
                modifier = Modifier.weight(1f),
            )
            F7CreateButton(onClick = vm::openAddSheet, size = 40.dp)
        }
        PullToRefreshBox(
            isRefreshing = state.syncing && state.contacts.isNotEmpty(),
            onRefresh = { vm.refresh(session, force = true) },
            modifier = Modifier
                .weight(1f)
                .fillMaxWidth(),
        ) {
            LazyColumn(modifier = Modifier.fillMaxSize()) {
                items(state.filteredContacts, key = { "${it.uid}|${it.email}" }) { contact ->
                    ContactListRow(
                        contact = contact,
                        onClick = { vm.openContact(contact) },
                    )
                    HorizontalDivider(color = F7Colors.Border.copy(alpha = 0.6f))
                }
            }
        }
    }

    state.selectedContact?.let { contact ->
        ContactDetailSheet(
            contact = contact,
            onDismiss = vm::closeContactDetail,
        )
    }

    if (state.addSheetOpen) {
        AddContactDialog(
            saving = state.savingContact,
            error = state.addError,
            onDismiss = vm::closeAddSheet,
            onSave = { name, email, phone ->
                vm.createContact(session, name, email, phone)
            },
        )
    }
}

@Composable
private fun AddContactDialog(
    saving: Boolean,
    error: String?,
    onDismiss: () -> Unit,
    onSave: (name: String, email: String, phone: String) -> Unit,
) {
    var name by remember { mutableStateOf("") }
    var email by remember { mutableStateOf("") }
    var phone by remember { mutableStateOf("") }

    Dialog(onDismissRequest = { if (!saving) onDismiss() }) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .clip(RoundedCornerShape(16.dp))
                .background(Color.White)
                .border(1.dp, F7Colors.Border, RoundedCornerShape(16.dp))
                .padding(20.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            Text(
                "Новый контакт",
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold,
            )
            AddContactField(label = "Имя", value = name, onValueChange = { name = it })
            AddContactField(label = "Email", value = email, onValueChange = { email = it })
            AddContactField(label = "Телефон", value = phone, onValueChange = { phone = it })
            if (!error.isNullOrBlank()) {
                Text(error, color = MaterialTheme.colorScheme.error, fontSize = 13.sp)
            }
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.End,
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Text(
                    "Отмена",
                    modifier = Modifier
                        .clickable(enabled = !saving, onClick = onDismiss)
                        .padding(8.dp),
                    color = F7Colors.TextSecondary,
                )
                Spacer(Modifier.size(8.dp))
                Box(
                    modifier = Modifier
                        .clip(RoundedCornerShape(100.dp))
                        .background(F7Colors.Primary)
                        .clickable(enabled = !saving) { onSave(name, email, phone) }
                        .padding(horizontal = 20.dp, vertical = 10.dp),
                    contentAlignment = Alignment.Center,
                ) {
                    if (saving) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(18.dp),
                            color = Color.White,
                            strokeWidth = 2.dp,
                        )
                    } else {
                        Text("Сохранить", color = Color.White, fontWeight = FontWeight.SemiBold)
                    }
                }
            }
        }
    }
}

@Composable
private fun AddContactField(
    label: String,
    value: String,
    onValueChange: (String) -> Unit,
) {
    Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
        Text(label, fontSize = 13.sp, color = F7Colors.TextSecondary)
        BasicTextField(
            value = value,
            onValueChange = onValueChange,
            modifier = Modifier
                .fillMaxWidth()
                .clip(RoundedCornerShape(8.dp))
                .border(1.dp, F7Colors.Border, RoundedCornerShape(8.dp))
                .padding(horizontal = 12.dp, vertical = 10.dp),
            singleLine = true,
            textStyle = TextStyle(fontSize = 15.sp, color = F7Colors.TextPrimary),
            cursorBrush = SolidColor(F7Colors.Primary),
        )
    }
}

@Composable
fun ContactListRow(
    contact: ContactItem,
    modifier: Modifier = Modifier,
    onClick: (() -> Unit)? = null,
) {
    val context = LocalContext.current
    val label = contact.displayName.ifBlank { contact.email }
    val (bg, fg) = ContactUi.avatarColors(label)
    val initials = ContactUi.contactInitials(label)
    val photoBytes = remember(contact.uid, contact.photoBase64) {
        ContactUi.decodeContactPhoto(contact.photoBase64)
    }
    Row(
        modifier = modifier
            .fillMaxWidth()
            .then(
                if (onClick != null) {
                    Modifier.clickable(onClick = onClick)
                } else {
                    Modifier
                },
            )
            .padding(horizontal = 4.dp, vertical = 10.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        Box(
            modifier = Modifier
                .size(40.dp)
                .clip(CircleShape)
                .background(bg),
            contentAlignment = Alignment.Center,
        ) {
            if (photoBytes != null) {
                AsyncImage(
                    model = ImageRequest.Builder(context)
                        .data(photoBytes)
                        .crossfade(true)
                        .build(),
                    contentDescription = null,
                    modifier = Modifier.fillMaxSize(),
                    contentScale = ContentScale.Crop,
                )
            } else {
                Text(
                    initials,
                    style = MaterialTheme.typography.labelMedium,
                    fontWeight = FontWeight.SemiBold,
                    color = fg,
                )
            }
        }
        Column(modifier = Modifier.weight(1f)) {
            // Живая тема: имя 16/500, детали 14/500 серым
            Text(
                contact.displayName.ifBlank { contact.email },
                style = MaterialTheme.typography.bodyLarge,
                fontWeight = FontWeight.Medium,
                color = F7Colors.TextPrimary,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
            )
            if (contact.email.isNotBlank() && contact.displayName.isNotBlank()) {
                Text(
                    contact.email,
                    style = MaterialTheme.typography.bodyMedium,
                    color = F7Colors.TextSecondary,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                )
            } else if (contact.phone.isNotBlank()) {
                Text(
                    contact.phone,
                    style = MaterialTheme.typography.bodyMedium,
                    color = F7Colors.TextSecondary,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                )
            }
        }
    }
}

@Composable
private fun ContactsSearchBar(
    serverUrl: String,
    query: String,
    onQueryChange: (String) -> Unit,
    modifier: Modifier = Modifier,
) {
    val base = serverUrl.trimEnd('/')
    Box(
        modifier = modifier
            .height(40.dp)
            .shadow(2.dp, RoundedCornerShape(100.dp), spotColor = Color(0xFFCBCBCB))
            .clip(RoundedCornerShape(100.dp))
            .background(Color.White)
            .border(1.dp, F7Colors.Border, RoundedCornerShape(100.dp))
            .padding(horizontal = 14.dp),
        contentAlignment = Alignment.CenterStart,
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            AsyncImage(
                model = "$base/themes/forbion/images/search/searchContacts.svg",
                contentDescription = null,
                modifier = Modifier.size(16.dp),
            )
            BasicTextField(
                value = query,
                onValueChange = onQueryChange,
                modifier = Modifier
                    .weight(1f)
                    .padding(horizontal = 8.dp),
                singleLine = true,
                textStyle = TextStyle(
                    fontSize = 14.sp,
                    fontWeight = FontWeight.Medium,
                    color = F7Colors.TextPrimary,
                ),
                cursorBrush = SolidColor(F7Colors.Primary),
                decorationBox = { inner ->
                    if (query.isEmpty()) {
                        Text(
                            "Поиск контактов",
                            style = TextStyle(
                                fontSize = 14.sp,
                                color = F7Colors.TextSecondary,
                            ),
                        )
                    }
                    inner()
                },
            )
        }
    }
}
