import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:em2rp/utils/price_helpers.dart';

/// Widget pour gérer les prix HT et TTC avec calcul automatique
/// Permet de saisir soit le prix HT, soit le prix TTC, l'autre est calculé automatiquement
class PriceHtTtcFields extends StatefulWidget {
  final TextEditingController basePriceController;
  final VoidCallback onPriceChanged;
  final double taxRate;
  final List<Map<String, dynamic>> selectedOptions;

  const PriceHtTtcFields({
    super.key,
    required this.basePriceController,
    required this.onPriceChanged,
    this.taxRate = 0.20,
    this.selectedOptions = const [],
  });

  @override
  State<PriceHtTtcFields> createState() => _PriceHtTtcFieldsState();
}

class _PriceHtTtcFieldsState extends State<PriceHtTtcFields> {
  final TextEditingController _htController = TextEditingController();
  final TextEditingController _ttcController = TextEditingController();
  bool _updatingFromHT = false;
  bool _updatingFromTTC = false;

  @override
  void initState() {
    super.initState();
    // Initialiser avec la valeur existante (considérée comme TTC)
    if (widget.basePriceController.text.isNotEmpty) {
      _ttcController.text = widget.basePriceController.text;
      _updateHTFromTTC();
    }

    // Synchroniser basePriceController avec TTC
    _htController.addListener(_onHTChanged);
    _ttcController.addListener(_onTTCChanged);

    // Écouter les changements externes du basePriceController (ex: changement de type d'événement)
    widget.basePriceController.addListener(_onBasePriceControllerChanged);
  }

  @override
  void dispose() {
    _htController.removeListener(_onHTChanged);
    _ttcController.removeListener(_onTTCChanged);
    widget.basePriceController.removeListener(_onBasePriceControllerChanged);
    _htController.dispose();
    _ttcController.dispose();
    super.dispose();
  }

  /// Appelé quand basePriceController change de l'extérieur (ex: sélection type d'événement)
  void _onBasePriceControllerChanged() {
    // Éviter la boucle infinie si le changement vient de nous
    if (_updatingFromHT || _updatingFromTTC) return;

    final newTTCText = widget.basePriceController.text;

    // Si le texte est différent de ce qu'on a dans _ttcController, mettre à jour
    if (newTTCText != _ttcController.text) {
      _ttcController.text = newTTCText;
      if (newTTCText.isNotEmpty) {
        _updateHTFromTTC();
      } else {
        _htController.clear();
      }
    }
  }

  void _onHTChanged() {
    if (_updatingFromTTC) return;

    final htText = _htController.text.replaceAll(',', '.');
    final htValue = double.tryParse(htText);

    if (htValue != null) {
      _updatingFromHT = true;
      final ttcValue = PriceHelpers.calculateTTC(htValue, taxRate: widget.taxRate);
      _ttcController.text = ttcValue.toStringAsFixed(2);

      // Mettre à jour basePriceController (qui stocke le prix TTC)
      widget.basePriceController.text = ttcValue.toStringAsFixed(2);
      widget.onPriceChanged();

      _updatingFromHT = false;
    } else if (htText.isEmpty) {
      _ttcController.clear();
      widget.basePriceController.clear();
      widget.onPriceChanged();
    }
  }

  void _onTTCChanged() {
    if (_updatingFromHT) return;

    final ttcText = _ttcController.text.replaceAll(',', '.');
    final ttcValue = double.tryParse(ttcText);

    if (ttcValue != null) {
      _updatingFromTTC = true;
      final htValue = PriceHelpers.calculateHT(ttcValue, taxRate: widget.taxRate);
      _htController.text = htValue.toStringAsFixed(2);

      // Mettre à jour basePriceController (qui stocke le prix TTC)
      widget.basePriceController.text = ttcValue.toStringAsFixed(2);
      widget.onPriceChanged();

      _updatingFromTTC = false;
    } else if (ttcText.isEmpty) {
      _htController.clear();
      widget.basePriceController.clear();
      widget.onPriceChanged();
    }
  }

