package id.iiyh.inatrading.feature.info.presentation

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.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.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.Chat
import androidx.compose.material.icons.outlined.AccountBalanceWallet
import androidx.compose.material.icons.outlined.ChevronRight
import androidx.compose.material.icons.outlined.Email
import androidx.compose.material.icons.outlined.LocalShipping
import androidx.compose.material.icons.outlined.Payments
import androidx.compose.material.icons.outlined.Person
import androidx.compose.material.icons.outlined.Search
import androidx.compose.material.icons.outlined.Shield
import androidx.compose.material.icons.outlined.ShoppingBag
import androidx.compose.material.icons.outlined.Store
import androidx.compose.material.icons.outlined.Warehouse
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import id.iiyh.inatrading.R
import id.iiyh.inatrading.core.ui.components.InaInnerTopAppBar
import id.iiyh.inatrading.core.ui.theme.AccentBlue
import id.iiyh.inatrading.core.ui.theme.AccentBlueContainer
import id.iiyh.inatrading.core.ui.theme.AccentPurple
import id.iiyh.inatrading.core.ui.theme.AccentPurpleContainer
import id.iiyh.inatrading.core.ui.theme.Background
import id.iiyh.inatrading.core.ui.theme.BrandRed
import id.iiyh.inatrading.core.ui.theme.BrandRedContainer
import id.iiyh.inatrading.core.ui.theme.ManropeFontFamily
import id.iiyh.inatrading.core.ui.theme.OnAccentBlueContainer
import id.iiyh.inatrading.core.ui.theme.OnSurface
import id.iiyh.inatrading.core.ui.theme.OnSurfaceVariant
import id.iiyh.inatrading.core.ui.theme.OutlineVariant
import id.iiyh.inatrading.core.ui.theme.SurfaceContainerHighest
import id.iiyh.inatrading.core.ui.theme.SurfaceContainerLow
import id.iiyh.inatrading.core.ui.theme.SurfaceContainerLowest

private data class HelpCategory(
    val icon: ImageVector,
    val title: String,
    val body: String,
    val iconContainer: Color,
    val iconTint: Color,
)

private data class HelpFaq(
    val question: String,
    val answer: String,
)

private const val HELP_CENTER_WHATSAPP_NUMBER = "6281181190222"
private const val HELP_CENTER_SUPPORT_EMAIL = "marketing@inatrading.co.id"

