import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:turquessa_mesas_hoster/core/models/producto_model.dart';
import 'package:turquessa_mesas_hoster/mvvm/viewmodels/creacion_pedido_view_model.dart';
import 'package:turquessa_mesas_hoster/utils/themes.dart';
import 'package:turquessa_mesas_hoster/utils/widgets/custom_appbar.dart';
import 'package:turquessa_mesas_hoster/utils/widgets/custom_card.dart';
import 'package:turquessa_mesas_hoster/utils/widgets/navigation_rail.dart';

class CreacionPedido extends StatefulWidget {
  const CreacionPedido({super.key});

  @override
  State<CreacionPedido> createState() => _CreacionPedidoState();
}

class _CreacionPedidoState extends State<CreacionPedido> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  final _selectedIndex = 0;

  @override
  Widget build(BuildContext context) {
    CreacionPedidoViewModel creacionPedidoViewModel =
        Provider.of<CreacionPedidoViewModel>(context, listen: true);
    List<Producto> listaPedido = creacionPedidoViewModel.productosDisponibles;
    return Container(
      decoration: const BoxDecoration(
          gradient: LinearGradient(
              begin: Alignment.bottomRight,
              end: Alignment.topLeft,
              colors: [
            Color(0xFF7FD4D4),
            Color.fromARGB(255, 141, 225, 225),
            Color.fromARGB(255, 74, 156, 156),
          ])),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        appBar: AppBar(
          title: const CustomAppbar(),
        ),
        body: Row(
          children: [
            CustomNavigationRail(selectedIndex: _selectedIndex),
            Expanded(
              flex: 8,
              child: Container(
                decoration: const BoxDecoration(
                  color: Colors.white,
                ),
                child: const Column(
                  children: [
                    CategoryFilters(),
                    CategoryGrid(),
                  ],
                ),
              ),
            ),
            Expanded(
              flex: 4,
              child: Container(
                decoration: const BoxDecoration(
                  color: Colors.white,
                ),
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Padding(
                        padding: EdgeInsets.only(left: 10),
                        child: Text(
                          "Mesa 3: Palmeras",
                          textAlign: TextAlign.start,
                          style: TextStyle(
                              fontSize: 40,
                              fontWeight: FontWeight.bold,
                              color: Colors.black),
                        ),
                      ),
                      const Divider(),
                      // En el DataTable
                      SingleChildScrollView(
                        scrollDirection: Axis.horizontal,
                        child: SingleChildScrollView(
                          scrollDirection: Axis.vertical,
                          child: SizedBox(
                            width: double.infinity,
                            child: DataTable(
                              columnSpacing: 16,
                              horizontalMargin: 12,
                              headingRowHeight: 48,
                              columns: const <DataColumn>[
                                DataColumn(label: Text('Cant')),
                                DataColumn(label: Text('Nombre')),
                                DataColumn(label: Text('SubTotal')),
                                DataColumn(label: Text('Acciones')),
                              ],
                              rows: creacionPedidoViewModel
                                  .carrito // Aquí usamos la lista de carrito
                                  .map(
                                    (e) => DataRow(cells: [
                                      DataCell(
                                        Text(e.venta.toString()),
                                      ),
                                      DataCell(Text(e.nombre!)),
                                      DataCell(
                                        Text((e.precio! * e.venta!)
                                            .toStringAsFixed(2)),
                                      ),
                                      DataCell(IconButton(
                                        color: Colors.grey[600],
                                        icon: const Icon(Icons.edit),
                                        onPressed: () {
                                          creacionPedidoViewModel
                                              .eliminarDelCarrito(e);
                                        },
                                      )),
                                    ]),
                                  )
                                  .toList(),
                            ),
                          ),
                        ),
                      ),
                      Expanded(
                        child: Column(
                          children: [
                            const SizedBox(
                              height: 100,
                              width: double.infinity,
                            ),
                            const Divider(),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                const Text(
                                  "Total",
                                  style: TextStyle(
                                      fontSize: 20,
                                      fontWeight: FontWeight.bold),
                                ),
                                Text(
                                  "\$${creacionPedidoViewModel.calcularTotalCarrito().toStringAsFixed(2)}",
                                  style: const TextStyle(
                                      fontSize: 20,
                                      fontWeight: FontWeight.bold),
                                ),
                              ],
                            ),
                            const SizedBox(height: 10),
                            Row(
                              children: [
                                Expanded(
                                  flex: 9,
                                  child: ElevatedButton(
                                    style: const ButtonStyle(
                                      backgroundColor: MaterialStatePropertyAll(
                                          Colors.green),
                                    ),
                                    onPressed: () {},
                                    child: const Text(
                                      "Mandar a Preparacion",
                                      style: TextStyle(color: Colors.white),
                                    ),
                                  ),
                                ),
                                Expanded(
                                  flex: 1,
                                  child: IconButton(
                                    style: const ButtonStyle(
                                        backgroundColor:
                                            MaterialStatePropertyAll(
                                                Colors.white),
                                        iconColor: MaterialStatePropertyAll(
                                            Colors.red)),
                                    icon: const Icon(Icons.delete,
                                        color: Colors.red),
                                    onPressed: () {
                                      creacionPedidoViewModel.limpiarCarrito();
                                    },
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

class CategoryGrid extends StatelessWidget {
  const CategoryGrid({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    CreacionPedidoViewModel creacionPedidoViewModel =
        Provider.of<CreacionPedidoViewModel>(context);
    List<Producto> listaProductos =
        creacionPedidoViewModel.productosDisponibles;
    return Expanded(
      child: Container(
        padding: const EdgeInsets.all(8),
        child: GridView.builder(
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            crossAxisSpacing: 10,
            mainAxisSpacing: 15,
          ),
          itemCount: listaProductos.length,
          itemBuilder: (context, index) {
            int carritoIndex = creacionPedidoViewModel.carrito
                .indexWhere((p) => p.id == listaProductos[index].id);
            int cantidad = carritoIndex != -1
                ? creacionPedidoViewModel.carrito[carritoIndex].venta!
                : 0;

            return Card(
              shadowColor: Colors.grey.shade700,
              surfaceTintColor: Colors.white,
              child: Column(children: [
                Padding(
                  padding: const EdgeInsets.all(3),
                  child: Container(
                    height: 140,
                    width: double.infinity,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      image: DecorationImage(
                        image: NetworkImage(
                            "https://picsum.photos/200/300?random=$index"),
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                ),
                Center(
                  child: Text(
                    listaProductos[index].nombre ?? "Error",
                    style: const TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 16,
                        color: Colors.black),
                  ),
                ),
                Text(
                  "\$${listaProductos[index].precio}",
                  textAlign: TextAlign.left,
                  style: TextStyle(
                    color: Colors.green[600],
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const Spacer(),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 10),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      IconButton(
                          style: ButtonStyle(
                              backgroundColor:
                                  MaterialStatePropertyAll(AppTheme.primary)),
                          onPressed: () {
                            if (cantidad > 0) {
                              creacionPedidoViewModel
                                  .reducirDelCarrito(listaProductos[index]);
                            }
                          },
                          icon: const Icon(
                            Icons.remove,
                            color: Colors.black,
                          )),
                      Text(
                        "$cantidad",
                        style: const TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      IconButton(
                          style: ButtonStyle(
                              backgroundColor:
                                  MaterialStatePropertyAll(AppTheme.primary)),
                          onPressed: () {
                            creacionPedidoViewModel
                                .agregarAlCarrito(listaProductos[index]);
                          },
                          icon: const Icon(
                            Icons.add,
                            color: Colors.black,
                          )),
                    ],
                  ),
                )
              ]),
            );
          },
        ),
      ),
    );
  }
}

class CategoryFilters extends StatefulWidget {
  const CategoryFilters({super.key});

  @override
  State<CategoryFilters> createState() => CategoryFiltersState();
}

class CategoryFiltersState extends State<CategoryFilters> {
  int _selectedNavIndex = 0;

  @override
  void initState() {
    super.initState();
  }

  void _closeFilterView() {
    setState(() {
      _selectedNavIndex = 0;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(8),
      decoration: BoxDecoration(
        border: Border(bottom: BorderSide(color: Colors.grey.shade300)),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            children: [
              // Buscador
              Expanded(
                child: Container(
                  height: 40,
                  padding: const EdgeInsets.symmetric(horizontal: 12),
                  decoration: BoxDecoration(
                    color: Colors.grey.shade200,
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Row(
                    children: [
                      Icon(Icons.search, color: Colors.grey.shade600),
                      const SizedBox(width: 8),
                      Text('Buscar',
                          style: TextStyle(color: Colors.grey.shade600)),
                    ],
                  ),
                ),
              ),
              const SizedBox(width: 10),
              // Botones de filtro
              _buildFilterButton(1, 'Categoría'),
              const SizedBox(width: 10),
              _buildFilterButton(2, 'Topics'),
              const SizedBox(width: 10),
              _buildFilterButton(3, 'Extras'),
            ],
          ),
          const SizedBox(height: 5),
          if (_selectedNavIndex != 0)
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      _getFilterTitle(_selectedNavIndex),
                      style: const TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 16,
                      ),
                    ),
                    const Spacer(),
                    GestureDetector(
                      onTap: _closeFilterView,
                      child: Container(
                        padding: const EdgeInsets.all(4),
                        decoration: BoxDecoration(
                          color: Colors.grey.shade300,
                          shape: BoxShape.circle,
                        ),
                        child: Icon(
                          Icons.close,
                          size: 16,
                          color: Colors.grey.shade800,
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                SizedBox(
                  height: 80,
                  child: ListView.builder(
                    scrollDirection: Axis.horizontal,
                    itemCount: 10,
                    itemBuilder: (context, index) {
                      return Container(
                        margin: const EdgeInsets.only(right: 8),
                        padding: const EdgeInsets.symmetric(horizontal: 20),
                        decoration: BoxDecoration(
                          color: Colors.grey.shade200,
                          borderRadius: BorderRadius.circular(4),
                          border: Border.all(
                            color: Colors.grey.shade400,
                            width: 1,
                          ),
                        ),
                        child: Center(
                          child: Text(
                            '${_getFilterTitle(_selectedNavIndex)} $index',
                            style: const TextStyle(fontSize: 16),
                            textAlign: TextAlign.center,
                          ),
                        ),
                      );
                    },
                  ),
                ),
              ],
            )
        ],
      ),
    );
  }

  String _getFilterTitle(int index) {
    switch (index) {
      case 1:
        return 'Categorías';
      case 2:
        return 'Topics';
      case 3:
        return 'Extras';
      default:
        return '';
    }
  }

  Widget _buildFilterButton(int index, String text) {
    final bool isSelected = _selectedNavIndex == index;
    return GestureDetector(
      onTap: () {
        setState(() {
          if (_selectedNavIndex == index) {
            _selectedNavIndex = 0;
          } else {
            _selectedNavIndex = index;
          }
        });
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        decoration: BoxDecoration(
          color: isSelected ? Colors.blue.shade100 : Colors.grey.shade200,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(
            color: isSelected ? Colors.blue : Colors.transparent,
            width: 1,
          ),
        ),
        child: Row(
          children: [
            Text(
              text,
              style: TextStyle(
                color: isSelected ? Colors.blue.shade800 : Colors.grey.shade800,
                fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
              ),
            ),
            if (isSelected) ...[
              const SizedBox(width: 4),
              Icon(
                Icons.keyboard_arrow_down,
                size: 16,
                color: Colors.blue.shade800,
              ),
            ],
          ],
        ),
      ),
    );
  }
}
