package com.example.uitugasakhir

import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.runtime.*
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.navigation.NavController
import androidx.compose.foundation.background
import android.content.Context
import android.os.Environment
import android.widget.Toast
import java.io.File
import java.io.FileWriter
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.draw.scale
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.uitugasakhir.model.RiwayatItem
import com.example.uitugasakhir.ViewModel.MainViewModel
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import android.content.ContentValues
import android.os.Build
import android.provider.MediaStore
import android.util.Log

import java.text.SimpleDateFormat
import java.util.Locale

import androidx.compose.material.icons.filled.Download
import com.example.app.ui.theme.Inria_Regular


@Composable
fun RiwayatScreen(navController: NavController) {

    val viewModel: MainViewModel = viewModel()

    //Riwayat hari ini, minggu ini dan bulan ini

    val data = viewModel.riwayatList

    val penyiramanData = viewModel.riwayatList.filter {
        it.aksi == "Pompa Dinyalakan"
    }

    val dataMingguan = viewModel.getDataMingguan(penyiramanData)
    val dataHarian = viewModel.getDataHarian(penyiramanData)

    // Halaman tabel selanjutnya dan sebelumnya
    var currentPage by remember { mutableStateOf(0) }
    val pageSize = 10

    var isDownloading by remember { mutableStateOf(false) }
    var isSuccess by remember { mutableStateOf<Boolean?>(null) }

    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    val snackbarHostState = remember { SnackbarHostState() }

    val scale by animateFloatAsState(
        targetValue = if (isDownloading) 0.9f else 1f,
        animationSpec = tween(200)
    )

    // STATE

    var showFileNameDialog by remember { mutableStateOf(false) }

    var fileName by remember { mutableStateOf("") }

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

    // Total penyiraman
    val sdfServer = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())


    val dataHariIni = penyiramanData.count {

        val split = it.waktu.split(" ")
        val tanggal = split.getOrNull(0) ?: return@count false

        val date = sdfServer.parse(tanggal) ?: return@count false

        val cal1 = java.util.Calendar.getInstance()
        val cal2 = java.util.Calendar.getInstance()

        cal1.time = date
        cal2.time = java.util.Date()

        cal1.get(java.util.Calendar.DAY_OF_YEAR) ==
                cal2.get(java.util.Calendar.DAY_OF_YEAR) &&
                cal1.get(java.util.Calendar.YEAR) ==
                cal2.get(java.util.Calendar.YEAR)
    }

    val dataMingguIni = penyiramanData.count {

        val split = it.waktu.split(" ")
        val tanggal = split.getOrNull(0) ?: return@count false

        val date = sdfServer.parse(tanggal) ?: return@count false

        val cal1 = java.util.Calendar.getInstance()
        val cal2 = java.util.Calendar.getInstance()

        cal1.time = date
        cal2.time = java.util.Date()

        cal1.get(java.util.Calendar.WEEK_OF_YEAR) ==
                cal2.get(java.util.Calendar.WEEK_OF_YEAR) &&
                cal1.get(java.util.Calendar.YEAR) ==
                cal2.get(java.util.Calendar.YEAR)
    }

    val dataBulanIni = penyiramanData.count {

        val split = it.waktu.split(" ")
        val tanggal = split.getOrNull(0) ?: return@count false

        val date = sdfServer.parse(tanggal) ?: return@count false

        val cal1 = java.util.Calendar.getInstance()
        val cal2 = java.util.Calendar.getInstance()

        cal1.time = date
        cal2.time = java.util.Date()

        cal1.get(java.util.Calendar.MONTH) ==
                cal2.get(java.util.Calendar.MONTH) &&
                cal1.get(java.util.Calendar.YEAR) ==
                cal2.get(java.util.Calendar.YEAR)
    }

    val totalData = penyiramanData.size

    // ================= FILTER FIX =================
    val filteredData = data.filter { item ->

        val split = item.waktu.split(" ")
        val tanggal = split.getOrNull(0) ?: ""
        val jam = split.getOrNull(1) ?: ""

        val matchFilter =
            selectedFilter == "Semua" ||
                    item.mode == selectedFilter ||
                    item.status == selectedFilter


        val matchDate = when (selectedDateFilter) {

            "Hari ini" -> {
                val todayStr = java.text.SimpleDateFormat("dd-MM-yyyy")
                    .format(java.util.Date())
                tanggal == todayStr
            }

            else -> true
        }

        matchFilter && matchDate
    }

    val totalPage = (filteredData.size + pageSize - 1) / pageSize

    val pagedData = filteredData
        .drop(currentPage * pageSize)
        .take(pageSize)

    LaunchedEffect(Unit) {
        viewModel.loadRiwayat(context)
    }

    // ================= UI =================
    Box(modifier = Modifier.fillMaxSize()) {

        SnackbarHost(
            hostState = snackbarHostState,
            modifier = Modifier.align(Alignment.BottomCenter)
        )

        // HEADER
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .height(160.dp),
            shape = RoundedCornerShape(0.dp),
            colors = CardDefaults.cardColors(Color(0xFF2F6F4E))
        ) {
            Box(
                modifier = Modifier.fillMaxSize().padding(top = 22.dp),
                contentAlignment = Alignment.TopCenter
            ) {

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

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

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

            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp)
                    .verticalScroll(rememberScrollState())
                    .animateContentSize()
            ) {

                Text("Total Penyiraman",
                    fontSize = 15.sp,
                    fontFamily = Inria_Regular,
                    fontWeight = FontWeight.Medium,
                    color = Color.Gray,
                )

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

                // SUMMARY FIX
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(16.dp),
                    colors = CardDefaults.cardColors(Color(0xFFF2F2F2)),
                    elevation = CardDefaults.cardElevation(4.dp)
                ) {
                    Column(modifier = Modifier.padding(12.dp)) {

                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 8.dp),
                            horizontalArrangement = Arrangement.SpaceAround
                        ) {

                            SummaryMini("Hari", dataHariIni)
                            SummaryMini("Minggu", dataMingguIni)
                            SummaryMini("Bulan", dataBulanIni)
                            SummaryMini("Total", totalData)
                        }
                    }
                }

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

                Text("Grafik Penyiraman Minggu Ini",
                    fontSize = 15.sp,
                    fontFamily = Inria_Regular,
                    fontWeight = FontWeight.Medium,
                    color = Color.Gray,
                )

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

                Card(
                    modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp),
                    shape = RoundedCornerShape(16.dp),
                    colors = CardDefaults.cardColors(Color(0xFFF2F2F2)),
                    elevation = CardDefaults.cardElevation(4.dp)
                ) {
                    Column(Modifier.padding(16.dp)) {

                        Text("Minggu Ini", fontWeight = FontWeight.Normal)

                        Spacer(Modifier.height(12.dp))

                        BarChart(dataHarian)
                    }
                }

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

                Text("Grafik Penyiraman Bulan Ini",
                    fontSize = 15.sp,
                    fontFamily = Inria_Regular,
                    fontWeight = FontWeight.Medium,
                    color = Color.Gray,
                )

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

                Card(
                    modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp),
                    shape = RoundedCornerShape(16.dp),
                    colors = CardDefaults.cardColors(Color(0xFFF2F2F2)),
                    elevation = CardDefaults.cardElevation(4.dp)
                ) {
                    Column(Modifier.padding(16.dp)) {

                        Text("Bulan Ini", fontWeight = FontWeight.Normal)

                        Spacer(Modifier.height(12.dp))

                        BarChart(dataMingguan)
                    }
                }

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

                Text(
                    text = "Mode",
                    fontSize = 15.sp,
                    fontFamily = Inria_Regular,
                    fontWeight = FontWeight.Medium,
                    color = Color.Gray,
                )

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

                LazyRow(
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    contentPadding = PaddingValues(horizontal = 4.dp)
                ) {
                    items(listOf("Semua", "Otomatis", "Manual", "Berhasil", "Gagal")) { item ->

                        FilterChipModern(
                            label = item,
                            selected = selectedFilter == item,
                            onClick = { selectedFilter = item }
                        )
                    }
                }

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

                Text(
                    text = "Periode",
                    fontSize = 15.sp,
                    fontFamily = Inria_Regular,
                    fontWeight = FontWeight.Medium,
                    color = Color.Gray,
                )

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

                LazyRow(
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    contentPadding = PaddingValues(horizontal = 4.dp)
                ) {
                    items(listOf("Semua", "Hari ini", "Minggu ini", "Bulan ini")) { item ->

                        FilterChipModern(
                            label = item,
                            selected = selectedDateFilter == item,
                            onClick = { selectedDateFilter = item }
                        )
                    }
                }

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

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {

                    Text(
                        text = "Data: ${filteredData.size}",
                        fontSize = 13.sp,
                        color = Color.Gray
                    )

                    Button(
                        onClick = {

                            if (filteredData.isEmpty()) {

                                Toast.makeText(
                                    context,
                                    "Tidak ada data",
                                    Toast.LENGTH_SHORT
                                ).show()

                            } else {

                                fileName = ""
                                showFileNameDialog = true
                            }
                        }, enabled = !isDownloading,
                        modifier = Modifier
                            .scale(scale)
                            .height(42.dp),
                        shape = RoundedCornerShape(20.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(0xFF2F6F4E)
                        ),
                        contentPadding = PaddingValues(horizontal = 14.dp)
                    ) {

                        Icon(
                            imageVector = Icons.Default.Download,
                            contentDescription = "Download",
                            tint = Color.White,
                            modifier = Modifier.size(18.dp)
                        )

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

                        Text(
                            text = if (isDownloading) "Loading..." else "Unduh",
                            fontSize = 12.sp,
                            color = Color.White
                        )
                    }
                }

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

                // HEADER TABLE
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(Color(0xFF2F6F4E))
                        .padding(8.dp)
                ) {
                    TableText("No", 0.1f)
                    TableText("Tanggal", 0.3f)
                    TableText("Jam", 0.2f)
                    TableText("Mode", 0.2f)
                    TableText("Status", 0.2f)
                    TableText("", 0.1f)
                }

                pagedData.forEachIndexed { index, item ->

                    val split = item.waktu.split(" ")
                    val tanggal = split.getOrNull(0) ?: "-"
                    val jam = split.getOrNull(1) ?: "-"

                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = 4.dp),
                        colors = CardDefaults.cardColors(Color(0xFFF8F8F8)),
                        shape = RoundedCornerShape(12.dp)
                    ) {

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

                            TableText("${index + 1 + (currentPage * pageSize)}", 0.1f)
                            TableText(tanggal, 0.25f)
                            TableText(jam, 0.2f)
                            TableText(item.mode, 0.2f)
                            TableText(item.status, 0.15f)

                            Box(
                                modifier = Modifier.weight(0.1f),
                                contentAlignment = Alignment.Center
                            ) {
                                IconButton(
                                    onClick = {
                                        viewModel.deleteRiwayat(context, item)
                                    }
                                ) {
                                    Icon(
                                        imageVector = Icons.Default.Delete,
                                        contentDescription = "Hapus",
                                        tint = Color.Red,
                                        modifier = Modifier.size(18.dp)
                                    )
                                }
                            }
                        }
                    }
                }

                Spacer(Modifier.height(10.dp))

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.Center
                ) {
                    Text(
                        "<",
                        modifier = Modifier
                            .clickable {
                                if (currentPage > 0) currentPage--
                            }
                            .padding(12.dp),
                        fontSize = 20.sp
                    )

                    Text(
                        "Page ${currentPage + 1} / $totalPage",
                        modifier = Modifier.padding(12.dp)
                    )

                    Text(
                        ">",
                        modifier = Modifier
                            .clickable {
                                if (currentPage < totalPage - 1) currentPage++
                            }
                            .padding(12.dp),
                        fontSize = 20.sp
                    )
                }
            }
        }
    }

    if (showFileNameDialog) {

        AlertDialog(

            onDismissRequest = {
                showFileNameDialog = false
            },

            title = {
                Text("Nama File")
            },

            text = {

                OutlinedTextField(

                    value = fileName,

                    onValueChange = {
                        fileName = it
                    },

                    label = {
                        Text("Masukkan nama file")
                    },

                    singleLine = true

                )
            },

            confirmButton = {

                Button(

                    onClick = {

                        scope.launch {

                            isDownloading = true

                            val success = exportToCSV(

                                context,

                                filteredData,

                                if (fileName.isBlank())
                                    "Riwayat.csv"
                                else
                                    "$fileName.csv"

                            )

                            isDownloading = false

                            if (success) {

                                Toast.makeText(
                                    context,
                                    "Berhasil disimpan",
                                    Toast.LENGTH_LONG
                                ).show()

                            } else {

                                Toast.makeText(
                                    context,
                                    "Gagal menyimpan",
                                    Toast.LENGTH_LONG
                                ).show()
                            }

                            showFileNameDialog = false
                        }

                    }

                ) {

                    Text("Simpan")
                }

            },

            dismissButton = {

                TextButton(

                    onClick = {

                        showFileNameDialog = false

                    }

                ) {

                    Text("Batal")

                }

            }

        )

    }
}

