package com.syaroful.agrilinkvocpro.presentation.screen.detail

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
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.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
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.ui.Alignment
import androidx.compose.ui.Alignment.Companion.CenterHorizontally
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.syaroful.agrilinkvocpro.R
import com.syaroful.agrilinkvocpro.core.components.DefaultErrorComponent
import com.syaroful.agrilinkvocpro.core.placeholder.shimmerEffect
import com.syaroful.agrilinkvocpro.core.utils.ResultState
import org.koin.androidx.compose.koinViewModel
import java.text.SimpleDateFormat
import java.util.Date


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DetailScreen(
    sensorId: String,
    modifier: Modifier = Modifier,
    detailViewModel: DetailViewModel = koinViewModel(),
) {
    LaunchedEffect(sensorId) {
        detailViewModel.fetchNpkData(sensorId)
    }
    val currentData = detailViewModel.currentSensorData
    val sdf = SimpleDateFormat("dd MMMM yyyy", java.util.Locale.getDefault())
    val currentDate = sdf.format(Date())
    val options = listOf(
        "Nitrogen",
        "Pospor",
        "Kalium",
        "Suhu Tanah",
        "PH Tanah",
        "Kelembapan",
        "Konduktivitas"
    )
    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        Text(
                            "Detail Grafik",
                            style = MaterialTheme.typography.titleMedium
                        )
                    }
                },
            )
        },
    ) { innerPadding ->
        val npkDataState by detailViewModel.npkDataState.collectAsState()
        val isRefreshing = remember { mutableStateOf(false) }
        PullToRefreshBox(
            isRefreshing = isRefreshing.value,
            onRefresh = {
                isRefreshing.value = true
                detailViewModel.fetchNpkData(sensorId)
            },
        ) {
            Column(
                modifier = Modifier
                    .padding(innerPadding)
                    .padding(top = 16.dp)
                    .padding(horizontal = 16.dp)
                    .verticalScroll(rememberScrollState())
            ) {

                when (npkDataState) {
                    is ResultState.Loading -> {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(200.dp)

                                .shimmerEffect()
                        )
                    }

                    is ResultState.Error -> {
                        isRefreshing.value = false
                        DefaultErrorComponent(
                            modifier = Modifier.padding(vertical = 20.dp),
                            label = "Oops!",
                            message = (npkDataState as ResultState.Error).message,
                            painter = painterResource(id = R.drawable.mascot_confused)
                        )
                    }

                    ResultState.Idle -> {

                    }

                    is ResultState.Success -> {
                        isRefreshing.value = false
                        val selectedSensor = remember { mutableStateOf(options[0]) }
                        val result = (npkDataState as ResultState.Success).data
                        val npkData = result?.data?.get(sensorId)
                        val hours = npkData?.filter { it.hour != null }?.map { it.hour!!.toInt() }
                            ?: emptyList()
                        val values = when (selectedSensor.value) {
                            "Nitrogen" -> npkData?.mapNotNull { it.soilnitrogen?.toDouble() } ?: emptyList()
                            "Pospor" -> npkData?.mapNotNull { it.soilphosphorus?.toDouble() } ?: emptyList()
                            "Kalium" -> npkData?.mapNotNull { it.soilpotassium?.toDouble() } ?: emptyList()
                            "Suhu Tanah" -> npkData?.mapNotNull { it.soiltemperature?.toDouble() } ?: emptyList()
                            "PH Tanah" -> npkData?.mapNotNull { it.soilph?.toDouble() } ?: emptyList()
                            "Kelembapan" -> npkData?.mapNotNull { it.soilhumidity?.toDouble() } ?: emptyList()
                            "Konduktivitas" -> npkData?.mapNotNull { it.soilconductivity?.toDouble() } ?: emptyList()
                            else -> emptyList()
                        }

                        DynamicBottomSheet(
                            options = options
                        ) { selected ->
                            selectedSensor.value = selected
                        }
                        Spacer(modifier = Modifier.height(16.dp))
                        LineChart(
                            hours = hours,
                            values = values,
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(180.dp)
                                .align(CenterHorizontally)
                        )
                    }
                }

                Text(
                    "Grafik ini adalah grafik per hari ini tanggal $currentDate",
                    style = MaterialTheme.typography.bodySmall,
                    textAlign = TextAlign.Center,
                    fontStyle = FontStyle.Italic,
                    modifier = Modifier
                        .fillMaxWidth()
                        .alpha(0.5f)
                        .padding(vertical = 8.dp)
                )
                if (currentData != null) {
                    val dataSensor = when (sensorId) {
                        "npk1" -> currentData.data?.npk1
                        "npk2" -> currentData.data?.npk2
                        else -> null
                    }
                    Column(
                        verticalArrangement = Arrangement.spacedBy(
                            8.dp,
                            Alignment.Top
                        )
                    ) {
                        DataSensorBar(
                            label = "Nitrogen",
                            value = dataSensor?.soilnitrogen ?: 0,
                            painter = painterResource(id = R.drawable.npk), // Assuming the max value is 255
                            percentage = (dataSensor?.soilnitrogen?.toFloat() ?: 0f) / 50f
                        )
                        DataSensorBar(
                            label = "Pospor",
                            value = dataSensor?.soilphosphorus ?: 0,
                            painter = painterResource(id = R.drawable.npk), // Assuming the max value is 255
                            percentage = (dataSensor?.soilphosphorus?.toFloat() ?: 0f) / 255f
                        )
                        DataSensorBar(
                            label = "Kalium",
                            value = dataSensor?.soilpotassium ?: 0,
                            painter = painterResource(id = R.drawable.npk), // Assuming the max value is 255
                            percentage = (dataSensor?.soilpotassium?.toFloat() ?: 0f) / 255f
                        )
                        DataSensorBar(
                            label = "Kelembaban",
                            value = dataSensor?.soilhumidity ?: 0,
                            painter = painterResource(id = R.drawable.soil_humidity), // Assuming the max value is 100
                            percentage = (dataSensor?.soilhumidity?.toFloat() ?: 0f) / 100f
                        )
                        DataSensorBar(
                            label = "Suhu Tanah",
                            value = dataSensor?.soiltemperature ?: 0,
                            painter = painterResource(id = R.drawable.soil_temperature), // Assuming the max value is 50 (adjust as needed)
                            percentage = (dataSensor?.soiltemperature?.toFloat() ?: 0f) / 50f
                        )
                        DataSensorBar(
                            label = "PH Tanah",
                            value = dataSensor?.soilph ?: 0,
                            painter = painterResource(id = R.drawable.meters), // Assuming the max value is 14
                            percentage = (dataSensor?.soilph?.toFloat() ?: 0f) / 14f
                        )
                        DataSensorBar(
                            label = "Konduktivitas",
                            value = dataSensor?.soilconductivity ?: 0,
                            painter = painterResource(id = R.drawable.electricity),
                            percentage = (dataSensor?.soilconductivity?.toFloat() ?: 0f) / 200f
                        )
                    }
                } else {
                    Text("data Sesnor kosong")
                }

            }
        }
    }
}