@Composable
fun HelpCenterScreen(
    onBack: () -> Unit,
) {
    var query by rememberSaveable { mutableStateOf("") }

    val sidebarEntries = listOf(
        Icons.Outlined.Warehouse to stringResource(R.string.help_center_sidebar_orders),
        Icons.Outlined.Payments to stringResource(R.string.help_center_sidebar_payment),
        Icons.Outlined.LocalShipping to stringResource(R.string.help_center_sidebar_shipping),
        Icons.Outlined.Person to stringResource(R.string.help_center_sidebar_account),
    )

    val categories = listOf(
        HelpCategory(
            icon = Icons.Outlined.ShoppingBag,
            title = stringResource(R.string.help_center_cat_orders_title),
            body = stringResource(R.string.help_center_cat_orders_body),
            iconContainer = BrandRedContainer.copy(alpha = 0.25f),
            iconTint = BrandRed,
        ),
        HelpCategory(
            icon = Icons.Outlined.AccountBalanceWallet,
            title = stringResource(R.string.help_center_cat_payment_title),
            body = stringResource(R.string.help_center_cat_payment_body),
            iconContainer = AccentBlueContainer.copy(alpha = 0.45f),
            iconTint = AccentBlue,
        ),
        HelpCategory(
            icon = Icons.Outlined.Shield,
            title = stringResource(R.string.help_center_cat_account_title),
            body = stringResource(R.string.help_center_cat_account_body),
            iconContainer = SurfaceContainerHighest,
            iconTint = OnSurface,
        ),
        HelpCategory(
            icon = Icons.Outlined.Store,
            title = stringResource(R.string.help_center_cat_merchant_title),
            body = stringResource(R.string.help_center_cat_merchant_body),
            iconContainer = BrandRedContainer.copy(alpha = 0.22f),
            iconTint = BrandRed,
        ),
    )

    val faqs = listOf(
        HelpFaq(
            question = stringResource(R.string.help_center_faq_track_question),
            answer = stringResource(R.string.help_center_faq_track_answer),
        ),
        HelpFaq(
            question = stringResource(R.string.help_center_faq_payment_question),
            answer = stringResource(R.string.help_center_faq_payment_answer),
        ),
        HelpFaq(
            question = stringResource(R.string.help_center_faq_refund_question),
            answer = stringResource(R.string.help_center_faq_refund_answer),
        ),
        HelpFaq(
            question = stringResource(R.string.help_center_faq_address_question),
            answer = stringResource(R.string.help_center_faq_address_answer),
        ),
    )

    val normalizedQuery = query.trim().lowercase()
    val filteredCategories = categories.filter {
        normalizedQuery.isBlank() ||
            it.title.lowercase().contains(normalizedQuery) ||
            it.body.lowercase().contains(normalizedQuery)
    }
    val filteredFaqs = faqs.filter {
        normalizedQuery.isBlank() ||
            it.question.lowercase().contains(normalizedQuery) ||
            it.answer.lowercase().contains(normalizedQuery)
    }

    Scaffold(
        topBar = { InaInnerTopAppBar(onBack = onBack) },
        containerColor = Background,
    ) { innerPadding ->
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding)
                .background(Background),
            contentPadding = PaddingValues(top = 16.dp, bottom = 32.dp),
            verticalArrangement = Arrangement.spacedBy(20.dp),
        ) {
            item {
                HeroSection(
                    query = query,
                    onQueryChange = { query = it },
                )
            }

            item {
                SupportCategoriesCard(entries = sidebarEntries)
            }

            item {
                ContactSupportCard()
            }

            item {
                Column(
                    modifier = Modifier.padding(horizontal = 16.dp),
                    verticalArrangement = Arrangement.spacedBy(12.dp),
                ) {
                    SectionHeader(
                        title = stringResource(R.string.help_center_main_categories),
                        action = stringResource(R.string.profile_view_all),
                    )
                    filteredCategories.forEach { category ->
                        HelpCategoryCard(category = category)
                    }
                }
            }

            item {
                FaqSection(faqs = filteredFaqs)
            }

            item {
                FooterCaption()
            }
        }
    }
}

@Composable
private fun HeroSection(
    query: String,
    onQueryChange: (String) -> Unit,
) {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .background(SurfaceContainerHighest.copy(alpha = 0.24f)),
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp, vertical = 24.dp),
            verticalArrangement = Arrangement.spacedBy(18.dp),
        ) {
            Text(
                text = stringResource(R.string.help_center_eyebrow).uppercase(),
                style = MaterialTheme.typography.labelSmall,
                color = BrandRed,
                fontWeight = FontWeight.Bold,
                letterSpacing = 1.6.sp,
                modifier = Modifier.align(Alignment.CenterHorizontally),
            )
            Text(
                text = stringResource(R.string.help_center_title),
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.ExtraBold,
                fontSize = 26.sp,
                lineHeight = 30.sp,
                color = OnSurface,
                textAlign = TextAlign.Center,
                modifier = Modifier.align(Alignment.CenterHorizontally),
            )
            Surface(
                color = SurfaceContainerLowest,
                shape = RoundedCornerShape(16.dp),
                shadowElevation = 6.dp,
            ) {
                OutlinedTextField(
                    value = query,
                    onValueChange = onQueryChange,
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    shape = RoundedCornerShape(16.dp),
                    placeholder = {
                        Text(
                            text = stringResource(R.string.help_center_search_placeholder),
                            color = OnSurfaceVariant.copy(alpha = 0.62f),
                        )
                    },
                    leadingIcon = {
                        Icon(
                            imageVector = Icons.Outlined.Search,
                            contentDescription = null,
                            tint = OnSurfaceVariant,
                        )
                    },
                )
            }
        }
    }
}