  void _updateHTFromTTC() {
    final ttcText = _ttcController.text.replaceAll(',', '.');
    final ttcValue = double.tryParse(ttcText);

    if (ttcValue != null) {
      final htValue = PriceHelpers.calculateHT(ttcValue, taxRate: widget.taxRate);
      _htController.text = htValue.toStringAsFixed(2);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          'Prix Base',
          style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
        ),
        const SizedBox(height: 8),
        Row(
          children: [
            // Champ Prix HT
            Expanded(
              child: TextFormField(
                controller: _htController,
                decoration: InputDecoration(
                  labelText: 'Prix HT (€)*',
                  border: const OutlineInputBorder(),
                  prefixIcon: const Icon(Icons.euro),
                  hintText: '1000.00',
                  helperText: 'Hors taxes',
                  helperStyle: TextStyle(
                    fontSize: 11,
                    color: Colors.grey[600],
                  ),
                ),
                keyboardType: const TextInputType.numberWithOptions(decimal: true),
                inputFormatters: [
                  FilteringTextInputFormatter.allow(RegExp(r'^\d*\.?\d{0,2}')),
                ],
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Requis';
                  }
                  final price = double.tryParse(value.replaceAll(',', '.'));
                  if (price == null) {
                    return 'Nombre invalide';
                  }
                  return null;
                },
              ),
            ),
            const SizedBox(width: 16),
            // Champ Prix TTC
            Expanded(
              child: TextFormField(
                controller: _ttcController,
                decoration: InputDecoration(
                  labelText: 'Prix TTC (€)*',
                  border: const OutlineInputBorder(),
                  prefixIcon: const Icon(Icons.attach_money),
                  hintText: '1200.00',
                  helperText: 'Toutes taxes comprises',
                  helperStyle: TextStyle(
                    fontSize: 11,
                    color: Colors.grey[600],
                  ),
                ),
                keyboardType: const TextInputType.numberWithOptions(decimal: true),
                inputFormatters: [
                  FilteringTextInputFormatter.allow(RegExp(r'^\d*\.?\d{0,2}')),
                ],
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Requis';
                  }
                  final price = double.tryParse(value.replaceAll(',', '.'));
                  if (price == null) {
                    return 'Nombre invalide';
                  }
                  return null;
                },
              ),
            ),
          ],
        ),
        const SizedBox(height: 4),
        // Affichage du montant de TVA (en plus petit) et du Prix Total
        Builder(
          builder: (context) {
            final htText = _htController.text.replaceAll(',', '.');
            final htValue = double.tryParse(htText);

            if (htValue != null) {
              final taxAmount = PriceHelpers.calculateTax(htValue, taxRate: widget.taxRate);
              final ttcValue = PriceHelpers.calculateTTC(htValue, taxRate: widget.taxRate);
              
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.only(left: 8.0, top: 4.0),
                    child: Text(
                      'TVA (${(widget.taxRate * 100).toStringAsFixed(0)}%) : ${taxAmount.toStringAsFixed(2)} €',
                      style: TextStyle(
                        fontSize: 11,
                        color: Colors.grey[600],
                        fontStyle: FontStyle.italic,
                      ),
                    ),
                  ),
                  if (widget.selectedOptions.isNotEmpty) ...[
                    const SizedBox(height: 16),
                    Builder(
                      builder: (context) {
                        double optionsTotalTTC = 0.0;
                        for (var opt in widget.selectedOptions) {
                          // Les options sont stockées en TTC ou HT ?
                          // Généralement l'application utilise TTC.
                          final optPrice = opt['price'] is double ? opt['price'] : double.tryParse(opt['price'].toString()) ?? 0.0;
                          final optQuantity = opt['quantity'] is int ? opt['quantity'] : int.tryParse(opt['quantity'].toString()) ?? 1;
                          optionsTotalTTC += optPrice * optQuantity;
                        }
                        
                        final totalTTC = ttcValue + optionsTotalTTC;
                        final totalHT = PriceHelpers.calculateHT(totalTTC, taxRate: widget.taxRate);

                        return Container(
                          padding: const EdgeInsets.all(12),
                          decoration: BoxDecoration(
                            color: Colors.blue.shade50,
                            borderRadius: BorderRadius.circular(8),
                            border: Border.all(color: Colors.blue.shade100),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              const Text(
                                'Prix Total (Base + Options)',
                                style: TextStyle(fontWeight: FontWeight.bold),
                              ),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: [
                                  Text(
                                    '${totalHT.toStringAsFixed(2)} € HT',
                                    style: TextStyle(fontSize: 14, color: Colors.blue.shade800),
                                  ),
                                  Text(
                                    '${totalTTC.toStringAsFixed(2)} € TTC',
                                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.blue.shade900),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        );
                      }
                    ),
                  ],
                ],
              );
            }
            return const SizedBox.shrink();
          },
        ),
      ],
    );
  }
}