// ================= COMPONENT FIX =================

@Composable
fun SummaryMini(label: String, value: Int) {

    val isToday = label == "Hari"

    Column(
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = "$value",
            fontWeight = FontWeight.Bold,
            fontSize = 16.sp,
            color = if (isToday) Color(0xFF2F6F4E) else Color.Black
        )
        Text(
            text = label,
            fontSize = 10.sp,
            color = Color.Gray
        )
    }
}

@Composable
fun FilterChip(label: String, selected: Boolean, onClick: () -> Unit) {
    Card(
        modifier = Modifier.clickable { onClick() },
        colors = CardDefaults.cardColors(
            if (selected) Color(0xFF2F6F4E) else Color.LightGray
        )
    ) {
        Text(
            text = label,
            modifier = Modifier.padding(8.dp),
            color = if (selected) Color.White else Color.Black
        )
    }
}

@Composable
fun RowScope.TableText(
    text: String,
    weight: Float,
    color: Color = Color.Black
) {
    Text(
        text = text,
        modifier = Modifier.weight(weight), // ✔ aman karena RowScope
        fontSize = 12.sp,
        color = color,
        textAlign = TextAlign.Center
    )
}

@Composable
fun TableText(
    text: String,
    modifier: Modifier = Modifier,
    color: Color = Color.Black
) {
    Text(
        text = text,
        modifier = modifier,
        fontSize = 12.sp,
        color = color,
        textAlign = TextAlign.Center
    )
}