@Composable
private fun SupportCategoriesCard(
    entries: List<Pair<ImageVector, String>>,
) {
    Surface(
        modifier = Modifier.padding(horizontal = 16.dp),
        color = SurfaceContainerLowest,
        shape = RoundedCornerShape(18.dp),
        shadowElevation = 2.dp,
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(10.dp),
        ) {
            Text(
                text = stringResource(R.string.help_center_sidebar_title),
                fontWeight = FontWeight.Medium,
                color = OnSurface,
            )
            entries.forEachIndexed { index, (icon, label) ->
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(
                            if (index == 0) SurfaceContainerLow else Color.Transparent,
                            RoundedCornerShape(12.dp),
                        )
                        .padding(horizontal = 12.dp, vertical = 12.dp),
                    horizontalArrangement = Arrangement.spacedBy(10.dp),
                    verticalAlignment = Alignment.CenterVertically,
                ) {
                    Icon(
                        imageVector = icon,
                        contentDescription = null,
                        tint = if (index == 0) BrandRed else OnSurfaceVariant,
                        modifier = Modifier.size(18.dp),
                    )
                    Text(
                        text = label,
                        color = if (index == 0) BrandRed else OnSurface,
                        fontWeight = if (index == 0) FontWeight.SemiBold else FontWeight.Normal,
                    )
                }
            }
        }
    }
}

@Composable
private fun ContactSupportCard() {
    val context = LocalContext.current
    Surface(
        modifier = Modifier.padding(horizontal = 16.dp),
        color = AccentPurple,
        shape = RoundedCornerShape(18.dp),
        shadowElevation = 8.dp,
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
        ) {
            Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                Text(
                    text = stringResource(R.string.help_center_contact_title),
                    fontFamily = ManropeFontFamily,
                    fontWeight = FontWeight.ExtraBold,
                    fontSize = 24.sp,
                    color = Color.White,
                )
                Text(
                    text = stringResource(R.string.help_center_contact_body),
                    color = Color.White.copy(alpha = 0.92f),
                    style = MaterialTheme.typography.bodySmall,
                )
                SupportButton(
                    icon = Icons.AutoMirrored.Outlined.Chat,
                    text = stringResource(R.string.help_center_contact_whatsapp),
                    containerColor = Color.White,
                    contentColor = AccentPurple,
                    onClick = {
                        val intent = Intent(
                            Intent.ACTION_VIEW,
                            Uri.parse("https://wa.me/$HELP_CENTER_WHATSAPP_NUMBER")
                        )
                        context.startActivity(intent)
                    },
                )
                SupportButton(
                    icon = Icons.Outlined.Email,
                    text = stringResource(R.string.help_center_contact_email),
                    containerColor = Color.White.copy(alpha = 0.12f),
                    contentColor = Color.White,
                    onClick = {
                        val intent = Intent(Intent.ACTION_SENDTO).apply {
                            data = Uri.parse("mailto:$HELP_CENTER_SUPPORT_EMAIL")
                        }
                        context.startActivity(intent)
                    },
                )
            }

            Icon(
                imageVector = Icons.Outlined.ChevronRight,
                contentDescription = null,
                tint = Color.White.copy(alpha = 0.08f),
                modifier = Modifier
                    .align(Alignment.BottomEnd)
                    .size(68.dp),
            )
        }
    }
}

@Composable
private fun SupportButton(
    icon: ImageVector,
    text: String,
    containerColor: Color,
    contentColor: Color,
    onClick: () -> Unit,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .background(containerColor, RoundedCornerShape(12.dp))
            .padding(horizontal = 14.dp, vertical = 12.dp),
        horizontalArrangement = Arrangement.Center,
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null,
            tint = contentColor,
            modifier = Modifier.size(16.dp),
        )
        Spacer(modifier = Modifier.size(8.dp))
        Text(
            text = text,
            color = contentColor,
            fontWeight = FontWeight.SemiBold,
        )
    }
}

@Composable
private fun SectionHeader(
    title: String,
    action: String,
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Text(
            text = title,
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.ExtraBold,
            fontSize = 20.sp,
            color = OnSurface,
        )
        Text(
            text = action,
            color = BrandRed,
            style = MaterialTheme.typography.labelSmall,
            fontWeight = FontWeight.Bold,
        )
    }
}

