package com.example.tiendaapp

import android.content.Context
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
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.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material.icons.outlined.ShoppingCart
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.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
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 androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.android.volley.Request
import com.android.volley.toolbox.JsonArrayRequest
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

// --- MAIN ACTIVITY ---
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MaterialTheme(
                colorScheme = lightColorScheme(
                    primary = Color(0xFF006C4C), // Un verde tipo "Tienda"
                    secondary = Color(0xFF4C6358),
                    tertiary = Color(0xFF3E6373)
                )
            ) {
                TiendaApp()
            }
        }
    }
}

// --- DATA CLASS ---
data class Producto(
    val codigo: String,
    val nombre: String,
    val precio: Double,
    val stock: Int
)

// --- NAVEGACIÓN PRINCIPAL ---
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TiendaApp() {
    val navController = rememberNavController()
    var selectedScreen by remember { mutableStateOf("venta") }

    Scaffold(
        topBar = {
            CenterAlignedTopAppBar(
                title = { Text("Mi Tienda POS", fontWeight = FontWeight.Bold) },
                colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                    titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer
                )
            )
        },
        bottomBar = {
            NavigationBar {
                NavigationBarItem(
                    selected = selectedScreen == "venta",
                    onClick = { selectedScreen = "venta"; navController.navigate("venta") },
                    icon = { Icon(Icons.Outlined.ShoppingCart, contentDescription = null) },
                    label = { Text("Vender") }
                )
                NavigationBarItem(
                    selected = selectedScreen == "inventario",
                    onClick = { selectedScreen = "inventario"; navController.navigate("inventario") },
                    icon = { Icon(Icons.Filled.List, contentDescription = null) },
                    label = { Text("Inventario") }
                )
            }
        }
    ) { padding ->
        NavHost(
            navController = navController,
            startDestination = "venta",
            modifier = Modifier.padding(padding)
        ) {
            composable("venta") { PantallaVenta() }
            composable("inventario") { PantallaInventarioCRUD() }
        }
    }
}