// ================= EXPORT =================
fun exportToCSV(
    context: Context,
    data: List<RiwayatItem>,
    fileName: String
): Boolean {

    return try {

        val values = ContentValues().apply {

            put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
            put(MediaStore.MediaColumns.MIME_TYPE, "text/csv")

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                put(
                    MediaStore.MediaColumns.RELATIVE_PATH,
                    Environment.DIRECTORY_DOWNLOADS
                )
            }
        }

        val collection =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                MediaStore.Downloads.EXTERNAL_CONTENT_URI
            } else {
                MediaStore.Files.getContentUri("external")
            }

        val uri = context.contentResolver.insert(
            collection,
            values
        ) ?: return false

        context.contentResolver.openOutputStream(uri)?.use { output ->

            output.write("No,Tanggal,Jam,Mode,Status\n".toByteArray())

            data.forEachIndexed { index, item ->

                val split = item.waktu.split(" ")

                val tanggal = split.getOrNull(0) ?: "-"
                val jam = split.getOrNull(1) ?: "-"

                val row =
                    "${index + 1},$tanggal,$jam,${item.mode},${item.status}\n"

                output.write(row.toByteArray())
            }

            output.flush()
        }

        Log.d("CSV", "Berhasil menyimpan: $fileName")

        true

    } catch (e: Exception) {

        e.printStackTrace()
        Log.e("CSV", "Gagal export", e)

        false
    }
}

