package com.approagency.pharmacy.presentation.components


import android.annotation.SuppressLint
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import com.approagency.pharmacy.presentation.common.CustomModalBottomSheet
import com.approagency.pharmacy.presentation.common.Loading
import com.approagency.pharmacy.presentation.viewModel.PharmacyState
import com.approagency.pharmacy.presentation.viewModel.PharmacyViewModel
import com.approagency.pharmacy.utils.provinces
import com.vada.caller.ui.theme.dime

@SuppressLint("ConfigurationScreenWidthHeight")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PharmacyBottomSheet(
    viewModel: PharmacyViewModel,
    genericDrugId: String,
    brandIrc: String,
    isOpen: Boolean,
    onDismiss: () -> Unit
) {
    val scope = rememberCoroutineScope()
    val sheetState = rememberModalBottomSheetState(
        skipPartiallyExpanded = true, confirmValueChange = { true }
    )

    var selectedProvinceId by remember { mutableStateOf("40") } // پیش‌فرض تهران
    var showProvinceDropdown by remember { mutableStateOf(false) }

    val pharmacyState by viewModel.state.collectAsState()

    // شیت بلند ثابت می‌شود تا لیست داخلی به‌درستی اسکرول شود (نه اینکه درگِ شیت
    // جای اسکرولِ لیست را بگیرد) و حالت‌های لودینگ/خالی/خطا وسط دیده شوند.
    val sheetHeight = (LocalConfiguration.current.screenHeightDp * 0.85f).dp

    LaunchedEffect(genericDrugId, brandIrc) {
        viewModel.search(genericDrugId, brandIrc, "40")
    }

    if (isOpen) {
        CustomModalBottomSheet(sheetState = sheetState, onDismiss = onDismiss, scope = scope) {
            CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(sheetHeight)
                        .padding(MaterialTheme.dime.lg)
                ) {
                    // سربرگ ثابت
                    Text(
                        text = "موجودی دارو در داروخانه‌ها",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold
                    )

                    Spacer(Modifier.height(MaterialTheme.dime.md))

                    ProvinceSelector(
                        selectedProvinceId = selectedProvinceId,
                        expanded = showProvinceDropdown,
                        onExpandedChange = { showProvinceDropdown = it },
                        onProvinceSelected = { id ->
                            selectedProvinceId = id
                            showProvinceDropdown = false
                            viewModel.search(genericDrugId, brandIrc, id)
                        }
                    )

                    Spacer(Modifier.height(MaterialTheme.dime.md))

                    // ناحیه‌ی محتوا فضای باقی‌مانده را پر می‌کند؛ سربرگ بالا ثابت می‌ماند.
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .weight(1f),
                        contentAlignment = Alignment.Center
                    ) {
                        when (val state = pharmacyState) {
                            PharmacyState.Loading -> Loading(
                                modifier = Modifier.fillMaxSize(),
                                message = "در حال جستجو..."
                            )

                            is PharmacyState.Success -> {
                                if (state.items.isEmpty()) {
                                    EmptyMessage("هیچ داروخانه‌ای یافت نشد")
                                } else {
                                    LazyColumn(
                                        modifier = Modifier.fillMaxSize(),
                                        verticalArrangement = Arrangement.spacedBy(MaterialTheme.dime.sm)
                                    ) {
                                        items(state.items) { pharmacy ->
                                            PharmacyResultItem(pharmacy = pharmacy, viewModel)
                                        }
                                        item {
                                            Text(
                                                text = "تعداد کل: ${state.items.size} داروخانه",
                                                style = MaterialTheme.typography.bodySmall,
                                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                                                modifier = Modifier.padding(vertical = MaterialTheme.dime.sm)
                                            )
                                        }
                                    }
                                }
                            }

                            is PharmacyState.Error -> Column(
                                horizontalAlignment = Alignment.CenterHorizontally
                            ) {
                                Text(
                                    text = state.message,
                                    color = MaterialTheme.colorScheme.error,
                                    style = MaterialTheme.typography.bodyMedium
                                )
                                Spacer(Modifier.height(MaterialTheme.dime.sm))
                                TextButton(onClick = { viewModel.retry() }) { Text("تلاش مجدد") }
                            }

                            PharmacyState.Idle -> {}
                        }
                    }
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun ProvinceSelector(
    selectedProvinceId: String,
    expanded: Boolean,
    onExpandedChange: (Boolean) -> Unit,
    onProvinceSelected: (String) -> Unit
) {
    ExposedDropdownMenuBox(
        expanded = expanded,
        onExpandedChange = onExpandedChange
    ) {
        OutlinedTextField(
            value = provinces.find { it.id == selectedProvinceId }?.name ?: "انتخاب استان",
            onValueChange = {},
            readOnly = true,
            label = { Text("استان") },
            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
            modifier = Modifier
                .fillMaxWidth()
                .menuAnchor(),
            shape = MaterialTheme.shapes.large
        )
        ExposedDropdownMenu(
            expanded = expanded,
            onDismissRequest = { onExpandedChange(false) }
        ) {
            provinces.forEach { province ->
                DropdownMenuItem(
                    text = { Text(province.name) },
                    onClick = { onProvinceSelected(province.id) }
                )
            }
        }
    }
}

@Composable
private fun EmptyMessage(message: String) {
    Text(
        text = message,
        style = MaterialTheme.typography.bodyMedium,
        color = MaterialTheme.colorScheme.onSurfaceVariant
    )
}
