import 'package:flutter/material.dart';
import 'package:youmazgestion/Models/client.dart';
import 'package:youmazgestion/Models/produit.dart';
import 'package:youmazgestion/Services/stock_managementDatabase.dart';


// Dialog pour sélectionner un cadeau
class GiftSelectionDialog extends StatefulWidget {
  final Commande commande;

  const GiftSelectionDialog({super.key, required this.commande});

  @override
  _GiftSelectionDialogState createState() => _GiftSelectionDialogState();
}

class _GiftSelectionDialogState extends State<GiftSelectionDialog> {
  List<Product> _products = [];
  List<Product> _filteredProducts = [];
  final _searchController = TextEditingController();
  Product? _selectedProduct;

  @override
  void initState() {
    super.initState();
    _loadProducts();
    _searchController.addListener(_filterProducts);
  }

  Future<void> _loadProducts() async {
    final products = await AppDatabase.instance.getProducts();
    setState(() {
      _products = products.where((p) => p.stock > 0).toList();
      _filteredProducts = _products;
    });
  }

  void _filterProducts() {
    final query = _searchController.text.toLowerCase();
    setState(() {
      _filteredProducts = _products.where((product) {
        return product.name.toLowerCase().contains(query) ||
               (product.reference?.toLowerCase().contains(query) ?? false) ||
               (product.category.toLowerCase().contains(query));
      }).toList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('Sélectionner un cadeau'),
      content: SizedBox(
        width: double.maxFinite,
        height: 400,
        child: Column(
          children: [
            TextField(
              controller: _searchController,
              decoration: const InputDecoration(
                labelText: 'Rechercher un produit',
                prefixIcon: Icon(Icons.search),
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 16),
            Expanded(
              child: ListView.builder(
                itemCount: _filteredProducts.length,
                itemBuilder: (context, index) {
                  final product = _filteredProducts[index];
                  return Card(
                    child: ListTile(
                      leading: product.image != null
                          ? Image.network(
                              product.image!,
                              width: 50,
                              height: 50,
                              fit: BoxFit.cover,
                              errorBuilder: (context, error, stackTrace) =>
                                  const Icon(Icons.image_not_supported),
                            )
                          : const Icon(Icons.phone_android),
                      title: Text(product.name),
                      subtitle: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('Catégorie: ${product.category}'),
                          Text('Stock: ${product.stock}'),
                          if (product.reference != null)
                            Text('Réf: ${product.reference}'),
                        ],
                      ),
                      trailing: Radio<Product>(
                        value: product,
                        groupValue: _selectedProduct,
                        onChanged: (value) {
                          setState(() {
                            _selectedProduct = value;
                          });
                        },
                      ),
                      onTap: () {
                        setState(() {
                          _selectedProduct = product;
                        });
                      },
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('Annuler'),
        ),
        ElevatedButton(
          onPressed: _selectedProduct != null
              ? () => Navigator.pop(context, _selectedProduct)
              : null,
          child: const Text('Ajouter le cadeau'),
        ),
      ],
    );
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }
}
