import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:em2rp/models/equipment_model.dart';
import 'package:em2rp/providers/equipment_provider.dart';
import 'package:em2rp/utils/colors.dart';

/// Dialogue pour le restock d'un équipement consommable
class RestockDialog extends StatefulWidget {
  final EquipmentModel equipment;

  const RestockDialog({
    super.key,
    required this.equipment,
  });

  @override
  State<RestockDialog> createState() => _RestockDialogState();

  /// Méthode statique pour afficher le dialogue
  static Future<void> show(BuildContext context, EquipmentModel equipment) {
    return showDialog(
      context: context,
      builder: (context) => RestockDialog(equipment: equipment),
    );
  }
}

class _RestockDialogState extends State<RestockDialog> {
  final TextEditingController _quantityController = TextEditingController();
  bool _addToTotal = false;

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

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Row(
        children: [
          const Icon(Icons.add_shopping_cart, color: AppColors.rouge),
          const SizedBox(width: 12),
          Expanded(
            child: Text('Restock - ${widget.equipment.name}'),
          ),
        ],
      ),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Quantités actuelles
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.grey[100],
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'Quantités actuelles',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.grey[700],
                    ),
                  ),
                  const SizedBox(height: 8),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const Text('Disponible:'),
                      Text(
                        '${widget.equipment.availableQuantity ?? 0}',
                        style: const TextStyle(fontWeight: FontWeight.bold),
                      ),
                    ],
                  ),
                  const SizedBox(height: 4),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const Text('Total:'),
                      Text(
                        '${widget.equipment.totalQuantity ?? 0}',
                        style: const TextStyle(fontWeight: FontWeight.bold),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            const SizedBox(height: 20),
            // Champ de saisie
            TextField(
              controller: _quantityController,
              decoration: const InputDecoration(
                labelText: 'Quantité à ajouter/retirer',
                border: OutlineInputBorder(),
                prefixIcon: Icon(Icons.inventory),
                hintText: 'Ex: 10 ou -5',
                helperText: 'Nombre positif pour ajouter, négatif pour retirer',
              ),
              keyboardType: const TextInputType.numberWithOptions(signed: true),
              autofocus: true,
            ),
            const SizedBox(height: 16),
            // Checkbox pour ajouter au total
            StatefulBuilder(
              builder: (context, setState) {
                return CheckboxListTile(
                  title: const Text('Ajouter à la quantité totale'),
                  subtitle: const Text('Mettre à jour aussi la quantité totale'),
                  value: _addToTotal,
                  contentPadding: EdgeInsets.zero,
                  onChanged: (bool? value) {
                    setState(() {
                      _addToTotal = value ?? false;
                    });
                    // Update parent state as well
                    this.setState(() {
                      _addToTotal = value ?? false;
                    });
                  },
                );
              },
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('Annuler'),
        ),
        ElevatedButton(
          onPressed: () => _handleRestock(context),
          style: ElevatedButton.styleFrom(
            backgroundColor: AppColors.rouge,
            foregroundColor: Colors.white,
          ),
          child: const Text('Valider'),
        ),
      ],
    );
  }

  Future<void> _handleRestock(BuildContext context) async {
    final quantityText = _quantityController.text.trim();

    if (quantityText.isEmpty) {
      _showError(context, 'Veuillez entrer une quantité');
      return;
    }

    final quantity = int.tryParse(quantityText);
    if (quantity == null) {
      _showError(context, 'Quantité invalide');
      return;
    }

    Navigator.pop(context);

    try {
      final currentAvailable = widget.equipment.availableQuantity ?? 0;
      final currentTotal = widget.equipment.totalQuantity ?? 0;

      final newAvailable = currentAvailable + quantity;
      final newTotal = _addToTotal ? currentTotal + quantity : currentTotal;

      if (newAvailable < 0) {
        _showError(context, 'La quantité disponible ne peut pas être négative');
        return;
      }

      if (newTotal < 0) {
        _showError(context, 'La quantité totale ne peut pas être négative');
        return;
      }

      final updatedData = {
        'availableQuantity': newAvailable,
        'totalQuantity': newTotal,
        'updatedAt': DateTime.now().toIso8601String(),
      };

      if (context.mounted) {
        final updatedEquipment = widget.equipment.copyWith(
          availableQuantity: newAvailable,
          totalQuantity: newTotal,
          updatedAt: DateTime.now(),
        );

        await context.read<EquipmentProvider>().updateEquipment(updatedEquipment);

        if (context.mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(
                quantity > 0
                    ? 'Ajout de $quantity unité(s) effectué'
                    : 'Retrait de ${quantity.abs()} unité(s) effectué',
              ),
              backgroundColor: Colors.green,
            ),
          );
        }
      }
    } catch (e) {
      if (context.mounted) {
        _showError(context, 'Erreur: $e');
      }
    }
  }

  void _showError(BuildContext context, String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message)),
    );
  }
}