@Composable
fun FilterChipModern(
    label: String,
    selected: Boolean,
    onClick: () -> Unit
) {
    Surface(
        shape = RoundedCornerShape(20.dp),
        color = if (selected) Color(0xFF2F6F4E) else Color(0xFFEDEDED),
        shadowElevation = if (selected) 4.dp else 0.dp,
        modifier = Modifier.clickable { onClick() }
    ) {
        Text(
            text = label,
            modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp),
            fontSize = 12.sp,
            color = if (selected) Color.White else Color.Black
        )
    }
}

@Composable
fun BarChart(data: List<Pair<String, Int>>) {

    val maxValue = (data.maxOfOrNull { it.second } ?: 1).toFloat()

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .height(150.dp),
        horizontalArrangement = Arrangement.SpaceEvenly,
        verticalAlignment = Alignment.Bottom
    ) {

        data.forEach { (label, value) ->

            val heightRatio = value / maxValue

            Column(
                horizontalAlignment = Alignment.CenterHorizontally
            ) {

                Text("$value", fontSize = 10.sp)

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

                Box(
                    modifier = Modifier
                        .width(20.dp)
                        .height((100 * heightRatio).dp)
                        .background(Color(0xFF2F6F4E), RoundedCornerShape(6.dp))
                )

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

                Text(label, fontSize = 10.sp)
            }
        }
    }
}