package com.example.uitugasakhir.ui_otomatis

import android.content.Intent
import android.net.Uri
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.app.ui.theme.Inria_Regular
import com.example.uitugasakhir.R
import com.example.uitugasakhir.ViewModel.MainViewModel
import kotlinx.coroutines.launch

@Composable
fun RataRataOtomatisSection(
    snackbarHostState: SnackbarHostState
) {

    val mainViewModel: MainViewModel = viewModel()
    val context = LocalContext.current
    val scope = rememberCoroutineScope()

    val avgKU = mainViewModel.avgKU
    val avgSU = mainViewModel.avgSU
    val avgKT = mainViewModel.avgKT
    val avgIH = mainViewModel.avgIH

    Text(
        text = stringResource(R.string.average_sensor_status),
        fontSize = 15.sp,
        fontFamily = Inria_Regular,
        fontWeight = FontWeight.Medium,
        color = Color.Black,
        modifier = Modifier.padding(horizontal = 28.dp)
    )

    Spacer(modifier = Modifier.height(5.dp))

    Text(
        text = stringResource(R.string.a_summary_of_the_latest_status_from_each_sensor),
        fontSize = 12.sp,
        fontFamily = Inria_Regular,
        color = Color.Gray,
        modifier = Modifier.padding(horizontal = 28.dp)
    )

    Spacer(modifier = Modifier.height(15.dp))

    Card(
        modifier = Modifier
            .padding(horizontal = 25.dp)
            .fillMaxWidth()
            .height(190.dp),
        shape = RoundedCornerShape(24.dp),
        colors = CardDefaults.cardColors(
            containerColor = Color(0xFFEDEDED)
        ),
        elevation = CardDefaults.cardElevation(4.dp)
    ) {

        Column(
            modifier = Modifier.fillMaxSize()
        ) {

            LazyRow(
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                contentPadding = PaddingValues(12.dp)
            ) {

                item {
                    SensorCard(
                        title = "💧 Udara",
                        value = if(avgKU > 0) "${avgKU.toInt()}%" else "--",
                        status = if(avgKU > 0) statusKelembaban(avgKU) else "Memuat...",
                        color = Color(0xFF4FC3F7)
                    )
                }

                item {
                    SensorCard(
                        title = "🌡 Suhu",
                        value = if(avgSU > 0) "${avgSU.toInt()}°C" else "--",
                        status = if(avgSU > 0) statusSuhu(avgSU) else "Memuat...",
                        color = Color(0xFF2E8B57)
                    )
                }

                item {
                    SensorCard(
                        title = "🌱 Tanah",
                        value = if(avgKT > 0) "${avgKT.toInt()}%" else "--",
                        status = if(avgKT > 0) statusKelembaban(avgKT) else "Memuat...",
                        color = Color(0xFF8B5A2B)
                    )
                }

                item {
                    SensorCard(
                        title = "🌧 Hujan",
                        value = if(avgIH > 0) "${avgIH.toInt()}%" else "--",
                        status = if(avgIH > 0){
                            when{
                                avgIH < 40 -> "Ringan"
                                avgIH < 70 -> "Sedang"
                                else -> "Deras"
                            }
                        }else{
                            "Memuat..."
                        },
                        color = Color(0xFF1E3A5F)
                    )
                }
            }

            Spacer(
                modifier = Modifier.weight(1f)
            )

            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(12.dp),
                shape = RoundedCornerShape(16.dp),
                colors = CardDefaults.cardColors(
                    containerColor = Color(0xFFE8F5E9)
                )
            ){

                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(12.dp),
                    verticalAlignment = Alignment.CenterVertically
                ){

                    Text(
                        text = "📥",
                        fontSize = 26.sp
                    )

                    Spacer(
                        modifier = Modifier.width(10.dp)
                    )

                    Column(
                        modifier = Modifier.weight(1f)
                    ){

                        Text(
                            text = "Unduh Data Monitoring",
                            fontSize = 13.sp,
                            fontWeight = FontWeight.Bold,
                            color = Color(0xFF1B5E20)
                        )

                        Text(
                            text = "Ekspor data sensor untuk laporan",
                            fontSize = 11.sp,
                            color = Color(0xFF388E3C)
                        )
                    }

                    Button(
                        onClick = {

                            val intent = Intent(
                                Intent.ACTION_VIEW,
                                Uri.parse(
                                    "http://kopikaosmartsystem.my.id/download_sensor_excel.php"
                                )
                            )

                            try{

                                context.startActivity(intent)

                                scope.launch {
                                    snackbarHostState.showSnackbar(
                                        "Membuka data sensor..."
                                    )
                                }

                            }catch(e:Exception){

                                scope.launch {
                                    snackbarHostState.showSnackbar(
                                        "Gagal membuka data"
                                    )
                                }

                            }

                        },
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(0xFF4CAF50)
                        )
                    ){

                        Text(
                            text = "Unduh",
                            fontSize = 11.sp
                        )

                    }

                }

            }

        }

    }

}


@Composable
fun SensorCard(
    title:String,
    value:String,
    status:String,
    color:Color
){

    Card(
        modifier = Modifier
            .width(95.dp)
            .height(85.dp),
        shape = RoundedCornerShape(16.dp),
        colors = CardDefaults.cardColors(
            containerColor = Color.White
        ),
        elevation = CardDefaults.cardElevation(2.dp)
    ){

        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(8.dp),
            verticalArrangement = Arrangement.SpaceBetween
        ){

            Text(
                text = title,
                fontSize = 10.sp,
                fontWeight = FontWeight.SemiBold,
                color = color
            )

            Text(
                text = value,
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold,
                color = Color.Black
            )

            Text(
                text = status,
                fontSize = 9.sp,
                color = Color.Gray
            )

        }

    }

}