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

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 {
    // CorteCaja? CorteCajaCompleto =
    //     await Provider.of<CorteCajaViewModel>(context, listen: false)
    //         .fetchCorteCajaConProductos(item.id);
    // if (CorteCajaCompleto != null) {
    //   // Navigator.push(
    //   //   context,
    //   //   MaterialPageRoute(
    //   //     builder: (context) => CorteCajaDetalleScreen(CorteCaja: CorteCajaCompleto),
    //   //   ),
    //   // );
    // } else {
    //   print("Error al cargar el CorteCaja con productos");
    // }
  }

  @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),
              ),
              PopupMenuItem(
                child: const Text('Cancelar CorteCaja'),
                onTap: () async {
                  bool confirmado = await showDialog<bool>(
                        context: context,
                        builder: (context) {
                          return AlertDialog(
                            title: const Text("Cancelar CorteCaja"),
                            content: const Text(
                                '¿Estás seguro de que deseas cancelar este CorteCaja?'),
                            actions: [
                              TextButton(
                                onPressed: () =>
                                    Navigator.of(context).pop(false),
                                child: const Text('No'),
                              ),
                              TextButton(
                                onPressed: () =>
                                    Navigator.of(context).pop(false),
                                child: const Text('Sí'),
                              ),
                            ],
                          );
                        },
                      ) ??
                      false;

                  if (confirmado) {
                    // bool result = await Provider.of<CorteCajaViewModel>(context,
                    //         listen: false)
                    //     .cancelarCorteCaja(item.id!);
                    // if (result) {
                    //   ScaffoldMessenger.of(context).showSnackBar(
                    //     SnackBar(
                    //         content: Text("CorteCaja cancelado correctamente")),
                    //   );
                    // } else {
                    //   ScaffoldMessenger.of(context).showSnackBar(
                    //     SnackBar(content: Text("Error al cancelar el CorteCaja")),
                    //   );
                    // }
                  }
                },
              )
            ],
            icon: const Icon(Icons.more_vert),
          ),
        ])),
        DataCell(
          Text(item.id.toString()),
          onTap: () => go(item),
        ),
        DataCell(
          Text(item.fecha ?? "Sin nombre"),
          onTap: () => go(item),
        ),
      ]));
    }

    return Scaffold(
      appBar: AppBar(
          title: Text(
            'Corte De Caja',
            style: TextStyle(color: AppTheme.quaternary),
          ),
          iconTheme: IconThemeData(color: AppTheme.quaternary)),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () async {
          await Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => CorteCajaForm(),
            ),
          ).then((_) => Provider.of<CorteCajaViewModel>(context, listen: false)
              .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.primary,
        foregroundColor: AppTheme.tertiary,
      ),
      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(
                            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("ID", style: estilo)),
                                    DataColumn(
                                        label: Text("FECHA", 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: 2,
            child: clase.tarjeta(
                ListTile(
                    title: Text(
                      "Fecha Inicial",
                      style: TextStyle(
                          color: AppTheme.quaternary,
                          fontWeight: FontWeight.bold),
                    ),
                    subtitle: Text(
                      fechaInicio == null
                          ? ""
                          : DateFormat("dd/MM/yyyy").format(fechaInicio!),
                      style: TextStyle(
                          color: AppTheme.quaternary,
                          fontWeight: FontWeight.bold),
                    ),
                    trailing:
                        Icon(Icons.calendar_month, color: AppTheme.quaternary),
                    onTap: () async {
                      DateTime? d = await clase.showDatetimePicker(
                          context, fechaInicio,
                          tipo: OmniDateTimePickerType.date, solofecha: true);
                      if (d == null) return;
                      setState(() {
                        fechaInicio = d;
                      });
                    }),
                color: AppTheme.primary)),
        const SizedBox(width: 5),
        Expanded(
            flex: 2,
            child: clase.tarjeta(
                ListTile(
                    title: Text(
                      "Fecha Final",
                      style: TextStyle(
                          color: AppTheme.quaternary,
                          fontWeight: FontWeight.bold),
                    ),
                    subtitle: Text(
                      fechaFin == null
                          ? ""
                          : DateFormat("dd/MM/yyyy").format(fechaFin!),
                      style: TextStyle(
                          color: AppTheme.quaternary,
                          fontWeight: FontWeight.bold),
                    ),
                    trailing:
                        Icon(Icons.calendar_month, color: AppTheme.quaternary),
                    onTap: () async {
                      DateTime? d = await clase.showDatetimePicker(
                          context, fechaInicio,
                          inicia: fechaInicio,
                          tipo: OmniDateTimePickerType.date,
                          solofecha: true);
                      if (d == null) return;
                      setState(() {
                        fechaFin = d;
                      });
                    }),
                color: AppTheme.primary)),
      ],
    );
  }

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