// ==========================================
// PANTALLA 1: VENTA (POS) Y VOUCHER
// ==========================================
@Composable
fun PantallaVenta() {
    val context = LocalContext.current
    var listaProductos by remember { mutableStateOf(listOf<Producto>()) }
    var productoSeleccionado by remember { mutableStateOf<Producto?>(null) }
    var cantidadVenta by remember { mutableStateOf("1") }
    var mostrarDialogoVenta by remember { mutableStateOf(false) }
    var mostrarVoucher by remember { mutableStateOf(false) }
    var ultimoVoucherData by remember { mutableStateOf<VoucherData?>(null) }

    // Cargar productos al iniciar
    LaunchedEffect(Unit) {
        API.listarProductos(context) { listaProductos = it }
    }

    Box(modifier = Modifier.fillMaxSize()) {
        Column(modifier = Modifier.padding(16.dp)) {
            Text("Catálogo de Productos", style = MaterialTheme.typography.titleMedium)
            Spacer(modifier = Modifier.height(8.dp))

            LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                items(listaProductos) { prod ->
                    ProductoVentaCard(prod) {
                        productoSeleccionado = prod
                        mostrarDialogoVenta = true
                    }
                }
            }
        }
    }

    // DIÁLOGO: Confirmar Cantidad
    if (mostrarDialogoVenta && productoSeleccionado != null) {
        AlertDialog(
            onDismissRequest = { mostrarDialogoVenta = false },
            title = { Text("Vender: ${productoSeleccionado!!.nombre}") },
            text = {
                Column {
                    Text("Precio Unitario: S/. ${productoSeleccionado!!.precio}")
                    Text("Stock Disponible: ${productoSeleccionado!!.stock}")
                    Spacer(modifier = Modifier.height(8.dp))
                    OutlinedTextField(
                        value = cantidadVenta,
                        onValueChange = { cantidadVenta = it },
                        label = { Text("Cantidad") },
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                        singleLine = true
                    )
                }
            },
            confirmButton = {
                Button(onClick = {
                    val qty = cantidadVenta.toIntOrNull() ?: 0
                    if (qty > 0 && qty <= productoSeleccionado!!.stock) {
                        val total = qty * productoSeleccionado!!.precio
                        // Procesar venta en BD
                        API.registrarVenta(context, productoSeleccionado!!, qty, total) { exito ->
                            if (exito) {
                                // Preparar Voucher
                                ultimoVoucherData = VoucherData(
                                    producto = productoSeleccionado!!.nombre,
                                    cantidad = qty,
                                    precioUnit = productoSeleccionado!!.precio,
                                    total = total,
                                    fecha = SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.getDefault()).format(Date())
                                )
                                mostrarDialogoVenta = false
                                mostrarVoucher = true
                                // Recargar lista para actualizar stock
                                API.listarProductos(context) { listaProductos = it }
                            } else {
                                Toast.makeText(context, "Error al procesar venta", Toast.LENGTH_SHORT).show()
                            }
                        }
                    } else {
                        Toast.makeText(context, "Cantidad inválida o sin stock", Toast.LENGTH_SHORT).show()
                    }
                }) { Text("COBRAR") }
            },
            dismissButton = {
                TextButton(onClick = { mostrarDialogoVenta = false }) { Text("Cancelar") }
            }
        )
    }

    // DIÁLOGO: VOUCHER (RECIBO)
    if (mostrarVoucher && ultimoVoucherData != null) {
        Dialog(onDismissRequest = { mostrarVoucher = false }) {
            Card(
                colors = CardDefaults.cardColors(containerColor = Color.White),
                elevation = CardDefaults.cardElevation(8.dp),
                modifier = Modifier.fillMaxWidth()
            ) {
                Column(
                    modifier = Modifier.padding(24.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Icon(Icons.Filled.CheckCircle, null, tint = Color(0xFF006C4C), modifier = Modifier.size(50.dp))
                    Text("¡VENTA EXITOSA!", fontWeight = FontWeight.Bold, color = Color(0xFF006C4C))
                    Divider(modifier = Modifier.padding(vertical = 16.dp))

                    Text("TIENDA GRUPO DVH", fontWeight = FontWeight.Black, fontSize = 18.sp)
                    Text("RUC: 20123456789", fontSize = 12.sp, color = Color.Gray)
                    Text(ultimoVoucherData!!.fecha, fontSize = 12.sp, color = Color.Gray)

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

                    Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                        Text("Producto:")
                        Text(ultimoVoucherData!!.producto, fontWeight = FontWeight.Bold)
                    }
                    Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                        Text("Cantidad:")
                        Text("${ultimoVoucherData!!.cantidad}")
                    }
                    Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                        Text("Precio Unit:")
                        Text("S/. ${ultimoVoucherData!!.precioUnit}")
                    }

                    Divider(modifier = Modifier.padding(vertical = 8.dp))

                    Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                        Text("TOTAL:", fontWeight = FontWeight.Black, fontSize = 20.sp)
                        Text("S/. ${String.format("%.2f", ultimoVoucherData!!.total)}", fontWeight = FontWeight.Black, fontSize = 20.sp)
                    }

                    Spacer(modifier = Modifier.height(24.dp))
                    Button(onClick = { mostrarVoucher = false }, modifier = Modifier.fillMaxWidth()) {
                        Text("Cerrar Recibo")
                    }
                }
            }
        }
    }
}

data class VoucherData(val producto: String, val cantidad: Int, val precioUnit: Double, val total: Double, val fecha: String)

@Composable
fun ProductoVentaCard(producto: Producto, onClick: () -> Unit) {
    Card(
        modifier = Modifier.fillMaxWidth().clickable { onClick() },
        elevation = CardDefaults.cardElevation(2.dp),
        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
    ) {
        Row(
            modifier = Modifier.padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Box(
                modifier = Modifier
                    .size(50.dp)
                    .clip(CircleShape)
                    .background(MaterialTheme.colorScheme.primaryContainer),
                contentAlignment = Alignment.Center
            ) {
                Text(producto.nombre.take(1), fontWeight = FontWeight.Bold)
            }
            Spacer(modifier = Modifier.width(16.dp))
            Column(modifier = Modifier.weight(1f)) {
                Text(producto.nombre, fontWeight = FontWeight.Bold, style = MaterialTheme.typography.titleMedium)
                Text("Stock: ${producto.stock} un.", style = MaterialTheme.typography.bodySmall, color = if(producto.stock < 5) Color.Red else Color.Gray)
            }
            Text("S/. ${producto.precio}", fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary)
        }
    }
}

