// ignore_for_file: must_be_immutable

import 'package:flutter/material.dart';
import '/views/categoria_producto/categoria_producto_screen.dart';
import '/views/mesa/mesa_screen.dart';
import '/views/pedido/pedido_screen.dart';
import '/views/producto/producto_screen.dart';
import '/views/sucursal/sucursal_screen.dart';
import '/views/variable/variable_screen.dart';
import '/views/venta/venta_screen.dart';
import 'package:provider/provider.dart';
import '../models/models.dart';
import '../services/services.dart';
import '../themes/themes.dart';
import '../viewmodels/login_view_model.dart';
import '../viewmodels/viewmodels.dart';
import '../views/corte_caja/corte_caja_screen.dart';
import '../views/descuento/descuento_screen.dart';
import 'widgets_components.dart';

class AppDrawer extends StatelessWidget {
  AppDrawer({super.key});

  Future<bool> _showExitConfirmationDialog(BuildContext context) async {
    bool shouldPop = false;
    await showDialog(
      context: context,
      builder: (context) => AlertDialog(
        surfaceTintColor: AppTheme.secondary,
        title: const Text('¿Cerrar sesión?'),
        content: const Text('¿Estás seguro de que quieres cerrar la sesión?'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('Cancelar', style: TextStyle(color: Colors.red)),
          ),
          TextButton(
            onPressed: () async {
              Provider.of<LoginViewModel>(context, listen: false).logOut();
              Navigator.of(context).pushNamedAndRemoveUntil(
                'login',
                (route) => false,
              );
            },
            child: const Text('Aceptar'),
          ),
        ],
      ),
    );
    return shouldPop;
  }

  @override
  Widget build(BuildContext context) {
    final permisoViewModel = Provider.of<PermisoViewModel>(context);
    List<String> userPermisos = permisoViewModel.userPermisos;
    BaseService baseService = BaseService(); // Instancia de BaseService
    String prefijoVersion = baseService.prefijoVersion();
    return Drawer(
      surfaceTintColor: Colors.white,
      backgroundColor: Colors.white,
      child: Column(
        children: [
          Container(
            width: double.infinity,
            decoration: BoxDecoration(
              color: AppTheme.primary,
            ),
            padding: EdgeInsets.only(
              top: MediaQuery.of(context).padding.top,
            ),
            child: const Column(
              children: [
                Padding(
                  padding: EdgeInsets.all(8.0),
                  child: Image(
                    image: AssetImage('assets/logo-BN.png'),
                    height: 150,
                  ),
                ),
                SizedBox(
                  height: 10,
                ),
                SizedBox(
                  height: 10,
                ),
              ],
            ),
          ),
          // HEADER
          Expanded(
            child: ListView(
              children: [
                ListTile(
                  leading: circulo(const Icon(Icons.restaurant_menu)),
                  title: const Text('Pedidos'),
                  onTap: () => {
                    Navigator.pop(context),
                    Navigator.of(context).push(
                      MaterialPageRoute(
                        builder: (context) => const PedidoScreen(),
                      ),
                    ),
                  },
                ),
                ListTile(
                  leading: circulo(const Icon(Icons.point_of_sale)),
                  title: const Text('Corte de caja'),
                  onTap: () => {
                    Navigator.pop(context),
                    Navigator.of(context).push(
                      MaterialPageRoute(
                        builder: (context) => CorteCajaScreen(),
                      ),
                    ),
                  },
                ),
                ListTile(
                  leading: circulo(const Icon(Icons.menu_book_rounded)),
                  title: const Text('Productos'),
                  onTap: () => {
                    Navigator.pop(context),
                    Navigator.of(context).push(
                      MaterialPageRoute(
                        builder: (context) => ProductoScreen(),
                      ),
                    ),
                  },
                ),
                if (userPermisos.contains(Usuario.VER_CATEGORIAS))
                  ListTile(
                    leading:
                        circulo(const Icon(Icons.format_list_bulleted_rounded)),
                    title: const Text('Categoría Producto'),
                    onTap: () => {
                      Navigator.pop(context),
                      Navigator.of(context).push(
                        MaterialPageRoute(
                          builder: (context) => CategoriaProductoScreen(),
                        ),
                      ),
                    },
                  ),
                ListTile(
                  leading: circulo(const Icon(Icons.receipt_long_outlined)),
                  title: const Text('Pedidos Por Día'),
                  onTap: () => {
                    Navigator.pop(context),
                    Navigator.of(context).push(
                      MaterialPageRoute(
                        builder: (context) => VentaScreen(),
                      ),
                    ),
                  },
                ),
                if (userPermisos.contains(Usuario.VER_ADMIN))
                  ExpansionTile(
                    leading: circulo(const Icon(Icons.admin_panel_settings)),
                    title: const Text('Administración'),
                    children: [
                      ListTile(
                        leading: circulo(const Icon(Icons.discount)),
                        title: const Text('Descuentos'),
                        onTap: () => {
                          Navigator.pop(context),
                          Navigator.of(context).push(
                            MaterialPageRoute(
                              builder: (context) => DescuentoScreen(),
                            ),
                          ),
                        },
                      ),
                      ListTile(
                        leading: circulo(const Icon(Icons.discount)),
                        title: const Text('Variables'),
                        onTap: () => {
                          Navigator.pop(context),
                          Navigator.of(context).push(
                            MaterialPageRoute(
                              builder: (context) => VariablesScreen(),
                            ),
                          ),
                        },
                      ),
                      ListTile(
                        leading: circulo(const Icon(Icons.table_bar)),
                        title: const Text('Mesas'),
                        onTap: () => {
                          Navigator.pop(context),
                          Navigator.of(context).push(
                            MaterialPageRoute(
                              builder: (context) => MesasScreen(),
                            ),
                          ),
                        },
                      ),
                      if (userPermisos.contains(Usuario.VER_SUCURSALES))
                        ListTile(
                          leading:
                              circulo(const Icon(Icons.storefront_outlined)),
                          title: const Text('Sucursales'),
                          onTap: () => {
                            Navigator.pop(context),
                            Navigator.of(context).push(
                              MaterialPageRoute(
                                builder: (context) => SucursalesPage(),
                              ),
                            ),
                          },
                        ),
                      if (userPermisos.contains(Usuario.FORZAR_SINCRONIZACION))
                        ListTile(
                          leading: circulo(const Icon(Icons.sync)),
                          title: const Text('Forzar Sincronización'),
                          onTap: () async {
                            bool confirmado = await showDialog(
                                  context: context,
                                  builder: (context) {
                                    return AlertDialog(
                                      title: const Text("Forzar Sincronización",
                                          style: TextStyle(
                                              fontWeight: FontWeight.w500,
                                              fontSize: 22)),
                                      content: const Text(
                                          '¿Estás seguro de que deseas forzar la sincronización?',
                                          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:
                                                    MaterialStateProperty.all(
                                                        EdgeInsets.fromLTRB(
                                                            20, 10, 20, 10)),
                                                backgroundColor:
                                                    MaterialStateProperty.all(
                                                        Colors.red),
                                                foregroundColor:
                                                    MaterialStateProperty.all(
                                                        AppTheme.secondary),
                                              ),
                                            ),
                                            TextButton(
                                              onPressed: () =>
                                                  Navigator.of(context)
                                                      .pop(true),
                                              child: const Text('Sí',
                                                  style:
                                                      TextStyle(fontSize: 18)),
                                              style: ButtonStyle(
                                                padding:
                                                    MaterialStateProperty.all(
                                                        EdgeInsets.fromLTRB(
                                                            20, 10, 20, 10)),
                                                backgroundColor:
                                                    MaterialStateProperty.all(
                                                        AppTheme.tertiary),
                                                foregroundColor:
                                                    MaterialStateProperty.all(
                                                        AppTheme.quaternary),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ],
                                    );
                                  },
                                ) ??
                                false;

                            if (confirmado) {
                              showDialog(
                                context: context,
                                barrierDismissible: false,
                                builder: (context) => AlertDialog(
                                  title: const Text("Sincronizando",
                                      style: TextStyle(
                                          fontWeight: FontWeight.w500,
                                          fontSize: 22)),
                                  content: Padding(
                                    padding:
                                        const EdgeInsetsDirectional.symmetric(
                                            horizontal: 120),
                                    child: const CircularProgressIndicator(),
                                  ),
                                ),
                              );

                              try {
                                await RepoService().forzarSincronizacion();

                                Navigator.of(context, rootNavigator: true)
                                    .pop();
                                Navigator.of(context).pop();

                                ScaffoldMessenger.of(context).showSnackBar(
                                  SnackBar(
                                    content: const Text(
                                        'Sincronización completada con éxito'),
                                    backgroundColor: Colors.green,
                                  ),
                                );
                              } catch (e) {
                                Navigator.of(context, rootNavigator: true)
                                    .pop();
                                Navigator.of(context).pop();

                                ScaffoldMessenger.of(context).showSnackBar(
                                  SnackBar(
                                    content:
                                        Text('Error en la sincronización: $e'),
                                    backgroundColor: Colors.red,
                                  ),
                                );
                              }
                            }
                          },
                        ),
                    ],
                  ),
                ListTile(
                  leading: const Icon(Icons.logout),
                  title: const Text('Cerrar sesión'),
                  onTap: () {
                    _showExitConfirmationDialog(context);
                  },
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(bottom: 10),
            child: Align(
              alignment: Alignment.bottomCenter,
              child: Text(
                '$prefijoVersion.1.25.01.24',
                style: const TextStyle(fontWeight: FontWeight.w300),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
