import '../../widgets/widgets.dart';
import '../../themes/themes.dart';
import '../../viewmodels/viewmodels.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../models/models.dart';
import 'categoria_producto_form.dart';
import '../../widgets/widgets_components.dart' as clase;

class CategoriaProductoScreen extends StatefulWidget {
  @override
  _CategoriaProductoScreenState createState() =>
      _CategoriaProductoScreenState();
}

class _CategoriaProductoScreenState extends State<CategoriaProductoScreen> {
  final _busqueda = TextEditingController(text: '');
  ScrollController horizontalScrollController = ScrollController();
  int _versionTapCount = 0;

  @override
  void initState() {
    super.initState();
    final categoriaModel =
        Provider.of<CategoriaProductoViewModel>(context, listen: false);
    categoriaModel.fetchLocalAll();
  }

  void go(CategoriaProducto categoriaProducto) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) =>
            CategoriaProductoForm(categoriaProducto: categoriaProducto),
      ),
    ).then((_) =>
        Provider.of<CategoriaProductoViewModel>(context, listen: false)
            .fetchLocalAll());
  }

  void clearSearchAndReset() {
    setState(() {
      _busqueda.clear();
      Provider.of<CategoriaProductoViewModel>(context, listen: false)
          .fetchLocalAll();
    });
  }

  void _mostrarResultado(BuildContext context, String mensaje, bool exito) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(
              exito ? 'Sincronización exitosa' : 'Error de sincronización'),
          content: SingleChildScrollView(
            child: Text(mensaje), // Mostrar el mensaje completo de error aquí
          ),
          actions: [
            TextButton(
              child: Text('OK'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final model = Provider.of<CategoriaProductoViewModel>(context);
    final categoriasModel = Provider.of<CategoriaProductoViewModel>(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 (CategoriaProducto item in model.categoriaProductos) {
      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('Eliminar'),
                onTap: () async {
                  // Retrasa la ejecución para permitir que se cierre el menú popup.
                  await Future.delayed(Duration(milliseconds: 100));
                  bool confirmado = await showDialog<bool>(
                        context: context,
                        builder: (context) {
                          return AlertDialog(
                            title: const Text("Eliminar",
                                style: TextStyle(
                                    fontWeight: FontWeight.w500, fontSize: 22)),
                            content: const Text(
                                '¿Estás seguro de que deseas eliminar esta categoría?',
                                style: TextStyle(fontSize: 18)),
                            actions: [
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  TextButton(
                                    onPressed: () =>
                                        Navigator.of(context).pop(false),
                                    child: const Text('No',
                                        style: TextStyle(fontSize: 18)),
                                    style: ButtonStyle(
                                        padding: MaterialStatePropertyAll(
                                            EdgeInsets.fromLTRB(
                                                20, 10, 20, 10)),
                                        backgroundColor:
                                            MaterialStatePropertyAll(
                                                Colors.red),
                                        foregroundColor:
                                            MaterialStatePropertyAll(
                                                AppTheme.secondary)),
                                  ),
                                  TextButton(
                                    onPressed: () =>
                                        Navigator.of(context).pop(true),
                                    child: const Text('Sí',
                                        style: TextStyle(fontSize: 18)),
                                    style: ButtonStyle(
                                        padding: MaterialStatePropertyAll(
                                            EdgeInsets.fromLTRB(
                                                20, 10, 20, 10)),
                                        backgroundColor:
                                            MaterialStatePropertyAll(
                                                AppTheme.tertiary),
                                        foregroundColor:
                                            MaterialStatePropertyAll(
                                                AppTheme.quaternary)),
                                  ),
                                ],
                              )
                            ],
                          );
                        },
                      ) ??
                      false;

                  if (confirmado) {
                    await Provider.of<CategoriaProductoViewModel>(context,
                            listen: false)
                        .deleteCategoriaProducto(item.id);
                    Provider.of<CategoriaProductoViewModel>(context,
                            listen: false)
                        .fetchLocalAll();
                  }
                },
              )
            ],
            icon: const Icon(Icons.more_vert),
          ),
        ])),
        DataCell(
          Text(item.id.toString()),
          onTap: () {
            Provider.of<CategoriaProductoViewModel>(context, listen: false)
                .selectCategoriaProducto(item);
            go(item);
          },
        ),
        DataCell(
          Text(item.nombre.toString()),
          onTap: () {
            Provider.of<CategoriaProductoViewModel>(context, listen: false)
                .selectCategoriaProducto(item);
            go(item);
          },
        ),
      ]));
    }

    return Scaffold(
      appBar: AppBar(
        title: GestureDetector(
          onTap: () async {
            _versionTapCount++;
            if (_versionTapCount == 5) {
              final productoViewModel =
                  Provider.of<ProductoViewModel>(context, listen: false);

              try {
                await productoViewModel.sincronizarProductosYCategorias();
                _mostrarResultado(context,
                    'La sincronización se completó exitosamente.', true);
              } catch (e) {
                _mostrarResultado(context, e.toString(), false);
              }
              _versionTapCount = 0;
            }
          },
          child: Text(
            'Categoría Producto',
            style: TextStyle(
                color: AppTheme.secondary, fontWeight: FontWeight.w500),
          ),
        ),
        iconTheme: IconThemeData(color: AppTheme.secondary),
      ),
      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: busquedaTextField(),
                              ),
                              SizedBox(width: 5),
                              botonBuscar()
                            ],
                          );
                        } else {
                          return Column(
                            children: [
                              Row(
                                children: [busquedaTextField()],
                              ),
                              SizedBox(height: 15),
                              Row(
                                children: [botonBuscar()],
                              ),
                            ],
                          );
                        }
                      },
                    ),
                  ),
                ),
                const SizedBox(height: 8),
                model.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("NOMBRE", style: estilo)),
                                  ],
                                  rows: registros,
                                ),
                              ),
                            ),
                          ),
                        );
                      }),
                    ],
                  ),
                ),
                const SizedBox(
                  height: 15,
                ),
                if (!model.isLoading) ...[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      TextButton(
                        onPressed:
                            model.currentPage > 1 ? model.previousPage : null,
                        child: Text('Anterior'),
                        style: ButtonStyle(
                          backgroundColor:
                              MaterialStateProperty.resolveWith<Color?>(
                            (Set<MaterialState> states) {
                              if (states.contains(MaterialState.disabled)) {
                                return Colors.grey;
                              }
                              return AppTheme.tertiary;
                            },
                          ),
                          foregroundColor:
                              MaterialStateProperty.resolveWith<Color?>(
                            (Set<MaterialState> states) {
                              if (states.contains(MaterialState.disabled)) {
                                return Colors.black;
                              }
                              return Colors.white;
                            },
                          ),
                        ),
                      ),
                      SizedBox(width: 15),
                      Text(
                          'Página ${model.currentPage} de ${model.totalPages}'),
                      SizedBox(width: 15),
                      TextButton(
                        onPressed: model.currentPage < model.totalPages
                            ? model.nextPage
                            : null,
                        child: Text('Siguiente'),
                        style: ButtonStyle(
                          backgroundColor:
                              MaterialStateProperty.resolveWith<Color?>(
                            (Set<MaterialState> states) {
                              if (states.contains(MaterialState.disabled)) {
                                return Colors.grey;
                              }
                              return AppTheme.tertiary;
                            },
                          ),
                          foregroundColor:
                              MaterialStateProperty.resolveWith<Color?>(
                            (Set<MaterialState> states) {
                              if (states.contains(MaterialState.disabled)) {
                                return Colors.black;
                              }
                              return Colors.white;
                            },
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
                const SizedBox(
                  height: 15,
                ),
              ],
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () async {
          CategoriaProducto nuevoProducto = CategoriaProducto();
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) =>
                  CategoriaProductoForm(categoriaProducto: nuevoProducto),
            ),
          ).then((_) =>
              Provider.of<CategoriaProductoViewModel>(context, listen: false)
                  .fetchLocalAll());
        },
        icon: Icon(Icons.add, size: 30, color: AppTheme.quaternary),
        label: Text(
          "Agregar Categoria Producto",
          style: TextStyle(fontSize: 18, color: AppTheme.quaternary),
        ),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
        backgroundColor: AppTheme.tertiary,
      ),
    );
  }

  Widget busquedaTextField() {
    return Row(
      children: [
        Expanded(
          flex: 3,
          child: AppTextField(
            prefixIcon: const Icon(Icons.search),
            etiqueta: 'Búsqueda por nombre...',
            controller: _busqueda,
            hintText: 'Búsqueda por nombre...',
          ),
        ),
        const SizedBox(width: 5),
      ],
    );
  }

  Widget botonBuscar() {
    return Expanded(
        flex: 2,
        child: Row(
          children: [
            Expanded(
              flex: 2,
              child: Padding(
                padding: const EdgeInsets.only(top: 30),
                child: ElevatedButton(
                  onPressed: clearSearchAndReset,
                  style: ElevatedButton.styleFrom(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20.0),
                    ),
                    primary: AppTheme.tertiary,
                    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: 30),
                child: ElevatedButton(
                  onPressed: () async {
                    if (_busqueda.text.isNotEmpty) {
                      await Provider.of<CategoriaProductoViewModel>(context,
                              listen: false)
                          .fetchLocalByName(nombre: _busqueda.text.trim());
                    } else {
                      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
                          content: Text('Introduce un nombre para buscar.')));
                    }
                  },
                  style: ElevatedButton.styleFrom(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20.0),
                    ),
                    primary: AppTheme.tertiary,
                    padding: const EdgeInsets.symmetric(vertical: 25),
                  ),
                  child: Text('Buscar',
                      style: TextStyle(color: AppTheme.quaternary)),
                ),
              ),
            ),
          ],
        ));
  }
}
