package com.example.uitugasakhir.Page

import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.*
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
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.uitugasakhir.R
import com.example.uitugasakhir.ViewModel.SensorViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*
import androidx.compose.foundation.clickable

import android.util.Log



@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NotifikasiScreen(
    navController: NavController,
    sensorVm: SensorViewModel
) {

    val list = sensorVm.warningList

    var selectedFilter by remember {
        mutableStateOf("Semua")
    }

    val filteredList = when (selectedFilter) {

        "Tanah" ->
            list.filter {
                it.message.contains("tanah", ignoreCase = true)
            }

        "Udara" ->
            list.filter {
                it.message.contains("udara", ignoreCase = true)
            }

        else -> list
    }

    LaunchedEffect(Unit) {
        sensorVm.loadLogs()
    }


    val selected = sensorVm.selectedItems

    LaunchedEffect(Unit) {

        sensorVm.readAllNotifications()
    }

    LaunchedEffect(list) {
        Log.d("NOTIF_DEBUG", "Jumlah notif: ${list.size}")
        list.forEach {
            Log.d("NOTIF_DEBUG", "Item: ${it.id} - ${it.message}")
        }
    }

    val snackbarHostState = remember { SnackbarHostState() }
    val scope = rememberCoroutineScope()



    Box(modifier = Modifier.fillMaxSize()) {

        // =========================
        // HEADER HIJAU
        // =========================
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(160.dp)
                .background(Color(0xFF2F6F4E)),
            contentAlignment = Alignment.TopCenter
        ) {

            Image(
                painter = painterResource(id = R.drawable.back),
                contentDescription = "back",
                modifier = Modifier
                    .size(18.dp)
                    .offset(x = -160.dp, y = 30.dp)
                    .clickable {
                        navController.popBackStack()
                    }
            )

            Text(
                text = "Notifikasi",
                fontSize = 16.sp,
                fontWeight = FontWeight.Bold,
                color = Color.White,
                modifier = Modifier.padding(top = 30.dp)
            )

            IconButton(
                onClick = {
                    val deleted = list.toList()

                    sensorVm.deleteAllWarnings()

                    scope.launch {
                        val res = snackbarHostState.showSnackbar(
                            message = "Semua notifikasi dihapus",
                            actionLabel = "UNDO",
                            duration = SnackbarDuration.Short
                        )

                        if (res == SnackbarResult.ActionPerformed) {
                            sensorVm.restoreDeleted(deleted)
                        }
                    }
                },
                modifier = Modifier
                    .align(Alignment.TopEnd)
                    .padding(top = 20.dp, end = 16.dp)
            ) {
                Icon(
                    imageVector = Icons.Default.Delete,
                    contentDescription = "Hapus Semua",
                    tint = Color.White
                )
            }
        }

        // =========================
        // CARD PUTIH FLOATING
        // =========================
        Card(
            modifier = Modifier
                .fillMaxSize()
                .padding(top = 70.dp),
            shape = RoundedCornerShape(topStart = 24.dp, topEnd = 0.dp),
            colors = CardDefaults.cardColors(containerColor = Color.White)
        ) {

            Scaffold(
                snackbarHost = { SnackbarHost(snackbarHostState) },

                // =========================
                // BOTTOM DELETE BAR
                // =========================
                bottomBar = {
                    if (selected.isNotEmpty()) {
                        BottomAppBar(containerColor = Color(0xFF1976D2)) {

                            Text(
                                text = "${selected.size} dipilih",
                                color = Color.White,
                                modifier = Modifier
                                    .weight(1f)
                                    .padding(start = 16.dp)
                            )

                            IconButton(onClick = {
                                val deleted = list.filter { it.id in selected }

                                sensorVm.deleteSelected()

                                scope.launch {
                                    val res = snackbarHostState.showSnackbar(
                                        message = "Terhapus",
                                        actionLabel = "UNDO"
                                    )

                                    if (res == SnackbarResult.ActionPerformed) {
                                        sensorVm.restoreDeleted(deleted)
                                    }
                                }
                            }) {
                                Icon(
                                    imageVector = Icons.Default.Delete,
                                    contentDescription = null,
                                    tint = Color.White
                                )
                            }
                        }
                    }
                }
            ) { padding ->

                Column(
                    modifier = Modifier
                        .padding(padding)
                        .fillMaxSize()
                ) {

                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp),
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {

                        FilterChip(
                            selected = selectedFilter == "Semua",
                            onClick = {
                                selectedFilter = "Semua"
                            },
                            label = {
                                Text("Semua")
                            }
                        )

                        FilterChip(
                            selected = selectedFilter == "Tanah",
                            onClick = {
                                selectedFilter = "Tanah"
                            },
                            label = {
                                Text("🌱 Tanah")
                            }
                        )

                        FilterChip(
                            selected = selectedFilter == "Udara",
                            onClick = {
                                selectedFilter = "Udara"
                            },
                            label = {
                                Text("🌡 Udara")
                            }
                        )
                    }

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

                        items(filteredList, key = { it.id }) { item ->

                            Log.d("NOTIF_ITEM", "Render item: ${item.id}")

                            val isSelected = selected.contains(item.id)

                            val bgColor by animateColorAsState(
                                if (isSelected) Color(0xFFE3F2FD) else Color.White
                            )

                            // =========================
                            // SWIPE DELETE (VERSI STABIL)
                            // =========================
                            SwipeToDismissBox(
                                state = rememberSwipeToDismissBoxState(
                                    confirmValueChange = { value ->
                                        if (value == SwipeToDismissBoxValue.EndToStart ||
                                            value == SwipeToDismissBoxValue.StartToEnd
                                        ) {
                                            sensorVm.deleteWarning(item)

                                            scope.launch {
                                                snackbarHostState.showSnackbar("Dihapus")
                                            }
                                        }
                                        true
                                    }
                                ),

                                backgroundContent = {
                                    Box(
                                        modifier = Modifier
                                            .fillMaxSize()
                                            .background(Color.Red)
                                            .padding(end = 20.dp),
                                        contentAlignment = Alignment.CenterEnd
                                    ) {
                                        Icon(
                                            imageVector = Icons.Default.Delete,
                                            contentDescription = null,
                                            tint = Color.White
                                        )
                                    }
                                }
                            ) {

                                // =========================
                                // ITEM UI
                                // =========================
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .background(bgColor)
                                        .pointerInput(Unit) {
                                            detectTapGestures(
                                                onTap = {
                                                    if (selected.isNotEmpty()) {
                                                        sensorVm.toggleSelection(item)
                                                    }
                                                },
                                                onLongPress = {
                                                    sensorVm.toggleSelection(item)
                                                }
                                            )
                                        }
                                        .padding(16.dp)
                                ) {

                                    val icon = when {

                                        item.message.contains("tanah", true) -> "🌱"

                                        item.message.contains("udara", true) -> "🌡"

                                        else -> "⚠️"

                                    }

                                    Text(icon, fontSize = 20.sp)

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

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

                                        Text(
                                            text = item.status,
                                            fontSize = 12.sp,
                                            color = Color(0xFF2F6F4E),
                                            fontWeight = FontWeight.Bold
                                        )

                                        Text(
                                            text = item.message,
                                            fontSize = 14.sp
                                        )

                                        Text(
                                            text = formatTime(item.time),
                                            fontSize = 12.sp,
                                            color = Color.Gray
                                        )
                                    }

                                    if (isSelected) {
                                        Text("✔", color = Color(0xFF1976D2))
                                    }
                                }
                            }

                            Divider()
                        }
                    }
                }
            }
        }
    }
}

// =========================
// FORMAT TIME
// =========================
fun formatTime(time: Long): String {
    val sdf = SimpleDateFormat("HH:mm", Locale.getDefault())
    return sdf.format(Date(time))
}