package com.example.barokahstore.ui.screens

import android.app.DatePickerDialog
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
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.Close
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Search
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.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import com.example.barokahstore.data.DatabaseHelper
import com.example.barokahstore.data.Transaction
import com.example.barokahstore.data.TransactionDetail
import com.example.barokahstore.data.User
import java.util.Calendar

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HistoryScreen(
    dbHelper: DatabaseHelper,
    currentUser: User
) {
    val isAdmin = currentUser.role == "admin"
    var invoiceQuery by remember { mutableStateOf("") }
    var dateQuery by remember { mutableStateOf("") } // Date formatted YYYY-MM-DD
    var transactionsList by remember { mutableStateOf(listOf<Transaction>()) }

    val context = LocalContext.current
    val calendar = Calendar.getInstance()
    val datePickerDialog = remember {
        DatePickerDialog(
            context,
            { _, selectedYear, selectedMonth, selectedDayOfMonth ->
                val formattedMonth = (selectedMonth + 1).toString().padStart(2, '0')
                val formattedDay = selectedDayOfMonth.toString().padStart(2, '0')
                dateQuery = "$selectedYear-$formattedMonth-$formattedDay"
            },
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        )
    }

    // Dialog details states
    var showDetailsDialog by remember { mutableStateOf(false) }
    var selectedTransaction by remember { mutableStateOf<Transaction?>(null) }
    var selectedDetailsList by remember { mutableStateOf(listOf<TransactionDetail>()) }

    // Delete confirm dialog states
    var showDeleteConfirmDialog by remember { mutableStateOf(false) }
    var transactionToDelete by remember { mutableStateOf<Transaction?>(null) }

    fun refreshHistory() {
        transactionsList = dbHelper.getAllTransactions(
            invoiceQuery = invoiceQuery.trim().ifEmpty { null },
            dateQuery = dateQuery.trim().ifEmpty { null }
        )
    }

    LaunchedEffect(invoiceQuery, dateQuery) {
        refreshHistory()
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        // Search Inputs row
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            OutlinedTextField(
                value = invoiceQuery,
                onValueChange = { invoiceQuery = it },
                placeholder = { Text("Invoice...") },
                leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) },
                singleLine = true,
                shape = RoundedCornerShape(12.dp),
                modifier = Modifier.weight(1.2f)
            )

            OutlinedTextField(
                value = dateQuery,
                onValueChange = { },
                placeholder = { Text("Pilih Tanggal") },
                singleLine = true,
                readOnly = true,
                shape = RoundedCornerShape(12.dp),
                modifier = Modifier
                    .weight(0.8f)
                    .clickable { datePickerDialog.show() },
                trailingIcon = {
                    if (dateQuery.isNotEmpty()) {
                        IconButton(onClick = { dateQuery = "" }) {
                            Icon(Icons.Default.Close, contentDescription = "Hapus Filter")
                        }
                    } else {
                        IconButton(onClick = { datePickerDialog.show() }) {
                            Icon(Icons.Default.DateRange, contentDescription = "Pilih Tanggal")
                        }
                    }
                }
            )
        }

        // List
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f),
            shape = RoundedCornerShape(16.dp),
            colors = CardDefaults.cardColors(containerColor = Color.White),
            elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
        ) {
            if (transactionsList.isEmpty()) {
                Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                    Text("Transaksi tidak ditemukan", color = Color.Gray, fontSize = 14.sp)
                }
            } else {
                LazyColumn(modifier = Modifier.padding(16.dp)) {
                    items(transactionsList) { tx ->
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 8.dp)
                                .border(0.5.dp, Color(0xFFE5E7EB), RoundedCornerShape(10.dp))
                                .padding(12.dp),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Column(modifier = Modifier.weight(1f)) {
                                Text(tx.invoiceNo, fontWeight = FontWeight.Bold, fontSize = 14.sp)
                                Text("Waktu: ${tx.createdAt} • Kasir: ${tx.cashierName}", fontSize = 11.sp, color = Color.Gray)
                                Row(
                                    modifier = Modifier.padding(top = 4.dp),
                                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                                ) {
                                    Text("Tipe: ${tx.paymentType.uppercase()}", fontSize = 11.sp, color = Color.Gray)
                                    Text("Status: ${tx.status.uppercase()}", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = if (tx.status == "paid") Color(0xFF059669) else Color(0xFFDC2626))
                                }
                            }
                            
                            Column(horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(8.dp)) {
                                Text(formatRupiah(tx.grandTotal), fontWeight = FontWeight.ExtraBold, fontSize = 14.sp, color = Color(0xFF1F2937))
                                
                                Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                                    IconButton(
                                        onClick = {
                                            selectedTransaction = tx
                                            selectedDetailsList = dbHelper.getTransactionDetails(tx.id)
                                            showDetailsDialog = true
                                        },
                                        modifier = Modifier.size(24.dp)
                                    ) {
                                        Icon(Icons.Default.Info, contentDescription = "Detail", tint = Color(0xFF4F46E5))
                                    }
                                    
                                    if (isAdmin) {
                                        IconButton(
                                            onClick = {
                                                transactionToDelete = tx
                                                showDeleteConfirmDialog = true
                                            },
                                            modifier = Modifier.size(24.dp)
                                        ) {
                                            Icon(Icons.Default.Delete, contentDescription = "Hapus", tint = Color(0xFFEF4444))
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // --- TRANSACTION DETAIL DIALOG ---
    if (showDetailsDialog && selectedTransaction != null) {
        Dialog(onDismissRequest = { showDetailsDialog = false }) {
            Card(
                shape = RoundedCornerShape(16.dp),
                colors = CardDefaults.cardColors(containerColor = Color.White),
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
            ) {
                Column(
                    modifier = Modifier.padding(24.dp),
                    verticalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    Text(
                        text = "Detail Transaksi",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFF1F2937),
                        modifier = Modifier.fillMaxWidth(),
                        textAlign = TextAlign.Center
                    )

                    Divider()

                    // Invoice meta details
                    Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
                        Text("Invoice: ${selectedTransaction!!.invoiceNo}", fontSize = 13.sp, fontWeight = FontWeight.Bold)
                        Text("Tanggal: ${selectedTransaction!!.createdAt}", fontSize = 12.sp, color = Color.Gray)
                        Text("Kasir: ${selectedTransaction!!.cashierName}", fontSize = 12.sp, color = Color.Gray)
                        Text("Tipe Pembayaran: ${selectedTransaction!!.paymentType.uppercase()}", fontSize = 12.sp, color = Color.Gray)
                        if (selectedTransaction!!.customerName != null) {
                            Text("Pelanggan: ${selectedTransaction!!.customerName}", fontSize = 12.sp, color = Color.Gray)
                        }
                    }

                    Divider()

                    // Items list
                    Text("Daftar Item:", fontSize = 13.sp, fontWeight = FontWeight.Bold)
                    LazyColumn(
                        modifier = Modifier.heightIn(max = 200.dp),
                        verticalArrangement = Arrangement.spacedBy(6.dp)
                    ) {
                        items(selectedDetailsList) { detail ->
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.SpaceBetween
                            ) {
                                Text(
                                    text = "${detail.productName} (x${detail.qty})",
                                    fontSize = 12.sp,
                                    modifier = Modifier.weight(1f)
                                )
                                Text(
                                    text = formatRupiah(detail.subtotal),
                                    fontSize = 12.sp,
                                    fontWeight = FontWeight.Bold
                                )
                            }
                        }
                    }

                    Divider()

                    // Summary cost math
                    Column(
                        verticalArrangement = Arrangement.spacedBy(4.dp),
                        horizontalAlignment = Alignment.End,
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                            Text("Subtotal:", fontSize = 12.sp, color = Color.Gray)
                            Text(formatRupiah(selectedTransaction!!.totalAmount), fontSize = 12.sp)
                        }
                        if (selectedTransaction!!.discount > 0) {
                            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                                Text("Diskon:", fontSize = 12.sp, color = Color.Gray)
                                Text("-${formatRupiah(selectedTransaction!!.discount)}", fontSize = 12.sp)
                            }
                        }
                        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                            Text("Total:", fontSize = 13.sp, fontWeight = FontWeight.Bold)
                            Text(formatRupiah(selectedTransaction!!.grandTotal), fontSize = 14.sp, fontWeight = FontWeight.ExtraBold, color = Color(0xFF4F46E5))
                        }
                    }

                    Button(
                        onClick = { showDetailsDialog = false },
                        colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF4F46E5)),
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        Text("Tutup")
                    }
                }
            }
        }
    }

    // --- DELETE TRANSACTION CONFIRM DIALOG ---
    if (showDeleteConfirmDialog && transactionToDelete != null) {
        AlertDialog(
            onDismissRequest = { showDeleteConfirmDialog = false },
            title = { Text("Hapus Transaksi") },
            text = { Text("Apakah Anda yakin ingin menghapus transaksi '${transactionToDelete!!.invoiceNo}'? Tindakan ini akan mengembalikan stok produk yang dibeli.") },
            confirmButton = {
                Button(
                    onClick = {
                        dbHelper.deleteTransaction(transactionToDelete!!.id)
                        refreshHistory()
                        showDeleteConfirmDialog = false
                    },
                    colors = ButtonDefaults.buttonColors(containerColor = Color.Red)
                ) {
                    Text("Hapus", color = Color.White)
                }
            },
            dismissButton = {
                TextButton(onClick = { showDeleteConfirmDialog = false }) {
                    Text("Batal")
                }
            }
        )
    }
}
