package ru.forbion.f7cloud.feature.contacts

import android.content.Intent
import android.net.Uri
import androidx.compose.foundation.background
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.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import ru.forbion.f7cloud.core.designsystem.F7Colors
import ru.forbion.f7cloud.core.designsystem.F7SecondaryButton

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ContactDetailSheet(
    contact: ContactItem,
    onDismiss: () -> Unit,
) {
    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    ModalBottomSheet(
        onDismissRequest = onDismiss,
        sheetState = sheetState,
        containerColor = F7Colors.Surface,
    ) {
        ContactDetailContent(
            contact = contact,
            onDismiss = onDismiss,
        )
    }
}

@Composable
private fun ContactDetailContent(
    contact: ContactItem,
    onDismiss: () -> Unit,
) {
    val context = LocalContext.current
    val label = contact.displayName.ifBlank { contact.email }
    val photoBytes = remember(contact.uid, contact.photoBase64) {
        ContactUi.decodeContactPhoto(contact.photoBase64)
    }
    val (avatarBg, avatarFg) = ContactUi.avatarColors(label)
    val initials = ContactUi.contactInitials(label)
    val primaryEmail = contact.emailLines.firstOrNull()
    val primaryPhone = contact.phoneLines.firstOrNull()

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .verticalScroll(rememberScrollState())
            .padding(horizontal = 20.dp)
            .padding(bottom = 28.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(16.dp),
    ) {
        Box(
            modifier = Modifier
                .size(88.dp)
                .clip(CircleShape)
                .background(avatarBg),
            contentAlignment = Alignment.Center,
        ) {
            if (photoBytes != null) {
                AsyncImage(
                    model = ImageRequest.Builder(context)
                        .data(photoBytes)
                        .crossfade(true)
                        .build(),
                    contentDescription = null,
                    modifier = Modifier.fillMaxWidth(),
                    contentScale = ContentScale.Crop,
                )
            } else {
                Text(
                    initials,
                    style = MaterialTheme.typography.headlineSmall,
                    fontWeight = FontWeight.SemiBold,
                    color = avatarFg,
                )
            }
        }

        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(4.dp),
        ) {
            Text(
                contact.displayName.ifBlank { contact.email },
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.Bold,
            )
            contact.subtitle?.let { subtitle ->
                Text(
                    subtitle,
                    style = MaterialTheme.typography.bodyMedium,
                    color = F7Colors.TextSecondary,
                )
            }
        }

        if (primaryEmail != null || primaryPhone != null) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(10.dp),
            ) {
                if (primaryEmail != null) {
                    F7SecondaryButton(
                        text = "Email",
                        onClick = {
                            context.startActivity(
                                Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:$primaryEmail")),
                            )
                        },
                        modifier = Modifier.weight(1f),
                    )
                }
                if (primaryPhone != null) {
                    F7SecondaryButton(
                        text = "Позвонить",
                        onClick = {
                            context.startActivity(
                                Intent(Intent.ACTION_DIAL, Uri.parse("tel:$primaryPhone")),
                            )
                        },
                        modifier = Modifier.weight(1f),
                    )
                }
            }
        }

        Column(
            modifier = Modifier
                .fillMaxWidth()
                .clip(RoundedCornerShape(14.dp))
                .background(F7Colors.Background)
                .padding(horizontal = 16.dp, vertical = 4.dp),
            verticalArrangement = Arrangement.spacedBy(0.dp),
        ) {
            if (contact.emailLines.isNotEmpty()) {
                contact.emailLines.forEachIndexed { index, email ->
                    ContactDetailField(
                        label = if (index == 0) "Email" else "Email ${index + 1}",
                        value = email,
                        onClick = {
                            context.startActivity(
                                Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:$email")),
                            )
                        },
                    )
                }
            }
            if (contact.phoneLines.isNotEmpty()) {
                contact.phoneLines.forEachIndexed { index, phone ->
                    ContactDetailField(
                        label = if (index == 0) "Телефон" else "Телефон ${index + 1}",
                        value = phone,
                        onClick = {
                            context.startActivity(
                                Intent(Intent.ACTION_DIAL, Uri.parse("tel:$phone")),
                            )
                        },
                    )
                }
            }
            if (contact.address.isNotBlank()) {
                ContactDetailField(label = "Адрес", value = contact.address)
            }
            if (contact.website.isNotBlank()) {
                ContactDetailField(
                    label = "Сайт",
                    value = contact.website,
                    onClick = {
                        val url = contact.website.let {
                            if (it.startsWith("http://") || it.startsWith("https://")) it
                            else "https://$it"
                        }
                        context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
                    },
                )
            }
            if (contact.birthday.isNotBlank()) {
                ContactDetailField(label = "День рождения", value = contact.birthday)
            }
            if (contact.bookName.isNotBlank()) {
                ContactDetailField(label = "Адресная книга", value = contact.bookName)
            }
        }

        Spacer(Modifier.height(4.dp))
        Text(
            "Закрыть",
            modifier = Modifier
                .clickable(onClick = onDismiss)
                .padding(8.dp),
            color = F7Colors.Primary,
            fontWeight = FontWeight.SemiBold,
        )
    }
}

@Composable
private fun ContactDetailField(
    label: String,
    value: String,
    onClick: (() -> Unit)? = null,
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .then(
                if (onClick != null) {
                    Modifier.clickable(onClick = onClick)
                } else {
                    Modifier
                },
            )
            .padding(vertical = 12.dp),
    ) {
        Text(
            label,
            style = MaterialTheme.typography.labelMedium,
            color = F7Colors.TextSecondary,
        )
        Spacer(Modifier.height(4.dp))
        Text(
            value,
            style = MaterialTheme.typography.bodyLarge,
            color = if (onClick != null) F7Colors.Primary else F7Colors.TextPrimary,
        )
    }
    HorizontalDivider(color = F7Colors.Border.copy(alpha = 0.5f))
}

internal object ContactUi {
    private val AvatarPalette = listOf(
        androidx.compose.ui.graphics.Color(0xFFE8F5E0) to androidx.compose.ui.graphics.Color(0xFF4A7C2E),
        androidx.compose.ui.graphics.Color(0xFFFCE4EC) to androidx.compose.ui.graphics.Color(0xFFC2185B),
        androidx.compose.ui.graphics.Color(0xFFE3F2FD) to androidx.compose.ui.graphics.Color(0xFF1565C0),
        androidx.compose.ui.graphics.Color(0xFFFFF3E0) to androidx.compose.ui.graphics.Color(0xFFE65100),
        androidx.compose.ui.graphics.Color(0xFFEDE7F6) to androidx.compose.ui.graphics.Color(0xFF6B4F9B),
    )

    fun contactInitials(name: String): String {
        val parts = name.trim().split(Regex("\\s+")).filter { it.isNotBlank() }
        return when {
            parts.size >= 2 -> "${parts[0].first()}${parts[1].first()}".uppercase()
            parts.size == 1 -> parts[0].take(2).uppercase()
            else -> "?"
        }
    }

    fun avatarColors(seed: String): Pair<androidx.compose.ui.graphics.Color, androidx.compose.ui.graphics.Color> {
        val idx = kotlin.math.abs(seed.hashCode()) % AvatarPalette.size
        return AvatarPalette[idx]
    }

    fun decodeContactPhoto(base64: String): ByteArray? {
        if (base64.isBlank()) return null
        return runCatching {
            android.util.Base64.decode(base64, android.util.Base64.DEFAULT)
        }.getOrNull()?.takeIf { it.isNotEmpty() }
    }
}
