package com.example.uitugasakhir

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
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.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.example.app.ui.theme.Inria_Regular
import com.example.app.ui.theme.Inter
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.ui.platform.LocalContext
import android.widget.Toast
import com.android.volley.Request
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import org.json.JSONObject
import androidx.compose.runtime.LaunchedEffect
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.compose.runtime.Composable
import com.example.uitugasakhir.ViewModel.RiwayatViewModel
import com.example.uitugasakhir.ViewModel.MQTTViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import android.util.Log
import org.json.JSONArray
import com.example.uitugasakhir.ViewModel.SensorViewModel
import com.google.accompanist.swiperefresh.*
import com.example.uitugasakhir.model.JadwalItem
import com.example.uitugasakhir.ViewModel.ManualViewModel
import com.example.uitugasakhir.api.RetrofitClient
import androidx.compose.animation.core.tween
import com.example.uitugasakhir.ui_manual.SensorSection
import com.example.uitugasakhir.ui_manual.PenyiramanSection
import com.example.uitugasakhir.ui_manual.RiwayatSection
import com.example.uitugasakhir.ui_manual.RataRataSection

import com.example.uitugasakhir.ui_otomatis.JadwalSection
import com.example.uitugasakhir.ui_otomatis.JedaPenyiramanCard

import com.example.uitugasakhir.aksi.DeleteDialog
import com.example.uitugasakhir.ui.komponen.WarningPopup
import android.media.MediaPlayer

import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings

import com.example.uitugasakhir.ui_otomatis.SensorSectionOtomatis
import com.example.uitugasakhir.ui_otomatis.RiwayatSectionOtomatis
import com.example.uitugasakhir.ui_otomatis.AmbangBatasSection

import com.example.uitugasakhir.ViewModel.PumpViewModel
import com.example.uitugasakhir.ViewModel.MainViewModel
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue

