package com.syaroful.agrilinkvocpro.presentation.screen.home

import androidx.compose.foundation.Image
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.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Person
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.runtime.Composable
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.graphics.painter.Painter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.syaroful.agrilinkvocpro.R
import com.syaroful.agrilinkvocpro.core.components.DefaultErrorComponent
import com.syaroful.agrilinkvocpro.core.components.DownloadProgressDialog
import com.syaroful.agrilinkvocpro.core.components.MenuItemButton
import com.syaroful.agrilinkvocpro.core.components.textTheme
import com.syaroful.agrilinkvocpro.core.placeholder.shimmerEffect
import com.syaroful.agrilinkvocpro.core.utils.ResultState
import com.syaroful.agrilinkvocpro.presentation.theme.AgrilinkVocproTheme
import com.syaroful.agrilinkvocpro.presentation.theme.LightGrey
import com.syaroful.agrilinkvocpro.presentation.theme.MainGreen
import org.koin.androidx.compose.koinViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeScreen(
    navController: NavController,
    onFeatureClick: (String) -> Unit,
    dynamicModuleViewModel: DynamicModuleViewModel,
    homeViewModel: HomeViewModel = koinViewModel()
) {
//     State untuk menampilkan dialog log/progress
    val showProgressDialog by dynamicModuleViewModel.showProgressDialog.collectAsState()
    val progressMessage by dynamicModuleViewModel.progressMessage.collectAsState()
    val progressPercent by dynamicModuleViewModel.progressPercent.collectAsState()

    val homeState by homeViewModel.homeState.collectAsState()
    val isRefreshing = remember { mutableStateOf(false) }

    val sensors = listOf("NPK", "DHT")
    var selectedSensor by remember { mutableStateOf("NPK") }

    AgrilinkVocproTheme {
        Scaffold { padding ->
            PullToRefreshBox(
                isRefreshing = isRefreshing.value,
                onRefresh = {
                    isRefreshing.value = true
                    homeViewModel.printUserToken()
                    homeViewModel.getGreenHouseData()
                },
            ) {
                Column(
                    modifier = Modifier
                        .padding(padding)
                        .fillMaxWidth()
                        .verticalScroll(rememberScrollState())
                ) {
                    GreenHouseInformationSection(navController = navController)
                    Spacer(modifier = Modifier.height(20.dp))
                    DynamicFeatureSection(
                        onFeatureClick = onFeatureClick
                    )
                    Spacer(modifier = Modifier.height(32.dp))
                    SensorTabBar(
                        sensors = sensors,
                        selectedSensor = selectedSensor,
                        onSensorSelected = { selectedSensor = it }
                    )
                    when (homeState) {
                        is ResultState.Loading -> {
                            Box(
                                modifier = Modifier
                                    .padding(16.dp)
                                    .fillMaxWidth()
                                    .height(100.dp)
                                    .shimmerEffect()
                            )
                            Box(
                                modifier = Modifier
                                    .padding(16.dp)
                                    .fillMaxWidth()
                                    .height(100.dp)
                                    .shimmerEffect()
                            )
                        }

                        is ResultState.Success -> {
                            isRefreshing.value = false
                            val data = (homeState as ResultState.Success).data
                            data?.data?.let { sensorData ->
                                when (selectedSensor) {
                                    "NPK" -> {
                                        BetDataComponent(
                                            onClick = {
                                                navController.navigate("detail-screen/npk1")
                                            },
                                            betNUmber = 1,
                                            commodity = "Kabocha",
                                            nitrogenValue = sensorData.npk1?.soilNitrogen.toString(),
                                            phosphorValue = sensorData.npk1?.soilPhosphorus.toString(),
                                            potassiumValue = sensorData.npk1?.soilPotassium.toString(),
                                            commodityImage = painterResource(id = R.drawable.kabocha)
                                        )
                                        BetDataComponent(
                                            onClick = {
                                                navController.navigate("detail-screen/npk2")
                                            },
                                            betNUmber = 2,
                                            commodity = "Melon",
                                            nitrogenValue = sensorData.npk2?.soilNitrogen.toString(),
                                            phosphorValue = sensorData.npk2?.soilPhosphorus.toString(),
                                            potassiumValue = sensorData.npk2?.soilPotassium.toString(),
                                            commodityImage = painterResource(id = R.drawable.melon)
                                        )
                                    }

                                    "DHT" -> {
                                        DhtDataComponent(
                                            onClick = {
                                                navController.navigate("detail-screen/dht")
                                            },
                                            temperatureValue = sensorData.dht?.viciTemperature.toString(),
                                            humidityValue = sensorData.dht?.viciHumidity.toString(),
                                            luminosityValue = sensorData.dht?.viciLuminosity.toString(),
                                        )
                                    }

                                }
                            }
                        }

                        is ResultState.Error -> {
                            isRefreshing.value = false
                            DefaultErrorComponent(
                                modifier = Modifier.padding(vertical = 20.dp),
                                label = "Oops!",
                                message = (homeState as ResultState.Error).message
                            )
                        }

                        else -> {}
                    }
                }
            }

            DownloadProgressDialog(
                showDialog = showProgressDialog,
                message = progressMessage,
                progress = progressPercent,
                onDismiss = { dynamicModuleViewModel.setDialogVisibility(false) }
            )
        }
    }

}


