import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:em2rp/models/route_result_model.dart';
import 'package:em2rp/services/travel_service.dart';
import 'package:em2rp/utils/colors.dart';

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

  @override
  State<FuelPricesManagement> createState() => _FuelPricesManagementState();
}

class _FuelPricesManagementState extends State<FuelPricesManagement> {
  final _service = TravelService();
  final _formKey = GlobalKey<FormState>();
  final _dieselCtrl = TextEditingController();
  final _essenceCtrl = TextEditingController();
  final _electriqueCtrl = TextEditingController();
  bool _isLoading = true;
  bool _isSaving = false;

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

  Future<void> _load() async {
    setState(() => _isLoading = true);
    final prices = await _service.getFuelPrices();
    _dieselCtrl.text = prices.diesel.toStringAsFixed(3);
    _essenceCtrl.text = prices.essence.toStringAsFixed(3);
    _electriqueCtrl.text = prices.electricite.toStringAsFixed(3);
    if (mounted) setState(() => _isLoading = false);
  }

  Future<void> _save() async {
    if (!_formKey.currentState!.validate()) return;
    setState(() => _isSaving = true);
    try {
      final prices = FuelPrices(
        diesel: double.parse(_dieselCtrl.text.trim()),
        essence: double.parse(_essenceCtrl.text.trim()),
        electricite: double.parse(_electriqueCtrl.text.trim()),
      );
      await _service.saveFuelPrices(prices);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Prix mis à jour ✓'),
            backgroundColor: Colors.green,
            duration: Duration(seconds: 2),
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Erreur: $e'), backgroundColor: Colors.red),
        );
      }
    } finally {
      if (mounted) setState(() => _isSaving = false);
    }
  }

  @override
  void dispose() {
    _dieselCtrl.dispose();
    _essenceCtrl.dispose();
    _electriqueCtrl.dispose();
    super.dispose();
  }

  Widget _buildPriceField({
    required TextEditingController controller,
    required String label,
    required String unit,
    required IconData icon,
    required Color color,
  }) {
    return Row(
      children: [
        CircleAvatar(
          backgroundColor: color.withValues(alpha: 0.1),
          child: Icon(icon, color: color),
        ),
        const SizedBox(width: 16),
        Expanded(
          child: TextFormField(
            controller: controller,
            decoration: InputDecoration(
              labelText: label,
              border: const OutlineInputBorder(),
              suffixText: unit,
            ),
            keyboardType: const TextInputType.numberWithOptions(decimal: true),
            inputFormatters: [
              FilteringTextInputFormatter.allow(RegExp(r'^\d+\.?\d{0,3}'))
            ],
            validator: (v) {
              if (v == null || v.isEmpty) return 'Requis';
              final parsed = double.tryParse(v);
              if (parsed == null || parsed <= 0) return 'Valeur invalide';
              return null;
            },
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(Icons.local_gas_station, color: AppColors.rouge, size: 28),
              const SizedBox(width: 12),
              Text(
                'Prix des carburants',
                style: Theme.of(context)
                    .textTheme
                    .headlineSmall
                    ?.copyWith(fontWeight: FontWeight.bold),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Text(
            'Ces prix sont utilisés pour calculer automatiquement le coût en carburant des déplacements.',
            style: Theme.of(context)
                .textTheme
                .bodyMedium
                ?.copyWith(color: Colors.grey[600]),
          ),
          const SizedBox(height: 32),
          if (_isLoading)
            const Center(child: CircularProgressIndicator())
          else
            Form(
              key: _formKey,
              child: Column(
                children: [
                  _buildPriceField(
                    controller: _dieselCtrl,
                    label: 'Prix du Diesel',
                    unit: '€/L',
                    icon: Icons.local_gas_station,
                    color: Colors.blue,
                  ),
                  const SizedBox(height: 20),
                  _buildPriceField(
                    controller: _essenceCtrl,
                    label: 'Prix de l\'Essence',
                    unit: '€/L',
                    icon: Icons.local_gas_station,
                    color: Colors.orange,
                  ),
                  const SizedBox(height: 20),
                  _buildPriceField(
                    controller: _electriqueCtrl,
                    label: 'Prix de l\'Électricité',
                    unit: '€/kWh',
                    icon: Icons.electric_bolt,
                    color: Colors.amber,
                  ),
                  const SizedBox(height: 32),
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton.icon(
                      icon: _isSaving
                          ? const SizedBox(
                              width: 18,
                              height: 18,
                              child: CircularProgressIndicator(
                                  strokeWidth: 2, color: Colors.white),
                            )
                          : const Icon(Icons.save_outlined),
                      label: Text(_isSaving ? 'Enregistrement...' : 'Enregistrer les prix'),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppColors.rouge,
                        foregroundColor: Colors.white,
                        padding: const EdgeInsets.symmetric(vertical: 14),
                      ),
                      onPressed: _isSaving ? null : _save,
                    ),
                  ),
                ],
              ),
            ),
        ],
      ),
    );
  }
}
