import '../../views/corte_caja/corte_caja_form.dart';
import '../../widgets/widgets.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import '../../themes/themes.dart';
import '../../models/models.dart';
import '../../viewmodels/viewmodels.dart';
import '../../widgets/widgets_components.dart' as clase;
import 'corte_caja_finalizado_screen.dart';

class CorteCajaScreen extends StatefulWidget {
  const CorteCajaScreen({Key? key}) : super(key: key);

  @override
  State<CorteCajaScreen> createState() => _CorteCajaScreenState();
}

class _CorteCajaScreenState extends State<CorteCajaScreen> {
  final _busqueda = TextEditingController(text: '');
  DateTime? fechaInicio;
  DateTime? fechaFin;
  ScrollController horizontalScrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Provider.of<CorteCajaViewModel>(context, listen: false).fetchCortes();
    });
  }

  void clearSearchAndReset() {
    setState(() {
      _busqueda.clear();
      fechaInicio = null;
      fechaFin = null;
      Provider.of<CorteCajaViewModel>(context, listen: false).fetchCortes();
    });
  }

  void go(CorteCaja item) async {
    final viewModel = Provider.of<CorteCajaViewModel>(context, listen: false);
    viewModel.selectCorte(item);

    await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => item.fechaCorte != null
            ? CorteCajaFinalizadoScreen(corteCajaId: item.id)
            : CorteCajaForm(corteCajaId: item.id),
      ),
    ).then((_) => viewModel.fetchCortes());
  }

  @override
  Widget build(BuildContext context) {
    final pvm = Provider.of<CorteCajaViewModel>(context);
    double screenWidth = MediaQuery.of(context).size.width;
    final isMobile = screenWidth < 1250;
    final double? columnSpacing = isMobile ? null : 0;
    TextStyle estilo = const TextStyle(fontWeight: FontWeight.bold);
    List<DataRow> registros = [];

    for (CorteCaja item in pvm.cortes) {
      registros.add(DataRow(cells: [
        DataCell(
            Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
          PopupMenuButton(
            itemBuilder: (context) => [
              PopupMenuItem(
                child: const Text('Editar'),
                onTap: () => go(item),
              ),
              if (item.fechaCorte != null)
                PopupMenuItem(
                  child: const Text('Imprimir Ticket'),
                  onTap: () async {
                    final viewModel =
                        Provider.of<CorteCajaViewModel>(context, listen: false);
                    viewModel.selectCorte(item);
                    await viewModel.imprimirCorteCajaTicket(
                        corteCajaId: item.id);
                  },
                ),
            ],
            icon: const Icon(Icons.more_vert),
          ),
        ])),
        DataCell(
          Text(item.fechaApertura != null
              ? DateFormat("dd/MM/yyyy HH:mm:ss")
                  .format(item.fechaApertura!.toLocal())
              : "Sin fecha"),
          onTap: () => go(item),
        ),
        DataCell(
          Text(item.fechaCorte != null
              ? DateFormat("dd/MM/yyyy HH:mm:ss")
                  .format(item.fechaCorte!.toLocal())
              : "Sin fecha"),
          onTap: () => go(item),
        ),
        DataCell(
          Text('\$${formatoMiles(item.corteFinal)}'),
          onTap: () => go(item),
        ),
      ]));
    }

    return Scaffold(
      appBar: AppBar(
          title: Text(
            'Corte De Caja',
            style: TextStyle(
                color: AppTheme.secondary, fontWeight: FontWeight.w500),
          ),
          iconTheme: IconThemeData(color: AppTheme.secondary)),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () async {
          final viewModel =
              Provider.of<CorteCajaViewModel>(context, listen: false);

          if (viewModel.hasOpenCorteCaja()) {
            alerta(context,
                etiqueta:
                    'No se puede crear un nuevo corte hasta que el anterior esté cerrado.');
            return;
          }

          String? nuevoCorteId = await viewModel.createCorteCaja();

          await viewModel.fetchCortes();

          await Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => CorteCajaForm(corteCajaId: nuevoCorteId),
            ),
          ).then((_) => viewModel.fetchCortes());
        },
        icon: Icon(Icons.add, size: 30, color: AppTheme.quaternary),
        label: Text(
          "Nuevo Corte De Caja",
          style: TextStyle(fontSize: 20, color: AppTheme.quaternary),
        ),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
        backgroundColor: AppTheme.secondary,
        foregroundColor: AppTheme.quaternary,
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView(
              padding: const EdgeInsets.fromLTRB(8, 0, 8, 0),
              children: [
                const SizedBox(height: 8),
                clase.tarjeta(
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: LayoutBuilder(
                      builder: (context, constraints) {
                        if (screenWidth > 1000) {
                          return Row(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              Expanded(
                                flex: 7,
                                child: _buildDateRangePicker(),
                              ),
                              SizedBox(width: 5),
                              botonBuscar()
                            ],
                          );
                        } else {
                          return Column(
                            children: [
                              Row(
                                children: [_buildDateRangePicker()],
                              ),
                              SizedBox(height: 15),
                              Row(
                                children: [botonBuscar()],
                              ),
                            ],
                          );
                        }
                      },
                    ),
                  ),
                ),
                const SizedBox(height: 8),
                pvm.isLoading
                    ? const Center(child: CircularProgressIndicator())
                    : Container(),
                clase.tarjeta(
                  Column(
                    children: [
                      LayoutBuilder(builder: (context, constraints) {
                        return SingleChildScrollView(
                          scrollDirection: Axis.vertical,
                          child: Scrollbar(
                            controller: horizontalScrollController,
                            interactive: true,
                            thumbVisibility: true,
                            thickness: 10.0,
                            child: SingleChildScrollView(
                              controller: horizontalScrollController,
                              scrollDirection: Axis.horizontal,
                              child: ConstrainedBox(
                                constraints: BoxConstraints(
                                    minWidth: isMobile
                                        ? constraints.maxWidth
                                        : screenWidth),
                                child: DataTable(
                                  columnSpacing: columnSpacing,
                                  sortAscending: true,
                                  sortColumnIndex: 1,
                                  columns: [
                                    DataColumn(label: Text(" ", style: estilo)),
                                    DataColumn(
                                        label: Text("Fecha Apertura",
                                            style: estilo)),
                                    DataColumn(
                                        label: Text("Fecha Cierre",
                                            style: estilo)),
                                    DataColumn(
                                        label: Text("Efectivo En Caja",
                                            style: estilo)),
                                  ],
                                  rows: registros,
                                ),
                              ),
                            ),
                          ),
                        );
                      }),
                    ],
                  ),
                ),
                const SizedBox(height: 15),
                if (!pvm.isLoading)
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      TextButton(
                        onPressed:
                            pvm.currentPage > 1 ? pvm.previousPage : null,
                        child: Text('Anterior'),
                        style: ButtonStyle(
                          backgroundColor:
                              MaterialStateProperty.resolveWith<Color?>(
                            (Set<MaterialState> states) {
                              if (states.contains(MaterialState.disabled)) {
                                return Colors.grey;
                              }
                              return AppTheme.primary;
                            },
                          ),
                          foregroundColor:
                              MaterialStateProperty.resolveWith<Color?>(
                            (Set<MaterialState> states) {
                              if (states.contains(MaterialState.disabled)) {
                                return Colors.black;
                              }
                              return Colors.white;
                            },
                          ),
                        ),
                      ),
                      SizedBox(width: 15),
                      Text('Página ${pvm.currentPage} de ${pvm.totalPages}'),
                      SizedBox(width: 15),
                      TextButton(
                        onPressed: pvm.currentPage < pvm.totalPages
                            ? pvm.nextPage
                            : null,
                        child: Text('Siguiente'),
                        style: ButtonStyle(
                          backgroundColor:
                              MaterialStateProperty.resolveWith<Color?>(
                            (Set<MaterialState> states) {
                              if (states.contains(MaterialState.disabled)) {
                                return Colors.grey;
                              }
                              return AppTheme.primary;
                            },
                          ),
                          foregroundColor:
                              MaterialStateProperty.resolveWith<Color?>(
                            (Set<MaterialState> states) {
                              if (states.contains(MaterialState.disabled)) {
                                return Colors.black;
                              }
                              return Colors.white;
                            },
                          ),
                        ),
                      ),
                    ],
                  ),
                const SizedBox(height: 15),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDateRangePicker() {
    return Row(
      children: [
        Expanded(
          flex: 3,
          child: clase.FechaSelectWidget(
            fecha: fechaInicio,
            onFechaChanged: (d) {
              setState(() {
                fechaInicio = d;
              });
            },
            etiqueta: "Fecha Inicial",
            context: context,
          ),
        ),
        const SizedBox(width: 5),
        Expanded(
          flex: 3,
          child: clase.FechaSelectWidget(
            fecha: fechaFin,
            onFechaChanged: (d) {
              setState(() {
                fechaFin = d;
              });
            },
            etiqueta: "Fecha Final",
            context: context,
          ),
        ),
      ],
    );
  }

  Widget botonBuscar() {
    return Expanded(
        flex: 2,
        child: Row(
          children: [
            Expanded(
              flex: 2,
              child: Padding(
                padding: const EdgeInsets.only(top: 0),
                child: ElevatedButton(
                  onPressed: clearSearchAndReset,
                  style: ElevatedButton.styleFrom(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20.0),
                    ),
                    backgroundColor: Colors.redAccent,
                    padding: const EdgeInsets.symmetric(vertical: 25),
                  ),
                  child: Text('Limpiar',
                      style: TextStyle(color: AppTheme.quaternary)),
                ),
              ),
            ),
            const SizedBox(width: 8),
            Expanded(
              flex: 2,
              child: Padding(
                padding: const EdgeInsets.only(top: 0),
                child: ElevatedButton(
                  onPressed: () async {
                    if (fechaInicio != null && fechaFin != null) {
                      await Provider.of<CorteCajaViewModel>(context,
                              listen: false)
                          .buscarPorFecha(fechaInicio!, fechaFin!);
                    } else {
                      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
                          content: Text(
                              'Selecciona un rango de fechas para buscar.')));
                    }
                  },
                  style: ElevatedButton.styleFrom(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20.0),
                    ),
                    backgroundColor: AppTheme.tertiary,
                    padding: const EdgeInsets.symmetric(vertical: 25),
                  ),
                  child: Text('Buscar',
                      style: TextStyle(color: AppTheme.quaternary)),
                ),
              ),
            ),
          ],
        ));
  }
}
