import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../../themes/themes.dart';
import 'package:intl/intl.dart';
import '../../models/corte_caja_model.dart';
import '../../viewmodels/corte_caja_view_model.dart';
import '../../widgets/app_textfield.dart';
import '../../widgets/widgets.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();
  DateTime? fechaApertura;
  bool isFirst = true;
  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;

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

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

          if (fechaApertura != null) {
            viewModel.cargarVentasDesdeFechaApertura(fechaApertura!).then((_) {
              viewModel.calcularCorteFinal();
            });
          }
        });
      });
    }
  }

  @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) {
                          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: 20),
                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: () {
                                cuadroConfirmacion(
                                  context,
                                  etiqueta:
                                      "¿Estás seguro de eliminar el depósito?",
                                  onConfirm: () {
                                    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: () {
                                cuadroConfirmacion(
                                  context,
                                  etiqueta:
                                      "¿Estás seguro de eliminar el retiro?",
                                  onConfirm: () {
                                    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: () {
                                cuadroConfirmacion(
                                  context,
                                  etiqueta:
                                      "¿Estás seguro de eliminar el gasto?",
                                  onConfirm: () {
                                    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),
                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 {
                        cuadroConfirmacion(
                          context,
                          etiqueta: "¿Estás seguro realizar el corte?",
                          onConfirm: () async {
                            await viewModel.guardarCorte(esCorte: true);
                            Navigator.pop(context);
                            await viewModel.imprimirCorteCajaTicket();
                          },
                        );
                      }, 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),
                // Lista de depósitos
                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: () {
                                    cuadroConfirmacion(
                                      context,
                                      etiqueta:
                                          "¿Estás seguro de eliminar el depósito?",
                                      onConfirm: () {
                                        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;

                        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: () {
                                    cuadroConfirmacion(
                                      context,
                                      etiqueta:
                                          "¿Estás seguro de eliminar el retiro?",
                                      onConfirm: () {
                                        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;

                        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: () {
                                    cuadroConfirmacion(
                                      context,
                                      etiqueta:
                                          "¿Estás seguro de eliminar el gasto?",
                                      onConfirm: () {
                                        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;

                        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),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