@Composable
private fun HelpCategoryCard(
    category: HelpCategory,
) {
    Surface(
        color = SurfaceContainerLowest,
        shape = RoundedCornerShape(16.dp),
        shadowElevation = 1.dp,
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalArrangement = Arrangement.spacedBy(14.dp),
            verticalAlignment = Alignment.Top,
        ) {
            Box(
                modifier = Modifier
                    .size(42.dp)
                    .background(category.iconContainer, RoundedCornerShape(12.dp)),
                contentAlignment = Alignment.Center,
            ) {
                Icon(
                    imageVector = category.icon,
                    contentDescription = null,
                    tint = category.iconTint,
                    modifier = Modifier.size(20.dp),
                )
            }
            Column(
                modifier = Modifier.weight(1f),
                verticalArrangement = Arrangement.spacedBy(4.dp),
            ) {
                Text(
                    text = category.title,
                    fontFamily = ManropeFontFamily,
                    fontWeight = FontWeight.Bold,
                    fontSize = 18.sp,
                    lineHeight = 22.sp,
                    color = OnSurface,
                )
                Text(
                    text = category.body,
                    color = OnSurfaceVariant,
                    style = MaterialTheme.typography.bodySmall,
                )
            }
        }
    }
}

@Composable
private fun FaqSection(
    faqs: List<HelpFaq>,
) {
    Surface(
        modifier = Modifier.padding(horizontal = 16.dp),
        color = SurfaceContainerLow,
        shape = RoundedCornerShape(20.dp),
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            Text(
                text = stringResource(R.string.help_center_faq_title),
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.ExtraBold,
                fontSize = 20.sp,
                lineHeight = 26.sp,
                color = OnSurface,
            )
            faqs.forEachIndexed { index, faq ->
                FaqCard(
                    faq = faq,
                    expandedByDefault = index == 0,
                )
            }
            CalloutCard()
        }
    }
}

@Composable
private fun FaqCard(
    faq: HelpFaq,
    expandedByDefault: Boolean = false,
) {
    var expanded by remember { mutableStateOf(expandedByDefault) }

    Surface(
        color = SurfaceContainerLowest,
        shape = RoundedCornerShape(14.dp),
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .clickable { expanded = !expanded }
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(10.dp),
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Text(
                    text = faq.question,
                    fontWeight = FontWeight.Medium,
                    fontSize = 16.sp,
                    lineHeight = 22.sp,
                    color = OnSurface,
                    modifier = Modifier.weight(1f),
                )
                Spacer(modifier = Modifier.size(12.dp))
                Icon(
                    imageVector = Icons.Outlined.ChevronRight,
                    contentDescription = null,
                    tint = BrandRed,
                    modifier = Modifier.size(18.dp),
                )
            }
            if (expanded) {
                Text(
                    text = faq.answer,
                    color = OnSurfaceVariant,
                    style = MaterialTheme.typography.bodySmall,
                )
            }
        }
    }
}

@Composable
private fun CalloutCard() {
    Surface(
        color = SurfaceContainerLowest,
        shape = RoundedCornerShape(16.dp),
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp, vertical = 22.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            Box(
                modifier = Modifier
                    .size(46.dp)
                    .background(AccentBlueContainer.copy(alpha = 0.5f), CircleShape),
                contentAlignment = Alignment.Center,
            ) {
                Icon(
                    imageVector = Icons.Outlined.Person,
                    contentDescription = null,
                    tint = OnAccentBlueContainer,
                    modifier = Modifier.size(18.dp),
                )
            }
            Text(
                text = stringResource(R.string.help_center_callout_title),
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.Bold,
                fontSize = 22.sp,
                lineHeight = 26.sp,
                textAlign = TextAlign.Center,
                color = OnSurface,
            )
            Text(
                text = stringResource(R.string.help_center_callout_body),
                color = OnSurfaceVariant,
                style = MaterialTheme.typography.bodySmall,
                textAlign = TextAlign.Center,
            )
            Box(
                modifier = Modifier
                    .background(BrandRed, RoundedCornerShape(12.dp))
                    .padding(horizontal = 20.dp, vertical = 12.dp),
                contentAlignment = Alignment.Center,
            ) {
                Text(
                    text = stringResource(R.string.help_center_callout_action),
                    color = Color.White,
                    fontWeight = FontWeight.Bold,
                    textAlign = TextAlign.Center,
                )
            }
        }
    }
}

@Composable
private fun FooterCaption() {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .background(SurfaceContainerHighest.copy(alpha = 0.28f))
            .padding(horizontal = 16.dp, vertical = 28.dp),
        contentAlignment = Alignment.Center,
    ) {
        Text(
            text = stringResource(R.string.help_center_footer),
            color = OnSurfaceVariant,
            style = MaterialTheme.typography.bodySmall,
            textAlign = TextAlign.Center,
        )
    }
}