@Composable
private fun BetDataComponent(
    modifier: Modifier = Modifier,
    onClick: () -> Unit,
    betNUmber: Int,
    commodity: String,
    nitrogenValue: String,
    phosphorValue: String,
    potassiumValue: String,
    commodityImage: Painter
) {
    Column(
        modifier
            .padding(horizontal = 20.dp, vertical = 8.dp)
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.Absolute.SpaceBetween
        ) {
            Text("Bet $betNUmber")
            Text(commodity, color = MainGreen)
        }
        Spacer(modifier = Modifier.height(4.dp))
        Row(
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier
                .clip(shape = RoundedCornerShape(16.dp))
                .fillMaxWidth()
                .background(
                    color = MaterialTheme.colorScheme.surfaceContainer,
                )
                .border(
                    width = 1.dp,
                    color = MainGreen.copy(alpha = 0.4f),
                    shape = RoundedCornerShape(16.dp)
                )
                .clickable { onClick() }
                .padding(horizontal = 16.dp, vertical = 8.dp)
        )
        {
            SensorDataItem(
                icon = "N",
                label = "Nitrogen",
                value = nitrogenValue
            )
            SensorDataItem(
                icon = "P",
                label = "Phosphor",
                value = phosphorValue
            )
            SensorDataItem(
                icon = "K",
                label = "Potassium",
                value = potassiumValue
            )
            Image(
                modifier = Modifier
                    .height(60.dp)
                    .width(60.dp),
                painter = commodityImage,
                contentDescription = "Commodity"
            )
        }
    }
}

@Composable
private fun DhtDataComponent(
    onClick: () -> Unit,
    temperatureValue: String,
    humidityValue: String,
    luminosityValue: String,
) {
    Row(
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier
            .padding(horizontal = 20.dp, vertical = 8.dp)
            .clip(shape = RoundedCornerShape(16.dp))
            .fillMaxWidth()
            .background(
                color = MaterialTheme.colorScheme.surfaceContainer,
            )
            .border(
                width = 1.dp,
                color = MainGreen.copy(alpha = 0.4f),
                shape = RoundedCornerShape(16.dp)
            )
            .clickable { onClick() }
            .padding(horizontal = 16.dp, vertical = 8.dp)
    )
    {
        SensorDataItem(
            icon = "Temp",
            label = "Suhu\nGreen House",
            value = temperatureValue
        )
        SensorDataItem(
            icon = "Hum",
            label = "Kelembaban\nUdara",
            value = humidityValue
        )
        SensorDataItem(
            icon = "Lux",
            label = "Intensitas\ncahaya",
            value = luminosityValue
        )
    }
}

@Composable
private fun SensorDataItem(
    icon: String = "-",
    label: String,
    value: String = "0"
) {
    Column(horizontalAlignment = Alignment.CenterHorizontally) {
        Text(text = icon, color = MainGreen, style = textTheme.headlineMedium)
        Text(text = label, color = LightGrey, style = textTheme.bodySmall, textAlign = TextAlign.Center)
        Spacer(modifier = Modifier.height(8.dp))
        Text(text = value, style = textTheme.headlineSmall)
    }
}

@Composable
fun DynamicFeatureSection(
    onFeatureClick: (String) -> Unit
) {
    Row(
        modifier = Modifier
            .padding(horizontal = 20.dp)
            .fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        MenuItemButton(
            label = "Kontrol\nAktuator",
            icon = painterResource(id = R.drawable.control_actuator_icon),
            onClick = { onFeatureClick("control_feature") },
        )
        MenuItemButton(
            label = "Resep\nPertumbuhan",
            icon = painterResource(id = R.drawable.growth_recipe_icon),
            onClick = { onFeatureClick("growth_recipe_feature") },
        )
        MenuItemButton(
            label = "Harga\nKomoditas",
            icon = painterResource(id = R.drawable.commodity_price_prediction_icon),
            onClick = { onFeatureClick("commodity_price_prediction_feature") },
        )
        MenuItemButton(
            label = "Deteksi\nPenyakit",
            icon = painterResource(id = R.drawable.plant_disease_detection_icon),
            onClick = { onFeatureClick("plant_disease_detection_feature") },
        )
    }
}

@Composable
fun GreenHouseInformationSection(navController: NavController) {
    Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) {
        IconButton(
            onClick = {
                navController.navigate("profile") {
                    popUpTo("profile") {
                        inclusive = true
                    }
                }
            },
            modifier = Modifier.align(Alignment.CenterVertically)
        ) {
            Icon(
                imageVector = Icons.Default.Person,
                contentDescription = "profile",
                tint = MainGreen
            )
        }
    }

    Row(
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier
            .padding(20.dp)
            .fillMaxWidth()
    ) {
        Column(
            modifier = Modifier.weight(1f)

        ) {
            Text(text = "2 Komoditas", color = MainGreen, style = textTheme.bodyMedium)
            Spacer(modifier = Modifier.height(24.dp))
            Text(text = "Green House Bumiaji", style = textTheme.bodyLarge)
            Text(
                text = "Jl. Kopral Kasdi 2, Bulukerto, Kec. Bumiaji, Kota Batu, Jawa Timur 65334 ",
                style = textTheme.bodyMedium,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
        Spacer(modifier = Modifier.width(24.dp))
        Image(
            painter = painterResource(id = R.drawable.green_house_image),
            contentDescription = "profile",
            modifier = Modifier
                .size(90.dp)
                .clip(RoundedCornerShape(10.dp))
        )
    }
}

//@Preview(showBackground = true, name = "Light Mode")
//@Preview(showBackground = true, name = "Dark Mode", uiMode = UI_MODE_NIGHT_YES)
//@Composable
//fun HomePreview() {
//    val navController = rememberNavController()
//    HomeScreen(
//        navController = navController,
//        onFeatureClick = {},
//    )
//}