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

class CorteCajaFinalizadoScreen extends StatefulWidget {
  final String? corteCajaId;

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

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

class _CorteCajaFinalizadoScreenState extends State<CorteCajaFinalizadoScreen> {
  Map<String, bool> _expandedSections = {};

  List<Pedido> _pedidosCancelados = [];

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

    viewModel.fetchPedidosCancelados(widget.corteCajaId!).then((pedidos) {
      setState(() {
        _pedidosCancelados = pedidos;
      });
    });

    viewModel.fetchPedidosConPropinas(widget.corteCajaId!);
  }

  @override
  Widget build(BuildContext context) {
    final viewModel = Provider.of<CorteCajaViewModel>(context);
    double totalEfe = viewModel.selectedCorte!.ventaEfe!;
    double totalTarj = viewModel.selectedCorte!.ventaTarj!;
    double totalTrans = viewModel.selectedCorte!.ventaTrans!;
    double totalRetiro = viewModel.selectedCorte!.retiro!;
    double totalGasto = viewModel.selectedCorte!.gasto!;
    double totalSalidas = totalRetiro + totalGasto;
    double totalVentas = totalEfe + totalTrans + totalTarj;

    return Scaffold(
      appBar: AppBar(
          title: Text('Resumen Corte de Caja',
              style: TextStyle(
                  color: AppTheme.secondary, fontWeight: FontWeight.w500)),
          iconTheme: IconThemeData(color: AppTheme.secondary)),
      body: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 250, vertical: 20),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                "Fecha: ${DateFormat('dd/MM/yyyy').format(viewModel.selectedCorte!.fechaApertura!)}",
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 20),
              tarjeta(Column(
                children: [
                  Table(
                    defaultVerticalAlignment: TableCellVerticalAlignment.middle,
                    columnWidths: {
                      0: FlexColumnWidth(4),
                      1: FlexColumnWidth(2)
                    },
                    children: [
                      _buildTableRow("Fondo", viewModel.selectedCorte?.fondo),
                      _buildTableRow("Fondo día siguiente",
                          viewModel.selectedCorte?.fondoDiaSig),
                      _buildTableRow("Ventas Efectivo", totalEfe),
                      _buildTableRow("Ventas Tarjeta", totalTarj),
                      _buildTableRow("Ventas Transferencia", totalTrans),
                    ],
                  ),
                  _buildExpandableTable("Depósitos", viewModel.depositos,
                      viewModel.selectedCorte?.deposito),
                  _buildExpandableTable(
                      "Retiros", viewModel.retiros, totalRetiro),
                  _buildExpandableTable("Gastos", viewModel.gastos, totalGasto),
                  _buildExpandablePropinas(
                    "Propinas",
                    viewModel.pedidosConPropinas,
                    viewModel.totalPropinas,
                  ),
                  _buildExpandablePedidosCancelados(
                    "Pedidos Cancelados",
                    _pedidosCancelados,
                  ),
                  Table(
                    defaultVerticalAlignment: TableCellVerticalAlignment.middle,
                    columnWidths: {
                      0: FlexColumnWidth(4),
                      1: FlexColumnWidth(2)
                    },
                    children: [
                      _buildTableRow('', null),
                      _buildTableRow('Venta total del día', totalVentas),
                      _buildTableRow("Efectivo en caja",
                          viewModel.selectedCorte?.corteFinal),
                      _buildTableRow("Salidas totales del día", totalSalidas),
                    ],
                  ),
                ],
              )),
            ],
          ),
        ),
      ),
    );
  }

  TableRow _buildTableRow(String label, double? value) {
    return TableRow(
      children: [
        Container(
          decoration: BoxDecoration(border: Border.all(color: Colors.grey)),
          padding: const EdgeInsets.all(8.5),
          child: Text(label,
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18)),
        ),
        Container(
          decoration: BoxDecoration(border: Border.all(color: Colors.grey)),
          height: 45,
          padding: const EdgeInsets.all(8.0),
          child: Text(
            value != null ? "\$${value.toStringAsFixed(2)}" : "",
            style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
          ),
        ),
      ],
    );
  }

  Widget _buildExpandableTable(
      String title, List<dynamic> items, double? total) {
    final isExpanded = _expandedSections[title] ?? true;

    return Column(
      children: [
        GestureDetector(
          onTap: () {
            setState(() {
              _expandedSections[title] = !isExpanded;
            });
          },
          child: Container(
            child: Table(
              defaultVerticalAlignment: TableCellVerticalAlignment.middle,
              columnWidths: {0: FlexColumnWidth(4), 1: FlexColumnWidth(2)},
              children: [
                TableRow(
                  children: [
                    Container(
                      padding: const EdgeInsets.all(8.5),
                      decoration:
                          BoxDecoration(border: Border.all(color: Colors.grey)),
                      child: Text(
                        title,
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 18),
                      ),
                    ),
                    Container(
                      padding: const EdgeInsets.all(8.5),
                      decoration:
                          BoxDecoration(border: Border.all(color: Colors.grey)),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            total != null
                                ? "\$${total.toStringAsFixed(2)}"
                                : "",
                            style: TextStyle(
                                fontWeight: FontWeight.bold, fontSize: 18),
                          ),
                          Icon(isExpanded
                              ? Icons.expand_less
                              : Icons.expand_more),
                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
        if (isExpanded)
          Table(
            defaultVerticalAlignment: TableCellVerticalAlignment.middle,
            columnWidths: {0: FlexColumnWidth(4), 1: FlexColumnWidth(2)},
            children: items.map((item) {
              return TableRow(
                children: [
                  Container(
                    padding: const EdgeInsets.all(8.5),
                    decoration:
                        BoxDecoration(border: Border.all(color: Colors.grey)),
                    child: Text(" -${item.descripcion}",
                        style: TextStyle(
                            fontSize: 16, fontWeight: FontWeight.w600)),
                  ),
                  Container(
                    padding: const EdgeInsets.all(8.5),
                    decoration:
                        BoxDecoration(border: Border.all(color: Colors.grey)),
                    child: Text(
                      "\$${item.monto?.toStringAsFixed(2)}",
                      style:
                          TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
                    ),
                  ),
                ],
              );
            }).toList(),
          ),
      ],
    );
  }

  Widget _buildExpandablePedidosCancelados(String title, List<Pedido> pedidos) {
    final isExpanded = _expandedSections[title] ?? true;

    return Column(
      children: [
        GestureDetector(
          onTap: () {
            setState(() {
              _expandedSections[title] = !isExpanded;
            });
          },
          child: Container(
            child: Table(
              defaultVerticalAlignment: TableCellVerticalAlignment.middle,
              columnWidths: {0: FlexColumnWidth(4), 1: FlexColumnWidth(2)},
              children: [
                TableRow(
                  children: [
                    Container(
                      padding: const EdgeInsets.all(8.5),
                      decoration:
                          BoxDecoration(border: Border.all(color: Colors.grey)),
                      child: Text(
                        title,
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 18),
                      ),
                    ),
                    Container(
                      padding: const EdgeInsets.all(8.5),
                      decoration:
                          BoxDecoration(border: Border.all(color: Colors.grey)),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            "Total: ${pedidos.length}",
                            style: TextStyle(
                                fontWeight: FontWeight.bold, fontSize: 18),
                          ),
                          Icon(isExpanded
                              ? Icons.expand_less
                              : Icons.expand_more),
                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),

        // Contenido expandido
        if (isExpanded)
          pedidos.isNotEmpty
              ? Table(
                  defaultVerticalAlignment: TableCellVerticalAlignment.middle,
                  columnWidths: {0: FlexColumnWidth(4), 1: FlexColumnWidth(2)},
                  children: pedidos.map((pedido) {
                    // Construir fila con folio, totalPedido y tipoPago si existe
                    // Observa que en la primer celda pondremos el texto completo
                    // y la segunda celda podría quedar vacía o un " - "
                    final tipoPago = (pedido.tipoPago?.isNotEmpty ?? false)
                        ? " - ${pedido.tipoPago}"
                        : "";
                    return TableRow(
                      children: [
                        Container(
                          padding: const EdgeInsets.all(8.5),
                          decoration: BoxDecoration(
                              border: Border.all(color: Colors.grey)),
                          child: Text(
                            "Folio: ${pedido.folio} "
                            "$tipoPago",
                            style: TextStyle(
                                fontSize: 16, fontWeight: FontWeight.w600),
                          ),
                        ),
                        Container(
                          padding: const EdgeInsets.all(8.5),
                          decoration: BoxDecoration(
                              border: Border.all(color: Colors.grey)),
                          child: Text(
                            "\$${pedido.totalPedido?.toStringAsFixed(2) ?? '0.00'}",
                            style: TextStyle(
                                fontSize: 16, fontWeight: FontWeight.w600),
                          ),
                        ),
                      ],
                    );
                  }).toList(),
                )
              : Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text(
                    "No hay pedidos cancelados para este corte.",
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
                  ),
                ),
      ],
    );
  }

  Widget _buildExpandablePropinas(
      String title, List<Pedido> pedidos, double totalPropinas) {
    final isExpanded = _expandedSections[title] ?? true;

    return Column(
      children: [
        GestureDetector(
          onTap: () {
            setState(() {
              _expandedSections[title] = !isExpanded;
            });
          },
          child: Container(
            child: Table(
              defaultVerticalAlignment: TableCellVerticalAlignment.middle,
              columnWidths: {0: FlexColumnWidth(4), 1: FlexColumnWidth(2)},
              children: [
                TableRow(
                  children: [
                    Container(
                      padding: const EdgeInsets.all(8.5),
                      decoration:
                          BoxDecoration(border: Border.all(color: Colors.grey)),
                      child: Text(
                        title,
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 18,
                        ),
                      ),
                    ),
                    Container(
                      padding: const EdgeInsets.all(8.5),
                      decoration:
                          BoxDecoration(border: Border.all(color: Colors.grey)),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          // Mostramos el total general de propinas
                          Text(
                            "\$${totalPropinas.toStringAsFixed(2)}",
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 18,
                            ),
                          ),
                          Icon(isExpanded
                              ? Icons.expand_less
                              : Icons.expand_more),
                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
        if (isExpanded)
          pedidos.isNotEmpty
              ? Table(
                  defaultVerticalAlignment: TableCellVerticalAlignment.middle,
                  columnWidths: {0: FlexColumnWidth(4), 1: FlexColumnWidth(2)},
                  children: pedidos.map((pedido) {
                    // Sumar propinas para este pedido en particular
                    double sumaPropinasPedido = pedido.propinas.fold(
                      0.0,
                      (prev, propina) => prev + (propina.cantidad ?? 0),
                    );
                    return TableRow(
                      children: [
                        Container(
                          padding: const EdgeInsets.all(8.5),
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.grey),
                          ),
                          child: Text(
                            "Folio: ${pedido.folio} - Total: \$${(pedido.totalPedido ?? 0).toStringAsFixed(2)}",
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                        Container(
                          padding: const EdgeInsets.all(8.5),
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.grey),
                          ),
                          child: Text(
                            "\$${sumaPropinasPedido.toStringAsFixed(2)}",
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ],
                    );
                  }).toList(),
                )
              : Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text(
                    "No hay propinas registradas para este corte.",
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
      ],
    );
  }
}
