import 'package:intl/intl.dart';
import 'package:flutter/material.dart';
import '../../models/models.dart';
import '../../themes/themes.dart';
import '../pedido/pedido_ticket.dart';

class PedidoDetalleScreen extends StatelessWidget {
  final Pedido pedido;

  const PedidoDetalleScreen({Key? key, required this.pedido}) : super(key: key);

  String formatCurrency(double amount) {
    final format = NumberFormat("#,##0.00", "es_MX");
    return format.format(amount);
  }

  @override
  Widget build(BuildContext context) {
    double totalSinDescuento =
        pedido.productos.fold(0, (previousValue, element) {
      double productTotal = element.cantidad! *
          (double.tryParse(element.producto?.precio ?? '') ?? 0.0);

      double toppingsTotal = element.toppings.fold(0, (toppingTotal, topping) {
        return toppingTotal +
            (double.tryParse(topping.topping?.precio ?? '') ?? 0.0) *
                element.cantidad!;
      });

      return previousValue + productTotal + toppingsTotal;
    });

    double descuento = pedido.descuento?.toDouble() ?? 0.0;
    double precioDescuento = totalSinDescuento * (descuento / 100);
    double totalConDescuento = totalSinDescuento - precioDescuento;

    return Scaffold(
      appBar: AppBar(
        title: Text(
          'Detalle del Pedido ${pedido.folio}',
          style: TextStyle(fontWeight: FontWeight.w500),
        ),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(12.0),
        child: Column(
          children: [
            Card(
              elevation: 4,
              color: Colors.white,
              child: Column(
                children: [
                  ListTile(
                    title: Text(
                      'Cliente: ${pedido.nombreCliente}',
                      style:
                          TextStyle(fontWeight: FontWeight.bold, fontSize: 22),
                    ),
                    subtitle: Text(
                      'Comentarios: ${pedido.comentarios}',
                      style:
                          TextStyle(fontSize: 20, fontWeight: FontWeight.w500),
                    ),
                  ),
                  ListTile(
                    title: Text(
                      'Estado del Pedido: ${pedido.estatus}',
                      style: TextStyle(
                        fontSize: 22,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  )
                ],
              ),
            ),
            SizedBox(height: 10),
            Card(
              elevation: 4,
              color: Colors.white,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('Productos',
                        style: TextStyle(
                            fontSize: 22, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 15),
                    ListView.builder(
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                      itemCount: pedido.productos.length,
                      itemBuilder: (context, index) {
                        final producto = pedido.productos[index];
                        return Padding(
                          padding: const EdgeInsets.symmetric(vertical: 4.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  Expanded(
                                    flex: 6,
                                    child: Text(
                                      producto.producto?.nombre ??
                                          "Producto no especificado",
                                      style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          fontSize: 17),
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ),
                                  Expanded(
                                    flex: 1,
                                    child: Text(
                                      'x${producto.cantidad}',
                                      style: TextStyle(
                                          fontWeight: FontWeight.w500,
                                          fontSize: 17),
                                      textAlign: TextAlign.center,
                                    ),
                                  ),
                                  Expanded(
                                    flex: 2,
                                    child: Text(
                                      '\$${formatCurrency(double.tryParse(producto.producto?.precio ?? '0.0') ?? 0.0)}',
                                      style: TextStyle(
                                          fontWeight: FontWeight.w500,
                                          fontSize: 17),
                                      textAlign: TextAlign.right,
                                    ),
                                  ),
                                ],
                              ),
                              if (producto.toppings.isNotEmpty)
                                Padding(
                                  padding: const EdgeInsets.only(top: 4.0),
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: producto.toppings.map((topping) {
                                      return Padding(
                                        padding: const EdgeInsets.symmetric(
                                            vertical: 2.0),
                                        child: Row(
                                          children: [
                                            Text(
                                              '- ${topping.topping?.nombre ?? "Topping no especificado"}',
                                              style: TextStyle(
                                                  fontSize: 15,
                                                  color: Colors.grey[600]),
                                            ),
                                            Spacer(),
                                            Text(
                                              '\$${formatCurrency(double.tryParse(topping.topping?.precio ?? '0.0') ?? 0.0)}',
                                              style: TextStyle(
                                                  fontSize: 15,
                                                  color: Colors.grey[600]),
                                            ),
                                          ],
                                        ),
                                      );
                                    }).toList(),
                                  ),
                                ),
                            ],
                          ),
                        );
                      },
                    ),
                    Divider(),
                    Padding(
                      padding: const EdgeInsets.symmetric(vertical: 8.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              const Text('Subtotal:',
                                  style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.bold)),
                              const SizedBox(width: 5),
                              Text('\$${formatCurrency(totalSinDescuento)}',
                                  style: const TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.bold)),
                            ],
                          ),
                          if (descuento > 0) ...[
                            Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                Text(
                                    'Descuento (${descuento.toStringAsFixed(0)}%):',
                                    style: const TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.bold)),
                                const SizedBox(width: 8),
                                Text('-\$${formatCurrency(precioDescuento)}',
                                    style: const TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.bold)),
                              ],
                            ),
                          ],
                          Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              const Text('Total:',
                                  style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.bold)),
                              const SizedBox(width: 5),
                              Text('\$${formatCurrency(totalConDescuento)}',
                                  style: const TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.bold)),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 10),
            Card(
              elevation: 4,
              color: Colors.white,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('Pago',
                        style: TextStyle(
                            fontSize: 22, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 10),
                    _buildPaymentDetails(),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 20),
            Align(
              alignment: Alignment.centerLeft,
              child: ElevatedButton.icon(
                icon: Icon(
                  Icons.receipt_long_outlined,
                  color: AppTheme.quaternary,
                  size: 30,
                ),
                onPressed: () => imprimirTicketsJuntos(context, pedido),
                label: Text(
                  'Imprimir Ticket',
                  style: TextStyle(
                      fontWeight: FontWeight.w500,
                      fontSize: 18,
                      color: AppTheme.quaternary),
                ),
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.fromLTRB(50, 20, 50, 20),
                  primary: AppTheme.tertiary,
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _buildPaymentDetails() {
    List<Widget> paymentDetails = [];

    if (pedido.cantEfectivo != null && pedido.cantEfectivo! > 0) {
      paymentDetails.add(_buildPaymentRow("Efectivo", pedido.cantEfectivo!));
    }
    if (pedido.cantTarjeta != null && pedido.cantTarjeta! > 0) {
      paymentDetails.add(_buildPaymentRow("Tarjeta", pedido.cantTarjeta!));
    }
    if (pedido.cantTransferencia != null && pedido.cantTransferencia! > 0) {
      paymentDetails
          .add(_buildPaymentRow("Transferencia", pedido.cantTransferencia!));
    }
    if (paymentDetails.isEmpty) {
      paymentDetails.add(Text("No se especificaron métodos de pago.",
          style: TextStyle(fontSize: 16, color: Colors.grey[600])));
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: paymentDetails,
    );
  }

  Widget _buildPaymentRow(String paymentType, double amount) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          paymentType,
          style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
        ),
        Text(
          '\$${formatCurrency(amount)}',
          style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
        ),
      ],
    );
  }
}
