import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:youmazgestion/Components/app_bar.dart';
import 'package:youmazgestion/Services/stock_managementDatabase.dart';
import '../Components/appDrawer.dart';
import '../Models/produit.dart';
// import '../Services/productDatabase.dart';
import 'editProduct.dart';
import 'dart:io';

class GestionProduit extends StatelessWidget {
  final AppDatabase _productDatabase = AppDatabase.instance;

  GestionProduit({super.key});

  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width * 0.8;

    return Scaffold(
      appBar: CustomAppBar(title: 'Gestion des produits'),
      drawer: CustomDrawer(),
      body: FutureBuilder<List<Product>>(
        future: _productDatabase.getProducts(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }

          if (snapshot.hasError) {
            return const Center(child: Text('Une erreur s\'est produite'));
          }

          final products = snapshot.data;

          if (products == null || products.isEmpty) {
            return const Center(child: Text('Aucun produit disponible'));
          }

          return ListView.builder(
            itemCount: products.length,
            itemBuilder: (context, index) {
              final product = products[index];
              return Container(
                width: screenWidth,
                margin: const EdgeInsets.symmetric(vertical: 2, horizontal: 20),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(30),
                  border: Border.all(color: Colors.grey, width: 1.0),
                ),
                child: ListTile(
                  leading: _buildProductImage(product.image),
                  title: Text(product.name),
                  subtitle: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('Prix: \$${product.price.toStringAsFixed(2)}'),
                      Text('Catégorie: ${product.category}'),
                      if (product.stock != null)
                        Text('Stock: ${product.stock}'),
                    ],
                  ),
                  trailing: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      IconButton(
                        onPressed: () => _deleteProduct(product.id),
                        icon: const Icon(Icons.delete),
                        color: Colors.red,
                      ),
                      IconButton(
                        onPressed: () => _editProduct(product),
                        icon: const Icon(Icons.edit),
                        color: Colors.blue,
                      ),
                    ],
                  ),
                ),
              );
            },
          );
        },
      ),
    );
  }

  Widget _buildProductImage(String? imagePath) {
    if (imagePath != null &&
        imagePath.isNotEmpty &&
        File(imagePath).existsSync()) {
      return CircleAvatar(
        backgroundImage: FileImage(File(imagePath)),
      );
    } else {
      return const CircleAvatar(
        backgroundColor: Colors.grey,
        child: Icon(Icons.shopping_bag, color: Colors.white),
      );
    }
  }

  void _deleteProduct(int? id) {
    _productDatabase.deleteProduct(id).then((value) {
      Get.snackbar(
        'Produit supprimé',
        'Le produit a été supprimé avec succès',
        snackPosition: SnackPosition.TOP,
        duration: const Duration(seconds: 3),
        backgroundColor: Colors.green,
        colorText: Colors.white,
      );
    });
  }

  void _editProduct(Product product) {
    Get.to(() => EditProductPage(product: product))?.then((result) {
      if (result != null && result is Product) {
        _productDatabase.updateProduct(result).then((value) {
          Get.snackbar(
            'Produit mis à jour',
            'Le produit a été mis à jour avec succès',
            snackPosition: SnackPosition.TOP,
            duration: const Duration(seconds: 3),
            backgroundColor: Colors.green,
            colorText: Colors.white,
          );
        });
      }
    });
  }
}
