import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../../models/models.dart';
import '../../themes/themes.dart';
import 'package:intl/intl.dart';
import '../../models/corte_caja_model.dart';
import '../../viewmodels/corte_caja_view_model.dart';
import '../../viewmodels/viewmodels.dart';
import '../../widgets/app_textfield.dart';
import '../../widgets/widgets.dart';
import 'dart:async';

import '../pedido/pedido_screen.dart';

class CorteCajaForm extends StatefulWidget {
  final String? corteCajaId;

  const CorteCajaForm({this.corteCajaId, Key? key}) : super(key: key);

  @override
  _CorteCajaFormState createState() => _CorteCajaFormState();
}

class _CorteCajaFormState extends State<CorteCajaForm> {
  final TextEditingController _montoDepositoController =
      TextEditingController();
  final TextEditingController _descripcionDepositoController =
      TextEditingController();
  final TextEditingController _personaDepositoController =
      TextEditingController();
  final TextEditingController _montoRetiroController = TextEditingController();
  final TextEditingController _descripcionRetiroController =
      TextEditingController();
  final TextEditingController _personaRetiroController =
      TextEditingController();
  final TextEditingController _montoGastoController = TextEditingController();
  final TextEditingController _descripcionGastoController =
      TextEditingController();
  final TextEditingController _personaGastoController = TextEditingController();
  late double fondoInicial;
  Timer? _validationTimer;
  bool isFondoValid = true;
  DateTime? fechaApertura;
  bool isFirst = true;
  List<Pedido> _pedidosCancelados = [];

  String formatNumber(double? value) {
    final formatter = NumberFormat('#,##0.00', 'en_US');
    return formatter.format(value);
  }

  @override
  void initState() {
    super.initState();
    final viewModel = Provider.of<CorteCajaViewModel>(context, listen: false);

    if (widget.corteCajaId != null) {
      viewModel.fetchDepositosAndRetiros(widget.corteCajaId!).then((_) {
        setState(() {
          final corte = viewModel.cortes.firstWhere(
            (corte) => corte.id == widget.corteCajaId,
            orElse: () => CorteCaja(
                id: widget.corteCajaId, fechaApertura: DateTime.now()),
          );
          viewModel.selectCorte(corte);
          fechaApertura = viewModel.selectedCorte?.fechaApertura;

          fondoInicial = viewModel.selectedCorte?.fondo ?? 0.0;

          viewModel.fondoController.text =
              viewModel.selectedCorte?.fondo != null
                  ? formatNumber(viewModel.selectedCorte!.fondo!)
                  : '';

          viewModel.fondoDiaSigController.text =
              viewModel.selectedCorte?.fondoDiaSig != null
                  ? formatNumber(viewModel.selectedCorte!.fondoDiaSig!)
                  : '';

          viewModel.cargarVentasPorCorteId(corte.id!).then((_) {
            viewModel.calcularCorteFinal();
          });
          viewModel.fetchPedidosCancelados(widget.corteCajaId!).then((pedidos) {
            setState(() {
              _pedidosCancelados = pedidos;
            });
          });
        });
      });

      viewModel.fetchPedidosConPropinas(widget.corteCajaId!).then((_) {
        setState(() {});
      });
    }
  }

  void _validateFondo(CorteCajaViewModel viewModel) {
    if (_validationTimer != null) {
      _validationTimer!.cancel();
    }

    _validationTimer = Timer(Duration(seconds: 2), () {
      final fondoActual = double.tryParse(
            viewModel.fondoController.text.replaceAll(',', ''),
          ) ??
          0.0;

      if (fondoActual < fondoInicial) {
        setState(() {
          isFondoValid = false;
        });

        alerta(context,
            etiqueta: "El fondo no puede ser menor al que ya se tenía.");
        viewModel.fondoController.text = formatNumber(fondoInicial);
      } else {
        setState(() {
          isFondoValid = true;
        });
      }
    });
  }