// ==========================================
// PANTALLA 2: INVENTARIO (CRUD)
// ==========================================
@Composable
fun PantallaInventarioCRUD() {
    val context = LocalContext.current
    var codigo by remember { mutableStateOf("") }
    var nombre by remember { mutableStateOf("") }
    var precio by remember { mutableStateOf("") }
    var stock by remember { mutableStateOf("") }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
            .verticalScroll(rememberScrollState()),
        verticalArrangement = Arrangement.spacedBy(10.dp)
    ) {
        Text("Gestión de Inventario", style = MaterialTheme.typography.headlineSmall, color = MaterialTheme.colorScheme.primary)

        Card(modifier = Modifier.fillMaxWidth()) {
            Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                OutlinedTextField(value = codigo, onValueChange = { codigo = it }, label = { Text("Código (Scan/Manual)") }, modifier = Modifier.fillMaxWidth())
                OutlinedTextField(value = nombre, onValueChange = { nombre = it }, label = { Text("Nombre Producto") }, modifier = Modifier.fillMaxWidth())
                Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                    OutlinedTextField(value = precio, onValueChange = { precio = it }, label = { Text("Precio") }, modifier = Modifier.weight(1f), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number))
                    OutlinedTextField(value = stock, onValueChange = { stock = it }, label = { Text("Stock") }, modifier = Modifier.weight(1f), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number))
                }
            }
        }

        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
            Button(
                modifier = Modifier.weight(1f),
                onClick = {
                    API.guardarProducto(context, Producto(codigo, nombre, precio.toDoubleOrNull()?:0.0, stock.toIntOrNull()?:0)) {
                        Toast.makeText(context, if(it) "Guardado" else "Error", Toast.LENGTH_SHORT).show()
                    }
                }
            ) { Text("Guardar") }

            Button(
                modifier = Modifier.weight(1f),
                onClick = {
                    API.modificarProducto(context, Producto(codigo, nombre, precio.toDoubleOrNull()?:0.0, stock.toIntOrNull()?:0)) {
                        Toast.makeText(context, if(it) "Editado" else "Error", Toast.LENGTH_SHORT).show()
                    }
                },
                colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.secondary)
            ) { Text("Editar") }
        }

        Button(
            modifier = Modifier.fillMaxWidth(),
            onClick = {
                API.borrarProducto(context, codigo) {
                    Toast.makeText(context, if(it) "Eliminado" else "Error", Toast.LENGTH_SHORT).show()
                    // Limpiar campos
                    codigo = ""; nombre = ""; precio = ""; stock = ""
                }
            },
            colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error)
        ) { Text("Eliminar Producto") }
    }
}

// ==========================================
// OBJETO API (CONEXIONES VOLLEY)
// ==========================================
object API {
    private const val BASE_URL = "https://emerson.grupodvh.com/api_tienda/tienda/"

    fun listarProductos(context: Context, callback: (List<Producto>) -> Unit) {
        val url = "${BASE_URL}listar_productos.php"
        val request = JsonArrayRequest(Request.Method.GET, url, null,
            { response ->
                val lista = mutableListOf<Producto>()
                try {
                    for (i in 0 until response.length()) {
                        val obj = response.getJSONObject(i)
                        lista.add(Producto(
                            obj.getString("codigo"),
                            obj.getString("nombre"),
                            obj.getString("precio").toDouble(),
                            obj.getString("stock").toInt()
                        ))
                    }
                    callback(lista)
                } catch (e: Exception) { callback(emptyList()) }
            },
            { callback(emptyList()) }
        )
        Volley.newRequestQueue(context).add(request)
    }

    fun guardarProducto(context: Context, p: Producto, callback: (Boolean) -> Unit) {
        enviarRequest(context, "guardar_producto.php", p, callback)
    }

    fun modificarProducto(context: Context, p: Producto, callback: (Boolean) -> Unit) {
        enviarRequest(context, "modificar_producto.php", p, callback)
    }

    fun borrarProducto(context: Context, codigo: String, callback: (Boolean) -> Unit) {
        val params = JSONObject().apply { put("codigo", codigo) }
        val request = JsonObjectRequest(Request.Method.POST, "${BASE_URL}borrar_producto.php", params,
            { res -> callback(res.optString("resultado") == "1") },
            { callback(false) }
        )
        Volley.newRequestQueue(context).add(request)
    }

    fun registrarVenta(context: Context, p: Producto, cantidad: Int, total: Double, callback: (Boolean) -> Unit) {
        val params = JSONObject().apply {
            put("codigo", p.codigo)
            put("nombre", p.nombre)
            put("cantidad", cantidad)
            put("total", total)
        }
        val request = JsonObjectRequest(Request.Method.POST, "${BASE_URL}registrar_venta.php", params,
            { res -> callback(res.optString("resultado") == "1") },
            { callback(false) }
        )
        Volley.newRequestQueue(context).add(request)
    }

    private fun enviarRequest(context: Context, endpoint: String, p: Producto, callback: (Boolean) -> Unit) {
        val params = JSONObject().apply {
            put("codigo", p.codigo)
            put("nombre", p.nombre)
            put("precio", p.precio)
            put("stock", p.stock)
        }
        val request = JsonObjectRequest(Request.Method.POST, "${BASE_URL}$endpoint", params,
            { res -> callback(res.optString("resultado") == "1") },
            { callback(false) }
        )
        Volley.newRequestQueue(context).add(request)
    }
}