package com.example.barokahstore.ui.screens

import androidx.compose.foundation.border
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.DateRange
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.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.barokahstore.data.BestSellerProduct
import com.example.barokahstore.data.DatabaseHelper
import com.example.barokahstore.data.SalesReport
import com.example.barokahstore.data.User
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

@OptIn(ExperimentalLayoutApi::class)
@Composable
fun LaporanScreen(
    dbHelper: DatabaseHelper,
    currentUser: User
) {
    val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
    val todayStr = sdf.format(Date())
    
    // Default start date = 7 days ago
    val initStart = remember {
        val cal = Calendar.getInstance()
        cal.add(Calendar.DAY_OF_YEAR, -7)
        sdf.format(cal.time)
    }

    var startDate by remember { mutableStateOf(initStart) }
    var endDate by remember { mutableStateOf(todayStr) }

    var salesReportsList by remember { mutableStateOf(listOf<SalesReport>()) }
    var bestSellersList by remember { mutableStateOf(listOf<BestSellerProduct>()) }

    var totalRevenue by remember { mutableStateOf(0.0) }
    var totalCost by remember { mutableStateOf(0.0) }
    var totalProfit by remember { mutableStateOf(0.0) }

    fun loadReports() {
        val reports = dbHelper.getSalesReport(startDate, endDate)
        salesReportsList = reports
        bestSellersList = dbHelper.getBestSellers(startDate, endDate)

        totalRevenue = reports.sumOf { it.revenue }
        totalCost = reports.sumOf { it.cost }
        totalProfit = totalRevenue - totalCost
    }

    LaunchedEffect(startDate, endDate) {
        loadReports()
    }

    LazyColumn(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        // Date Pickers Row
        item {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(12.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                OutlinedTextField(
                    value = startDate,
                    onValueChange = { startDate = it },
                    label = { Text("Mulai (YYYY-MM-DD)") },
                    singleLine = true,
                    shape = RoundedCornerShape(10.dp),
                    modifier = Modifier.weight(1f)
                )

                OutlinedTextField(
                    value = endDate,
                    onValueChange = { endDate = it },
                    label = { Text("Sampai (YYYY-MM-DD)") },
                    singleLine = true,
                    shape = RoundedCornerShape(10.dp),
                    modifier = Modifier.weight(1f)
                )
            }
        }

        // Stats Cards Grid
        item {
            FlowRow(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(12.dp),
                verticalArrangement = Arrangement.spacedBy(12.dp),
                maxItemsInEachRow = 2
            ) {
                val cardWidthModifier = Modifier.weight(1f).minWidth(150.dp)
                
                // Total Pendapatan / Omset
                StatCard(
                    title = "Total Omset",
                    value = formatRupiah(totalRevenue),
                    icon = Icons.Default.DateRange,
                    backgroundColor = Color(0xFFE0E7FF),
                    iconColor = Color(0xFF4F46E5),
                    modifier = cardWidthModifier
                )

                // Total Modal / Cost
                StatCard(
                    title = "Total Modal",
                    value = formatRupiah(totalCost),
                    icon = Icons.Default.DateRange,
                    backgroundColor = Color(0xFFFEE2E2),
                    iconColor = Color(0xFFEF4444),
                    modifier = cardWidthModifier
                )

                // Total Laba Bersih
                StatCard(
                    title = "Laba Bersih",
                    value = formatRupiah(totalProfit),
                    icon = Icons.Default.DateRange,
                    backgroundColor = Color(0xFFD1FAE5),
                    iconColor = Color(0xFF059669),
                    modifier = cardWidthModifier
                )

                // Margin Laba %
                val margin = if (totalRevenue > 0) (totalProfit / totalRevenue * 100) else 0.0
                StatCard(
                    title = "Margin Laba",
                    value = String.format(Locale.getDefault(), "%.1f%%", margin),
                    icon = Icons.Default.DateRange,
                    backgroundColor = Color(0xFFFEF3C7),
                    iconColor = Color(0xFFD97706),
                    modifier = cardWidthModifier
                )
            }
        }

        // Best Sellers List
        item {
            Card(
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(16.dp),
                colors = CardDefaults.cardColors(containerColor = Color.White),
                elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
            ) {
                Column(modifier = Modifier.padding(16.dp)) {
                    Text(
                        text = "Produk Terlaris",
                        fontSize = 15.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFF1F2937)
                    )
                    Spacer(modifier = Modifier.height(12.dp))

                    if (bestSellersList.isEmpty()) {
                        Text(
                            text = "Belum ada data penjualan.",
                            fontSize = 13.sp,
                            color = Color.Gray,
                            modifier = Modifier.fillMaxWidth().padding(vertical = 12.dp),
                            textAlign = TextAlign.Center
                        )
                    } else {
                        bestSellersList.forEach { product ->
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(vertical = 6.dp),
                                horizontalArrangement = Arrangement.SpaceBetween,
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Column {
                                    Text(product.productName, fontSize = 13.sp, fontWeight = FontWeight.Bold)
                                    Text("Terjual: ${product.totalQty}", fontSize = 11.sp, color = Color.Gray)
                                }
                                Text(formatRupiah(product.revenue), fontSize = 13.sp, fontWeight = FontWeight.Bold, color = Color(0xFF4F46E5))
                            }
                            Divider(color = Color(0xFFF3F4F6))
                        }
                    }
                }
            }
        }

        // Daily Reports Breakdown
        item {
            Card(
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(16.dp),
                colors = CardDefaults.cardColors(containerColor = Color.White),
                elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
            ) {
                Column(modifier = Modifier.padding(16.dp)) {
                    Text(
                        text = "Laporan Harian",
                        fontSize = 15.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFF1F2937)
                    )
                    Spacer(modifier = Modifier.height(12.dp))

                    if (salesReportsList.isEmpty()) {
                        Text(
                            text = "Tidak ada transaksi dalam rentang tanggal.",
                            fontSize = 13.sp,
                            color = Color.Gray,
                            modifier = Modifier.fillMaxWidth().padding(vertical = 12.dp),
                            textAlign = TextAlign.Center
                        )
                    } else {
                        salesReportsList.forEach { report ->
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(vertical = 8.dp)
                                    .border(0.5.dp, Color(0xFFE5E7EB), RoundedCornerShape(8.dp))
                                    .padding(10.dp),
                                horizontalArrangement = Arrangement.SpaceBetween,
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Column {
                                    Text(report.date, fontSize = 13.sp, fontWeight = FontWeight.Bold)
                                    Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                                        Text("Omset: ${formatRupiah(report.revenue)}", fontSize = 11.sp, color = Color.Gray)
                                        Text("Laba: ${formatRupiah(report.profit)}", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color(0xFF059669))
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