  void _mostrarDialogoPedidosNuevos(
    BuildContext context,
    List<Pedido> pedidos, {
    required Function(List<Pedido>) onAbrirNuevaCaja,
  }) {
    showDialog(
      context: context,
      builder: (ctx) {
        return AlertDialog(
          title: Text(
            'Atención: Aún cuentas con pedidos sin terminar.',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          content: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '¿Deseas terminar los pedidos o abrir una nueva caja con ellos?',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
                ),
                SizedBox(height: 10),
                Text(
                  'Pedidos pendientes:',
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
                ),
                SizedBox(height: 5),
                Column(
                  children: pedidos.map((p) {
                    return Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          'Folio: ${p.folio}',
                          style: TextStyle(
                              fontSize: 16, fontWeight: FontWeight.w600),
                        ),
                        Text(
                          '\$${p.totalPedido?.toStringAsFixed(2) ?? '0.00'}',
                          style: TextStyle(
                              fontSize: 16, fontWeight: FontWeight.w600),
                        ),
                      ],
                    );
                  }).toList(),
                ),
              ],
            ),
          ),
          actions: [
            TextButton(
              style: ButtonStyle(
                backgroundColor: MaterialStatePropertyAll(AppTheme.rojo),
                foregroundColor: MaterialStatePropertyAll(AppTheme.quaternary),
              ),
              child: Text(
                'Terminar mis pedidos primero',
                style: TextStyle(fontSize: 16),
              ),
              onPressed: () {
                Navigator.of(ctx).pop();
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => PedidoScreen(),
                  ),
                );
              },
            ),
            TextButton(
              style: ButtonStyle(
                  backgroundColor: MaterialStatePropertyAll(AppTheme.verde),
                  foregroundColor:
                      MaterialStatePropertyAll(AppTheme.quaternary)),
              child: Text(
                'Abrir una caja nueva con esos pedidos',
                style: TextStyle(fontSize: 16),
              ),
              onPressed: () {
                Navigator.of(ctx).pop();
                onAbrirNuevaCaja(pedidos);
              },
            ),
          ],
        );
      },
    );
  }

  void _mostrarDialogoDespuesDe6pm(
    BuildContext context,
    List<Pedido> pedidos,
  ) {
    showDialog(
      context: context,
      builder: (ctx) {
        return AlertDialog(
          title: Text(
            'Pedidos sin terminar',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          content: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'Debes terminar estos pedidos para poder realizar el corte:',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
                ),
                SizedBox(height: 10),
                Column(
                  children: pedidos.map((p) {
                    return Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          'Folio: ${p.folio}',
                          style: TextStyle(
                              fontSize: 16, fontWeight: FontWeight.w600),
                        ),
                        Text(
                          '\$${p.totalPedido?.toStringAsFixed(2) ?? '0.00'}',
                          style: TextStyle(
                              fontSize: 16, fontWeight: FontWeight.w600),
                        ),
                      ],
                    );
                  }).toList(),
                ),
              ],
            ),
          ),
          actions: [
            TextButton(
              style: ButtonStyle(
                backgroundColor: MaterialStatePropertyAll(AppTheme.rojo),
                foregroundColor: MaterialStatePropertyAll(AppTheme.quaternary),
              ),
              child: Text(
                'Terminar mis pedidos',
                style: TextStyle(fontSize: 16),
              ),
              onPressed: () {
                Navigator.of(ctx).pop();
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => PedidoScreen(),
                  ),
                );
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final viewModel = Provider.of<CorteCajaViewModel>(context);

    return Scaffold(
        appBar: AppBar(
          title: Text(
            'Caja',
            style: TextStyle(
                color: AppTheme.secondary, fontWeight: FontWeight.w500),
          ),
          iconTheme: IconThemeData(color: AppTheme.secondary),
        ),
        body: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    fechaApertura == null
                        ? Text(
                            "Fecha: ${DateFormat('dd/MM/yyyy').format(DateTime.now())}",
                            style: TextStyle(
                                fontSize: 20, fontWeight: FontWeight.bold),
                          )
                        : Text(
                            "Fecha: ${DateFormat('dd/MM/yyyy').format(fechaApertura!)}",
                            style: TextStyle(
                                fontSize: 20, fontWeight: FontWeight.bold),
                          ),
                    Container(
                      padding:
                          EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                      decoration: BoxDecoration(
                        color: viewModel.isCorteAbierto()
                            ? AppTheme.verde
                            : AppTheme.rojo,
                        borderRadius: BorderRadius.circular(20),
                      ),
                      child: Row(
                        children: [
                          Icon(
                            Icons.circle,
                            color: Colors.white,
                            size: 12,
                          ),
                          SizedBox(width: 8),
                          Text(
                            viewModel.isCorteAbierto() ? 'ABIERTA' : 'CERRADA',
                            style: TextStyle(
                                color: Colors.white,
                                fontWeight: FontWeight.bold),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 20),
                Row(
                  children: [
                    Expanded(
                      child: AppTextField(
                        etiqueta: "Fondo",
                        prefixIcon: const Icon(Icons.attach_money_sharp),
                        controller: viewModel.fondoController,
                        keyboardType: TextInputType.number,
                        separarMiles: true,
                        onChanged: (value) {
                          _validateFondo(viewModel);
                          viewModel.calcularCorteFinal();
                        },
                      ),
                    ),
                    SizedBox(width: 20),
                    Expanded(
                      child: AppTextField(
                        etiqueta: "Fondo Día Siguiente",
                        prefixIcon: const Icon(Icons.attach_money_sharp),
                        controller: viewModel.fondoDiaSigController,
                        keyboardType: TextInputType.number,
                        separarMiles: true,
                        onChanged: (value) {
                          viewModel.calcularCorteFinal();
                        },
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 10),
                if (!isFondoValid)
                  Text(
                    "El fondo no puede ser menor a $fondoInicial",
                    style: TextStyle(
                        color: Colors.red,
                        fontSize: 16,
                        fontWeight: FontWeight.bold),
                  ),
                SizedBox(height: 10),
                Row(
                  children: [
                    Expanded(
                      child: AppTextField(
                        etiqueta: "Ventas Efectivo",
                        prefixIcon: const Icon(Icons.attach_money_sharp),
                        controller: viewModel.ventaEfeController,
                        readOnly: true,
                        onChanged: viewModel.actualizarVentaEfectivo,
                      ),
                    ),
                    SizedBox(width: 20),
                    Expanded(
                      child: AppTextField(
                        etiqueta: "Ventas Tarjeta",
                        prefixIcon: const Icon(Icons.attach_money_sharp),
                        controller: viewModel.ventaTarjController,
                        readOnly: true,
                        onChanged: viewModel.actualizarVentaTarjeta,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 10),
                Row(
                  children: [
                    Expanded(
                      child: AppTextField(
                        etiqueta: "Ventas Transferencia",
                        prefixIcon: const Icon(Icons.attach_money_sharp),
                        controller: viewModel.ventaTransfController,
                        readOnly: true,
                        onChanged: viewModel.actualizarVentaTransferencia,
                      ),
                    ),
                    SizedBox(width: 20),
                    Expanded(
                      child: AppTextField(
                        etiqueta: "Total Ventas",
                        prefixIcon: const Icon(Icons.attach_money_sharp),
                        controller: viewModel.totalVentaController,
                        readOnly: true,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 20),
                ExpansionTile(
                  backgroundColor: Colors.white,
                  collapsedBackgroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                    side: BorderSide(color: Colors.grey),
                  ),
                  collapsedShape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                    side: BorderSide(color: Colors.grey),
                  ),
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        "Depósitos",
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 18),
                      ),
                      Row(
                        children: [
                          Text(
                            "Total: \$${formatNumber(viewModel.totalDepositos)}",
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ),
                          const SizedBox(
                            width: 20,
                          ),
                          ElevatedButton.icon(
                            icon: Icon(Icons.add, color: Colors.white),
                            label: Text(
                              "Agregar",
                              style: TextStyle(color: Colors.white),
                            ),
                            style: ElevatedButton.styleFrom(
                              backgroundColor: AppTheme.primary,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(10),
                              ),
                            ),
                            onPressed: () => _showDepositoModal(viewModel),
                          ),
                        ],
                      )
                    ],
                  ),
                  children: [
                    ListView.builder(
                      shrinkWrap: true,
                      itemCount: viewModel.depositos.length,
                      itemBuilder: (context, index) {
                        final deposito = viewModel.depositos[index];
                        if (deposito.eliminado == null) {
                          return ListTile(
                            title: Text(
                                "${DateFormat('dd/MM/yyyy HH:mm:ss').format(deposito.fechaDeposito!.toLocal())} - \$${formatNumber(deposito.monto)} - ${deposito.descripcion} - ${deposito.persona}"),
                            trailing: IconButton(
                              icon: Icon(Icons.remove_circle_outline,
                                  color: Colors.red),
                              onPressed: () async {
                                showDialog(
                                  context: context,
                                  builder: (context) {
                                    return TotpCuadroConfirmacion(
                                      title: "Eliminar Deposito",
                                      content:
                                          "Por favor, ingresa el código de autenticación para continuar.",
                                      onSuccess: () {
                                        viewModel
                                            .eliminarDeposito(deposito.id!);
                                      },
                                    );
                                  },
                                );
                              },
                            ),
                          );
                        }
                        return SizedBox.shrink();
                      },
                    ),
                    Padding(
                      padding: const EdgeInsets.only(right: 15),
                      child: Align(
                        alignment: Alignment.centerRight,
                        child: Text(
                          "Total: \$${formatNumber(viewModel.totalDepositos)}",
                          style: TextStyle(fontWeight: FontWeight.bold),
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 20),
                ExpansionTile(
                  backgroundColor: Colors.white,
                  collapsedBackgroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                    side: BorderSide(color: Colors.grey),
                  ),
                  collapsedShape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                    side: BorderSide(color: Colors.grey),
                  ),
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        "Retiros",
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 18),
                      ),
                      Row(
                        children: [
                          Text(
                            "Total: \$${formatNumber(viewModel.totalRetiros)}",
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ),
                          const SizedBox(
                            width: 20,
                          ),
                          ElevatedButton.icon(
                            icon: Icon(Icons.add, color: Colors.white),
                            label: Text(
                              "Agregar",
                              style: TextStyle(color: Colors.white),
                            ),
                            style: ElevatedButton.styleFrom(
                              backgroundColor: AppTheme.primary,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(10),
                              ),
                            ),
                            onPressed: () => _showRetiroModal(viewModel),
                          ),
                        ],
                      )
                    ],
                  ),
                  children: [
                    ListView.builder(
                      shrinkWrap: true,
                      itemCount: viewModel.retiros.length,
                      itemBuilder: (context, index) {
                        final retiro = viewModel.retiros[index];
                        if (retiro.eliminado == null) {
                          return ListTile(
                            title: Text(
                              "${DateFormat('dd/MM/yyyy HH:mm:ss').format(retiro.fechaRetiro!.toLocal())} - \$${formatNumber(retiro.monto)} - ${retiro.descripcion} - ${retiro.persona}",
                            ),
                            trailing: IconButton(
                              icon: Icon(Icons.remove_circle_outline,
                                  color: Colors.red),
                              onPressed: () async {
                                showDialog(
                                  context: context,
                                  builder: (context) {
                                    return TotpCuadroConfirmacion(
                                      title: "Eliminar Retiro",
                                      content:
                                          "Por favor, ingresa el código de autenticación para continuar.",
                                      onSuccess: () {
                                        viewModel.eliminarRetiro(retiro.id!);
                                      },
                                    );
                                  },
                                );
                              },
                            ),
                          );
                        }
                        return SizedBox.shrink();
                      },
                    ),
                    Padding(
                      padding: const EdgeInsets.only(right: 15),
                      child: Align(
                        alignment: Alignment.centerRight,
                        child: Text(
                          "Total: \$${formatNumber(viewModel.totalRetiros)}",
                          style: TextStyle(fontWeight: FontWeight.bold),
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 20),
                ExpansionTile(
                  backgroundColor: Colors.white,
                  collapsedBackgroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                    side: BorderSide(color: Colors.grey),
                  ),
                  collapsedShape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                    side: BorderSide(color: Colors.grey),
                  ),
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        "Gastos",
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 18),
                      ),
                      Row(
                        children: [
                          Text(
                            "Total: \$${formatNumber(viewModel.totalGastos)}",
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ),
                          const SizedBox(
                            width: 20,
                          ),
                          ElevatedButton.icon(
                            icon: Icon(Icons.add, color: Colors.white),
                            label: Text(
                              "Agregar",
                              style: TextStyle(color: Colors.white),
                            ),
                            style: ElevatedButton.styleFrom(
                              backgroundColor: AppTheme.primary,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(10),
                              ),
                            ),
                            onPressed: () => _showGastoModal(viewModel),
                          ),
                        ],
                      )
                    ],
                  ),
                  children: [
                    ListView.builder(
                      shrinkWrap: true,
                      itemCount: viewModel.gastos.length,
                      itemBuilder: (context, index) {
                        final gasto = viewModel.gastos[index];
                        if (gasto.eliminado == null) {
                          return ListTile(
                            title: Text(
                                "${DateFormat('dd/MM/yyyy HH:mm:ss').format(gasto.fechaGasto!.toLocal())} - \$${formatNumber(gasto.monto)} - ${gasto.descripcion} - ${gasto.persona}"),
                            trailing: IconButton(
                              icon: Icon(Icons.remove_circle_outline,
                                  color: Colors.red),
                              onPressed: () async {
                                showDialog(
                                  context: context,
                                  builder: (context) {
                                    return TotpCuadroConfirmacion(
                                      title: "Eliminar Gasto",
                                      content:
                                          "Por favor, ingresa el código de autenticación para continuar.",
                                      onSuccess: () {
                                        viewModel.eliminarGasto(gasto.id!);
                                      },
                                    );
                                  },
                                );
                              },
                            ),
                          );
                        }
                        return SizedBox.shrink();
                      },
                    ),
                    Padding(
                      padding: const EdgeInsets.only(right: 15),
                      child: Align(
                        alignment: Alignment.centerRight,
                        child: Text(
                          "Total: \$${formatNumber(viewModel.totalGastos)}",
                          style: TextStyle(fontWeight: FontWeight.bold),
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 20),
                ExpansionTile(
                  backgroundColor: Colors.white,
                  collapsedBackgroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                    side: BorderSide(color: Colors.grey),
                  ),
                  collapsedShape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                    side: BorderSide(color: Colors.grey),
                  ),
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        "Propinas",
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 18),
                      ),
                      Text(
                        "Total: \$${formatNumber(viewModel.totalPropinas)}",
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 18),
                      ),
                    ],
                  ),
                  children: [
                    if (viewModel.pedidosConPropinas.isEmpty)
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                            "No hay propinas registradas para este corte."),
                      )
                    else
                      ...viewModel.pedidosConPropinas.map((pedido) {
                        double totalPedidoPropinas = pedido.propinas.fold(
                          0.0,
                          (suma, prop) => suma + (prop.cantidad ?? 0.0),
                        );
                        return ListTile(
                          title: Text(
                            "Folio: ${pedido.folio} "
                            "- Total: \$${(pedido.totalPedido ?? 0).toStringAsFixed(2)} "
                            "- Propina: \$${totalPedidoPropinas.toStringAsFixed(2)}",
                          ),
                        );
                      }).toList(),
                  ],
                ),
                const SizedBox(height: 20),
                ExpansionTile(
                  backgroundColor: Colors.white,
                  collapsedBackgroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                    side: BorderSide(color: Colors.grey),
                  ),
                  collapsedShape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                    side: BorderSide(color: Colors.grey),
                  ),
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        "Pedidos Cancelados",
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 18),
                      ),
                      Row(
                        children: [
                          Text(
                            "Total: ${_pedidosCancelados.length}",
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ),
                          SizedBox(width: 20),
                        ],
                      )
                    ],
                  ),
                  children: [
                    if (_pedidosCancelados.isNotEmpty)
                      ListView.builder(
                        shrinkWrap: true,
                        itemCount: _pedidosCancelados.length,
                        itemBuilder: (context, index) {
                          final pedidoCancelado = _pedidosCancelados[index];
                          final tipoPagoString =
                              (pedidoCancelado.tipoPago?.isNotEmpty ?? false)
                                  ? " - ${pedidoCancelado.tipoPago}"
                                  : "";

                          return ListTile(
                            title: Text("Folio: ${pedidoCancelado.folio}"
                                " - \$${pedidoCancelado.totalPedido?.toStringAsFixed(2) ?? '0.00'}"
                                "$tipoPagoString"),
                          );
                        },
                      )
                    else
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child:
                            Text("No hay pedidos cancelados para este corte."),
                      ),
                  ],
                ),
                const SizedBox(height: 20),
                Align(
                  alignment: Alignment.centerRight,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      RichText(
                        text: TextSpan(
                          text: 'Efectivo en caja: ',
                          style: TextStyle(
                            fontSize: 22,
                            fontWeight: FontWeight.bold,
                            color: Colors.black,
                          ),
                          children: [
                            TextSpan(
                              text: '\$${formatNumber(viewModel.corteFinal)}',
                              style: TextStyle(
                                fontSize: 22,
                                fontWeight: FontWeight.normal,
                                color: Colors.black,
                              ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(height: 5),
                      RichText(
                        text: TextSpan(
                          text: 'Salidas Totales del Día: ',
                          style: TextStyle(
                            fontSize: 22,
                            fontWeight: FontWeight.bold,
                            color: Colors.black,
                          ),
                          children: [
                            TextSpan(
                              text:
                                  '\$${formatNumber(viewModel.salidasTotales)}',
                              style: TextStyle(
                                fontSize: 22,
                                fontWeight: FontWeight.normal,
                                color: Colors.black,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 20),
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    boton('Guardar', () async {
                      await viewModel.guardarCorte();
                      Navigator.pop(context);
                    }, height: 60, width: 250),
                    const SizedBox(width: 15),
                    if (viewModel.selectedCorte?.modificado != null)
                      boton('Realizar Corte', () async {
                        // 1) Verificar si hay pedidos con estatus NUEVO de este corte
                        final pedidosViewModel = Provider.of<PedidoViewModel>(
                            context,
                            listen: false);
                        List<Pedido> pedidosNuevos =
                            await pedidosViewModel.fetchPedidosNuevosByCorteId(
                                viewModel.selectedCorte!.id!);

                        // 2) Si no hay pedidos con estatus NUEVO se continúa flujo normal
                        if (pedidosNuevos.isEmpty) {
                          cuadroConfirmacion(
                            context,
                            etiqueta: "¿Estás seguro de realizar el corte?",
                            onConfirm: () async {
                              await viewModel.guardarCorte(esCorte: true);
                              Navigator.pop(context);
                              await viewModel.imprimirCorteCajaTicket();
                            },
                          );
                          return;
                        }

                        // 3) Hay pedidos con estatus NUEVO se va a revisar hora local
                        final serverDateTime = await viewModel.fetchHoraLocal();
                        print(DateFormat('dd/MM/yyyy HH:mm:ss')
                            .format(serverDateTime!));
                        if (serverDateTime.hour < 18) {
                          // Si son antes de las 6pm mostramos el diálogo para pasar los pedidos al siguiente corte
                          _mostrarDialogoPedidosNuevos(
                            context,
                            pedidosNuevos,
                            onAbrirNuevaCaja: (nuevosPedidos) async {
                              final oldCorteId = viewModel.selectedCorte!.id!;

                              await viewModel.guardarCorte(esCorte: true);

                              String? nuevaCajaId =
                                  await viewModel.createCorteCaja();
                              if (nuevaCajaId == null) return;

                              List<int> ids =
                                  nuevosPedidos.map((p) => p.id!).toList();
                              await pedidosViewModel
                                  .actualizarCorteCajaEnPedidos(
                                      ids, nuevaCajaId);

                              Navigator.pop(context);

                              await viewModel.imprimirCorteCajaTicket(
                                  corteCajaId: oldCorteId);
                            },
                          );
                        } else {
                          // Si son de las 6pm mostramos el diálogo que forza el terminar esos pedidos
                          _mostrarDialogoDespuesDe6pm(context, pedidosNuevos);
                        }
                      }, height: 60, width: 250),
                  ],
                ),
              ],
            ),
          ),
        ));
  }

  void _showDepositoModal(CorteCajaViewModel viewModel) {
    showDialog(
      context: context,
      builder: (context) {
        return Dialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10),
          ),
          child: Container(
            width: MediaQuery.of(context).size.width * 0.6,
            padding: EdgeInsets.all(20),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  "Depósitos",
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
                SizedBox(height: 10),
                AppTextField(
                  etiqueta: "Monto del depósito",
                  prefixIcon: const Icon(Icons.attach_money_sharp),
                  controller: _montoDepositoController,
                  keyboardType: TextInputType.number,
                  separarMiles: true,
                ),
                SizedBox(height: 10),
                AppTextField(
                  etiqueta: "Descripción del depósito",
                  controller: _descripcionDepositoController,
                ),
                SizedBox(height: 10),
                AppTextField(
                  etiqueta: "Persona",
                  controller: _personaDepositoController,
                ),
                SizedBox(height: 20),
                Text(
                  "Lista de Depósitos",
                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
                ),
                SizedBox(height: 10),
                Consumer<CorteCajaViewModel>(
                  builder: (context, viewModel, child) {
                    return Column(
                      children: [
                        ListView.builder(
                          shrinkWrap: true,
                          itemCount: viewModel.depositos.length,
                          itemBuilder: (context, index) {
                            final deposito = viewModel.depositos[index];
                            if (deposito.eliminado == null) {
                              return ListTile(
                                title: Text(
                                  "${DateFormat('dd/MM/yyyy HH:mm:ss').format(deposito.fechaDeposito!.toLocal())} - \$${formatNumber(deposito.monto)} - ${deposito.descripcion} - ${deposito.persona}",
                                ),
                                trailing: IconButton(
                                  icon: Icon(Icons.remove_circle_outline,
                                      color: Colors.red),
                                  onPressed: () async {
                                    showDialog(
                                      context: context,
                                      builder: (context) {
                                        return TotpCuadroConfirmacion(
                                          title: "Eliminar Deposito",
                                          content:
                                              "Por favor, ingresa el código de autenticación para continuar.",
                                          onSuccess: () {
                                            viewModel
                                                .eliminarDeposito(deposito.id!);
                                          },
                                        );
                                      },
                                    );
                                  },
                                ),
                              );
                            }
                            return SizedBox.shrink();
                          },
                        ),
                        Align(
                          alignment: Alignment.centerRight,
                          child: Text(
                            "Total: \$${formatNumber(viewModel.totalDepositos)}",
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ),
                        ),
                      ],
                    );
                  },
                ),
                SizedBox(height: 20),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    ElevatedButton(
                      onPressed: () {
                        double monto = double.tryParse(_montoDepositoController
                                .text
                                .replaceAll(',', '')) ??
                            0;
                        if (monto <= 0) {
                          alerta(context,
                              etiqueta: "El monto debe ser mayor a 0.");
                          return;
                        }
                        String descripcion =
                            _descripcionDepositoController.text;
                        String persona = _personaDepositoController.text;

                        showDialog(
                          context: context,
                          builder: (context) {
                            return TotpCuadroConfirmacion(
                              title: "Agregar Depósito",
                              content:
                                  "Por favor, ingresa el código de autenticación para continuar.",
                              onSuccess: () {
                                viewModel.addDeposito(
                                  monto,
                                  descripcion,
                                  persona,
                                  widget.corteCajaId!,
                                );
                                _montoDepositoController.clear();
                                _descripcionDepositoController.clear();
                                _personaDepositoController.clear();
                              },
                            );
                          },
                        );
                      },
                      child: Text(
                        "Agregar",
                        style: TextStyle(color: AppTheme.quaternary),
                      ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppTheme.primary,
                        padding:
                            EdgeInsets.symmetric(horizontal: 50, vertical: 15),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                      ),
                    ),
                    ElevatedButton(
                      onPressed: () {
                        Navigator.pop(context);
                      },
                      child: Text(
                        "Cerrar",
                        style: TextStyle(color: AppTheme.quaternary),
                      ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppTheme.primary,
                        padding:
                            EdgeInsets.symmetric(horizontal: 50, vertical: 15),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  void _showRetiroModal(CorteCajaViewModel viewModel) {
    showDialog(
      context: context,
      builder: (context) {
        return Dialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10),
          ),
          child: Container(
            width: MediaQuery.of(context).size.width * 0.6,
            padding: EdgeInsets.all(20),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  "Retiros",
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
                SizedBox(height: 10),
                AppTextField(
                  etiqueta: "Monto del retiro",
                  prefixIcon: const Icon(Icons.attach_money_sharp),
                  controller: _montoRetiroController,
                  keyboardType: TextInputType.number,
                  separarMiles: true,
                ),
                SizedBox(height: 10),
                AppTextField(
                  etiqueta: "Descripción del retiro",
                  controller: _descripcionRetiroController,
                ),
                SizedBox(height: 10),
                AppTextField(
                  etiqueta: "Persona",
                  controller: _personaRetiroController,
                ),
                SizedBox(height: 20),
                Text(
                  "Lista de Retiros",
                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
                ),
                SizedBox(height: 10),
                Consumer<CorteCajaViewModel>(
                  builder: (context, viewModel, child) {
                    return Column(
                      children: [
                        ListView.builder(
                          shrinkWrap: true,
                          itemCount: viewModel.retiros.length,
                          itemBuilder: (context, index) {
                            final retiro = viewModel.retiros[index];
                            if (retiro.eliminado == null) {
                              return ListTile(
                                title: Text(
                                  "${DateFormat('dd/MM/yyyy HH:mm:ss').format(retiro.fechaRetiro!.toLocal())} - \$${formatNumber(retiro.monto)} - ${retiro.descripcion} - ${retiro.persona}",
                                ),
                                trailing: IconButton(
                                  icon: Icon(Icons.remove_circle_outline,
                                      color: Colors.red),
                                  onPressed: () async {
                                    showDialog(
                                      context: context,
                                      builder: (context) {
                                        return TotpCuadroConfirmacion(
                                          title: "Eliminar Retiro",
                                          content:
                                              "Por favor, ingresa el código de autenticación para continuar.",
                                          onSuccess: () {
                                            viewModel
                                                .eliminarRetiro(retiro.id!);
                                          },
                                        );
                                      },
                                    );
                                  },
                                ),
                              );
                            }
                            return SizedBox.shrink();
                          },
                        ),
                        Align(
                          alignment: Alignment.centerRight,
                          child: Text(
                            "Total: \$${formatNumber(viewModel.totalRetiros)}",
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ),
                        ),
                      ],
                    );
                  },
                ),
                SizedBox(height: 20),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    ElevatedButton(
                      onPressed: () {
                        double monto = double.tryParse(_montoRetiroController
                                .text
                                .replaceAll(',', '')) ??
                            0;
                        if (monto <= 0) {
                          alerta(context,
                              etiqueta: "El monto debe ser mayor a 0.");
                          return;
                        }
                        String descripcion = _descripcionRetiroController.text;
                        String persona = _personaRetiroController.text;

                        showDialog(
                          context: context,
                          builder: (context) {
                            return TotpCuadroConfirmacion(
                              title: "Agregar Retiro",
                              content:
                                  "Por favor, ingresa el código de autenticación para continuar.",
                              onSuccess: () {
                                viewModel.addRetiro(
                                  monto,
                                  descripcion,
                                  persona,
                                  widget.corteCajaId!,
                                );
                                _montoRetiroController.clear();
                                _descripcionRetiroController.clear();
                                _personaRetiroController.clear();
                              },
                            );
                          },
                        );
                      },
                      child: Text(
                        "Agregar",
                        style: TextStyle(color: AppTheme.quaternary),
                      ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppTheme.primary,
                        padding:
                            EdgeInsets.symmetric(horizontal: 50, vertical: 15),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                      ),
                    ),
                    ElevatedButton(
                      onPressed: () {
                        Navigator.pop(context);
                      },
                      child: Text(
                        "Cerrar",
                        style: TextStyle(color: AppTheme.quaternary),
                      ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppTheme.primary,
                        padding:
                            EdgeInsets.symmetric(horizontal: 50, vertical: 15),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  void _showGastoModal(CorteCajaViewModel viewModel) {
    showDialog(
      context: context,
      builder: (context) {
        return Dialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10),
          ),
          child: Container(
            width: MediaQuery.of(context).size.width * 0.6,
            padding: EdgeInsets.all(20),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  "Gastos",
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
                SizedBox(height: 10),
                AppTextField(
                  etiqueta: "Monto del gasto",
                  prefixIcon: const Icon(Icons.attach_money_sharp),
                  controller: _montoGastoController,
                  keyboardType: TextInputType.number,
                  separarMiles: true,
                ),
                SizedBox(height: 10),
                AppTextField(
                  etiqueta: "Descripción del gasto",
                  controller: _descripcionGastoController,
                ),
                SizedBox(height: 10),
                AppTextField(
                  etiqueta: "Persona",
                  controller: _personaGastoController,
                ),
                SizedBox(height: 20),
                Text(
                  "Lista de Gastos",
                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
                ),
                SizedBox(height: 10),
                Consumer<CorteCajaViewModel>(
                  builder: (context, viewModel, child) {
                    return Column(
                      children: [
                        ListView.builder(
                          shrinkWrap: true,
                          itemCount: viewModel.gastos.length,
                          itemBuilder: (context, index) {
                            final gasto = viewModel.gastos[index];
                            if (gasto.eliminado == null) {
                              return ListTile(
                                title: Text(
                                  "${DateFormat('dd/MM/yyyy HH:mm:ss').format(gasto.fechaGasto!.toLocal())} - \$${formatNumber(gasto.monto)} - ${gasto.descripcion} - ${gasto.persona}",
                                ),
                                trailing: IconButton(
                                  icon: Icon(Icons.remove_circle_outline,
                                      color: Colors.red),
                                  onPressed: () async {
                                    showDialog(
                                      context: context,
                                      builder: (context) {
                                        return TotpCuadroConfirmacion(
                                          title: "Eliminar Gasto",
                                          content:
                                              "Por favor, ingresa el código de autenticación para continuar.",
                                          onSuccess: () {
                                            viewModel.eliminarGasto(gasto.id!);
                                          },
                                        );
                                      },
                                    );
                                  },
                                ),
                              );
                            }
                            return SizedBox.shrink();
                          },
                        ),
                        Align(
                          alignment: Alignment.centerRight,
                          child: Text(
                            "Total: \$${formatNumber(viewModel.totalGastos)}",
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ),
                        ),
                      ],
                    );
                  },
                ),
                SizedBox(height: 20),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    ElevatedButton(
                      onPressed: () {
                        double monto = double.tryParse(_montoGastoController
                                .text
                                .replaceAll(',', '')) ??
                            0;
                        if (monto <= 0) {
                          alerta(context,
                              etiqueta: "El monto debe ser mayor a 0.");
                          return;
                        }
                        String descripcion = _descripcionGastoController.text;
                        String persona = _personaGastoController.text;

                        showDialog(
                          context: context,
                          builder: (context) {
                            return TotpCuadroConfirmacion(
                              title: "Agregar Gasto",
                              content:
                                  "Por favor, ingresa el código de autenticación para continuar.",
                              onSuccess: () {
                                viewModel.addGasto(
                                  monto,
                                  descripcion,
                                  persona,
                                  widget.corteCajaId!,
                                );
                                _montoGastoController.clear();
                                _descripcionGastoController.clear();
                                _personaGastoController.clear();
                              },
                            );
                          },
                        );
                      },
                      child: Text(
                        "Agregar",
                        style: TextStyle(color: AppTheme.quaternary),
                      ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppTheme.primary,
                        padding:
                            EdgeInsets.symmetric(horizontal: 50, vertical: 15),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                      ),
                    ),
                    ElevatedButton(
                      onPressed: () {
                        Navigator.pop(context);
                      },
                      child: Text(
                        "Cerrar",
                        style: TextStyle(color: AppTheme.quaternary),
                      ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppTheme.primary,
                        padding:
                            EdgeInsets.symmetric(horizontal: 50, vertical: 15),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