import com.example.uitugasakhir.mqtt.MqttManager
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.ui.res.stringResource
import com.example.uitugasakhir.ui_otomatis.RataRataOtomatisSection


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ManualScreen(
    navController: NavController,
    sensorVm: SensorViewModel,
    mainVm: MainViewModel
) {
    // Riwayat viewModel
    val viewModel = mainVm
    val mainViewModel: MainViewModel = viewModel()
    val mode = mainVm.mode
    val isLoading = mainVm.isLoading
    val context = LocalContext.current

    val snackbarHostState = remember {
        SnackbarHostState()
    }

    var showPopup by remember {
        mutableStateOf(false)
    }

    val mqttVm: MQTTViewModel = viewModel()
    val mqttState = mqttVm.state

    val sheetState = rememberModalBottomSheetState(
        skipPartiallyExpanded = false
    )

    var mutePopupUntil by remember {
        mutableLongStateOf(0L)
    }

    var disablePopup1Minute by remember {
        mutableStateOf(false)
    }

    var popupMessage by remember {
        mutableStateOf("")
    }


    val mqtt = remember {
        MqttManager(context)
    }

    val mediaPlayerManual = remember {
        MediaPlayer.create(context, R.raw.peringatan)
    }

    DisposableEffect(Unit) {
        onDispose {
            mediaPlayerManual.release()
        }
    }

    var autoStatus by remember {
        mutableStateOf("Monitoring sistem")
    }

    LaunchedEffect(Unit) {

        viewModel.initMQTT(context)

        viewModel.loadRiwayat(context)

        Log.d(
            "LOAD_RIWAYAT",
            "Size = ${viewModel.riwayatList.size}"
        )
    }

    LaunchedEffect(Unit) {
        mainViewModel.loadAverageSensor(context)
    }

    // Set pompa
    val pumpVm: PumpViewModel = viewModel()

    // ✅ FIX 1: rename supaya tidak bentrok
    val manualViewModel: ManualViewModel = viewModel()
    val swipeState = rememberSwipeRefreshState(manualViewModel.isLoading)

    val riwayatVm: RiwayatViewModel = viewModel()

    var showDeleteDialog by remember { mutableStateOf(false) }
    var selectedDeleteId by remember { mutableStateOf("") }

    var targetMode by remember { mutableStateOf("") }


    var jeda by remember { mutableStateOf("") }

    val formattedJeda = jeda.padStart(2, '0')

    val interactionSource = remember { MutableInteractionSource() }
    val isPressed by interactionSource.collectIsPressedAsState()

    val scale by animateFloatAsState(
        targetValue = if (isPressed) 0.95f else 1f,
        label = "scale",
        animationSpec = tween(300)
    )

    var selected by remember { mutableStateOf("Manual") }

    var showConfirmDialog by remember { mutableStateOf(false) }
    var showSettingDialog by remember { mutableStateOf(false) }

    val status = sensorVm.status


    //Pop up
    LaunchedEffect(Unit) {

        mqtt.connect(

            onConnected = {
                Log.d("MQTT", "CONNECTED")
            },

            onMessage = { topic, msg ->

                try {

                    val json = JSONObject(msg)

                    // ================= ALARM =================
                    if (topic == "smartplant/alarm") {

                        val message =
                            json.optString("message")

                        if (message != "AMAN") {

                            val now = System.currentTimeMillis()

                            // CEK APAKAH POPUP SEDANG DIMUTE
                            if (now > mutePopupUntil) {

                                showPopup = true
                                popupMessage = message
                            }

                        } else {

                            showPopup = false
                        }
                    }

                    // ================= SENSOR =================
                    if (topic == "smartplant/sensor") {

                        val tanah =
                            json.optInt("tanah")

                        val hujan =
                            json.optInt("hujan")

                        Log.d(
                            "HUJAN_DEBUG",
                            "HUJAN = $hujan"
                        )

                        // ================= HUJAN =================
                        if (hujan > 80) {

                            autoStatus =
                                "Hujan terdeteksi.\nPenyiraman ditunda"
                        }

                        // ================= TANAH KERING =================
                        else if (tanah < 20) {

                            autoStatus =
                                "Penyiraman otomatis berjalan"
                        }

                        // ================= NORMAL =================
                        else {

                            autoStatus =
                                "Tanah lembab.\nPompa tidak aktif"
                        }
                    }

                } catch (e: Exception) {

                    Log.e(
                        "MQTT_ERROR",
                        e.toString()
                    )
                }
            }
        )
    }

    // LOAD DATA
    LaunchedEffect(Unit) {
        riwayatVm.loadRiwayat(1)
        sensorVm.getData(context)
    }

    //========== Batas Akhir ============

    var jedaDetik by remember {
        mutableIntStateOf(0)
    }

    // Jadwal ui

    var jadwalList by remember {
        mutableStateOf(listOf<JadwalItem>())
    }

    val loadJadwal = remember {

        {

            val url = "http://kopikaosmartsystem.my.id/get_jadwal.php"

            val request = StringRequest(
                Request.Method.GET,
                url,

                { response ->

                    try {

                        Log.d("API_RESPONSE", response)

                        val jsonObject = JSONObject(response)

                        val jsonArray = jsonObject.getJSONArray("jadwal")

                        val temp = mutableListOf<JadwalItem>()

                        for (i in 0 until jsonArray.length()) {

                            val obj = jsonArray.getJSONObject(i)

                            temp.add(

                                JadwalItem(
                                    id = obj.getString("id"),
                                    waktu = obj.getString("waktu"),
                                    status = obj.getString("status")
                                )
                            )
                        }

                        jadwalList = temp

                    } catch (e: Exception) {

                        Log.e("JSON_ERROR", e.toString())
                    }
                },

                { error ->

                    Log.e("API_ERROR", error.toString())
                }
            )

            Volley.newRequestQueue(context).add(request)
        }
    }

    LaunchedEffect(Unit) {
        loadJadwal()
    }



    LaunchedEffect(status) {
        if (status.isNotEmpty()) {
            Toast.makeText(context, status.toString(), Toast.LENGTH_SHORT).show()
        }
    }

    Box(
        modifier = Modifier.fillMaxSize()
    ) {



        Box(
            modifier = Modifier.fillMaxSize()
        ) {
            // HEADER HIJAU
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(160.dp),
                contentAlignment = Alignment.TopCenter
            ) {
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(0.dp),
                    colors = CardDefaults.cardColors(
                        containerColor = Color(0xFF2F6F4E)
                    )
                ) {
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(top = 22.dp),
                        contentAlignment = Alignment.TopCenter
                    ) {
                        Image(
                            painter = painterResource(id = R.drawable.back),
                            contentDescription = "kembali",
                            modifier = Modifier
                                .size(15.dp)
                                .offset(x = (-160).dp, y = 1.dp)
                                .clickable {
                                    navController.popBackStack()
                                }
                        )

                        Text(
                            text = "Penyiraman",
                            fontSize = 16.sp,
                            fontFamily = Inter,
                            fontWeight = FontWeight.Bold,
                            color = Color.White
                        )
                    }
                }
            }

            // CONTENT PUTIH
            Card(
                modifier = Modifier
                    .padding(top = 64.dp)
                    .fillMaxSize(),
                shape = RoundedCornerShape(topStart = 24.dp),
                colors = CardDefaults.cardColors(
                    containerColor = Color.White
                )
            ) {

                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(top = 15.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {

                    // JUDUL MODE
                    Text(
                        text = stringResource(R.string.watering_mode),
                        fontSize = 15.sp,
                        fontFamily = Inria_Regular,
                        fontWeight = FontWeight.Medium,
                        color = Color.Black,
                        modifier = Modifier
                            .align(Alignment.Start)
                            .padding(horizontal = 28.dp)
                    )

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

                    Text(
                        text = stringResource(R.string.select_a_watering_mode),
                        fontSize = 12.sp,
                        fontFamily = Inria_Regular,
                        fontWeight = FontWeight.Normal,
                        color = Color.Gray,
                        modifier = Modifier.align(Alignment.Start).padding(horizontal = 28.dp)
                    )

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

                    // TOGGLE MANUAL OTOMATIS
                    Column(
                        modifier = Modifier
                            .verticalScroll(rememberScrollState()),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Card(
                            modifier = Modifier
                                .padding(horizontal = 25.dp)
                                .size(width = 333.dp, height = 100.dp),
                            shape = RoundedCornerShape(24.dp),
                            colors = CardDefaults.cardColors(
                                containerColor = Color(0xFFEDEDED)
                            ),
                            elevation = CardDefaults.cardElevation(4.dp)
                        ) {

                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(horizontal = 12.dp)
                                    .offset(y = 23.dp)
                                    .height(55.dp)
                                    .clip(RoundedCornerShape(50.dp))
                                    .background(Color(0xFFD9D9D9))
                                    .padding(4.dp),
                                verticalAlignment = Alignment.CenterVertically
                            ) {

                                // ================= OTOMATIS =================
                                Box(
                                    modifier = Modifier
                                        .weight(1f)
                                        .fillMaxHeight()
                                        .clip(RoundedCornerShape(20.dp))
                                        .background(
                                            if (selected == "Otomatis")
                                                Color(0xFF2F6F4E)
                                            else
                                                Color.Transparent
                                        )
                                        .clickable {
                                            if (selected != "Otomatis") {
                                                targetMode = "Otomatis"
                                                showConfirmDialog = true
                                            }
                                        },
                                    contentAlignment = Alignment.Center
                                ) {
                                    Text(
                                        "Otomatis",
                                        color = if (selected == "Otomatis")
                                            Color.White else Color.Black
                                    )
                                }

                                // ================= MANUAL =================
                                Box(
                                    modifier = Modifier
                                        .weight(1f)
                                        .fillMaxHeight()
                                        .clip(RoundedCornerShape(20.dp))
                                        .background(
                                            if (selected == "Manual")
                                                Color(0xFF2F6F4E)
                                            else
                                                Color.Transparent
                                        )
                                        .clickable {
                                            if (selected != "Manual") {
                                                targetMode = "Manual"
                                                showConfirmDialog = true
                                            }
                                        },
                                    contentAlignment = Alignment.Center
                                ) {
                                    Text(
                                        "Manual",
                                        color = if (selected == "Manual")
                                            Color.White else Color.Black
                                    )
                                }
                            }
                        }

                        // Ikon Pengaturan
                        Box(
                        ) {
                            if (selected == "Otomatis") {
                                Icon(
                                    imageVector = Icons.Default.Settings,
                                    contentDescription = "Pengaturan",
                                    tint = Color.Black.copy(alpha = 0.7f), // 🔥 ganti putih biar kelihatan (background abu2)
                                    modifier = Modifier
                                        .align(Alignment.TopEnd)
                                        .padding(top = 15.dp, end = 8.dp)
                                        .offset(x = 150.dp)
                                        .size(30.dp)
                                        .clickable {
                                            showSettingDialog = true
                                        }
                                )
                            }
                        }

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

                        // Tampilan monitoring otomatis
                        if (selected == "Otomatis") {

                            SensorSectionOtomatis()

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

                            RataRataOtomatisSection(
                                snackbarHostState = snackbarHostState
                            )

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

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

                            Text(
                                text = stringResource(R.string.displays_the_status_of_the_sensors_pump_and_watering_mode),
                                fontSize = 12.sp,
                                fontFamily = Inria_Regular,
                                fontWeight = FontWeight.Normal,
                                color = Color.Gray,
                                modifier = Modifier.padding(horizontal = 25.dp)
                            )

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

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

                                    Box(
                                        modifier = Modifier
                                            .size(12.dp)
                                            .background(
                                                when {

                                                    autoStatus.contains("Hujan") ->
                                                        Color(0xFF2196F3)

                                                    autoStatus.contains("ditunda") ->
                                                        Color(0xFF2196F3)

                                                    autoStatus.contains("berjalan") ->
                                                        Color(0xFF2F6F4E)

                                                    autoStatus.contains("Menunggu") ->
                                                        Color(0xFFFF9800)

                                                    autoStatus.contains("Jeda") ->
                                                        Color(0xFFFF9800)

                                                    autoStatus.contains("lembab") ->
                                                        Color.Gray

                                                    else ->
                                                        Color.LightGray
                                                },
                                                RoundedCornerShape(50)
                                            )
                                    )

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

                                    Text(
                                        text = autoStatus,
                                        fontSize = 14.sp,
                                        color = Color.DarkGray
                                    )
                                }
                            }
                        }

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

                        if (selected == "Otomatis") {
                            RiwayatSectionOtomatis(viewModel.riwayatList)
                        }
                    }

                    // Pop up Konfirmasi
                    if (showConfirmDialog) {
                        AlertDialog(
                            onDismissRequest = {
                                showConfirmDialog = false
                            },
                            title = {
                                Text("Konfirmasi")
                            },
                            text = {
                                Text("Anda akan beralih ke mode $targetMode. Tekan OK untuk melanjutkan.")
                            },
                            confirmButton = {
                                TextButton(
                                    onClick = {
                                        selected = targetMode
                                        mqttVm.setMode(targetMode)
                                        showConfirmDialog = false
                                        sensorVm.setMode(targetMode)
                                        mqttVm.setMode(targetMode)
                                    }
                                ) {
                                    Text("OK")
                                }
                            },
                            dismissButton = {
                                TextButton(
                                    onClick = {
                                        showConfirmDialog = false
                                    }
                                ) {
                                    Text("Batal")
                                }
                            }
                        )
                    }

                    // popup pengaturan jadwal
                    if (showSettingDialog) {

                        ModalBottomSheet(
                            onDismissRequest = {
                                showSettingDialog = false
                            },
                            sheetState = sheetState,
                            containerColor = Color.White
                        ) {

                            Column(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .fillMaxHeight(0.7f) // 70% tinggi layar
                                    .padding(16.dp)
                                    .verticalScroll(rememberScrollState())
                            ) {

                                Text(
                                    text = "Pengaturan Mode Otomatis",
                                    fontSize = 18.sp,
                                    fontWeight = FontWeight.Bold
                                )

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

                                JadwalSection(
                                    jadwalList = jadwalList,
                                    loadJadwal = { loadJadwal() },
                                    context = context,
                                    onDeleteClick = { id ->
                                        selectedDeleteId = id
                                        showDeleteDialog = true
                                    }
                                )

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

                                JedaPenyiramanCard(
                                    onJedaChanged = {
                                        jedaDetik = it
                                    }
                                )

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

                                AmbangBatasSection()

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

                                Row(
                                    modifier = Modifier.fillMaxWidth(),
                                    horizontalArrangement = Arrangement.End
                                ) {

                                    TextButton(
                                        onClick = {
                                            showSettingDialog = false
                                        }
                                    ) {
                                        Text("Batal")
                                    }

                                    Button(
                                        onClick = {
                                            selected = "Otomatis"
                                            viewModel.setMode("Otomatis")
                                            showSettingDialog = false
                                        }
                                    ) {
                                        Text("Simpan")
                                    }
                                }

                                Spacer(modifier = Modifier.height(20.dp))
                            }
                        }
                    }
                    //Aksi tombol delete
                    if (showDeleteDialog) {
                        DeleteDialog(
                            showDialog = true,
                            selectedId = selectedDeleteId,
                            context = context,
                            onDismiss = {
                                showDeleteDialog = false
                            },
                            onSuccess = {
                                loadJadwal()
                            }
                        )
                    }

                    // KONTEN BERDASARKAN MODE
                    when (selected) {

                        "Manual" -> {

                            // Tampilan utama monitoring sensor
                            Box(
                                modifier = Modifier.fillMaxSize()
                            ) {

                                // =================== SEMUA KONTEN UTAMA ===================
                                Column(
                                    modifier = Modifier
                                        .fillMaxSize()
                                        .verticalScroll(rememberScrollState())
                                ) {

                                    // Tampilan utama monitoring sensor
                                    SensorSection()

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

                                    RataRataSection(
                                        snackbarHostState = snackbarHostState
                                    )

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

                                    // Tampilan utama penyiraman sensor

                                    PenyiramanSection(
                                        mode = mode,
                                        pumpStatus = mqttState.pump,
                                        isLoading = isLoading,
                                        onPumpChange = { status ->

                                            // publish MQTT
                                            mqttVm.setPump(status == "ON")

                                            // simpan riwayat
                                            viewModel.onPumpChange(
                                                context = context,
                                                status = status,
                                                mode = mode
                                            )
                                        }
                                    )

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

                                    // Tampilan utama riwayat sensor
                                    RiwayatSection(
                                        riwayatList = viewModel.riwayatList
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }
    }


    WarningPopup(
        show = showPopup,
        message = popupMessage,

        onDismiss = {

            // JIKA CHECKBOX AKTIF
            if (disablePopup1Minute) {

                mutePopupUntil =
                    System.currentTimeMillis() + 60000
            }

            showPopup = false
        },

        disablePopup1Minute = disablePopup1Minute,

        onDisableChange = {
            disablePopup1Minute = it
        }
    )
}
