import 'package:flutter/material.dart';
import 'package:em2rp/models/event_type_model.dart';
import 'package:em2rp/utils/colors.dart';
import 'package:intl/intl.dart';
import 'package:em2rp/services/data_service.dart';
import 'package:em2rp/services/api_service.dart';

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

  @override
  State<EventTypesManagement> createState() => _EventTypesManagementState();
}

class _EventTypesManagementState extends State<EventTypesManagement> {
  String _searchQuery = '';
  List<EventTypeModel> _eventTypes = [];
  bool _loading = true;
  late final DataService _dataService;

  @override
  void initState() {
    super.initState();
    _dataService = DataService(FirebaseFunctionsApiService());
    _loadEventTypes();
  }

  Future<void> _loadEventTypes() async {
    setState(() => _loading = true);
    try {
      final eventTypesData = await _dataService.getEventTypes();

      // Trier par nom
      eventTypesData.sort((a, b) =>
        (a['name'] as String).compareTo(b['name'] as String));

      setState(() {
        _eventTypes = eventTypesData
            .map((data) => EventTypeModel.fromMap(data, data['id'] as String))
            .toList();
        _loading = false;
      });
    } catch (e) {
      setState(() => _loading = false);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Erreur lors du chargement : $e')),
        );
      }
    }
  }

  List<EventTypeModel> get _filteredEventTypes {
    if (_searchQuery.isEmpty) return _eventTypes;
    return _eventTypes.where((type) =>
        type.name.toLowerCase().contains(_searchQuery.toLowerCase())
    ).toList();
  }

  Future<bool> _canDeleteEventType(String eventTypeId) async {
    try {
      final events = await _dataService.getEventsByEventType(eventTypeId);
      return events.isEmpty;
    } catch (e) {
      return false;
    }
  }

  Future<List<Map<String, dynamic>>> _getBlockingEvents(String eventTypeId) async {
    try {
      final events = await _dataService.getEventsByEventType(eventTypeId);
      final now = DateTime.now();
      List<Map<String, dynamic>> futureEvents = [];
      List<Map<String, dynamic>> pastEvents = [];

      for (final event in events) {
        final eventDate = event['startDateTime'] != null
            ? DateTime.parse(event['startDateTime'] as String)
            : DateTime.now();

        if (eventDate.isAfter(now)) {
          futureEvents.add({
            'id': event['id'],
            'name': event['name'],
            'startDateTime': eventDate,
          });
        } else {
          pastEvents.add({
            'id': event['id'],
            'name': event['name'],
            'startDateTime': eventDate,
          });
        }
      }

      return [...futureEvents, ...pastEvents];
    } catch (e) {
      return [];
    }
  }

  Future<void> _deleteEventType(EventTypeModel eventType) async {
    final events = await _getBlockingEvents(eventType.id);
    final futureEvents = events.where((e) =>
        (e['startDateTime'] as DateTime).isAfter(DateTime.now())).toList();

    if (futureEvents.isNotEmpty) {
      // Il y a des événements futurs, empêcher la suppression
      _showBlockingEventsDialog(eventType, events, canDelete: false);
      return;
    }

    if (events.isNotEmpty) {
      // Il n'y a que des événements passés, afficher un avertissement
      _showBlockingEventsDialog(eventType, events, canDelete: true);
      return;
    }

    // Aucun événement, suppression directe
    _confirmAndDelete(eventType);
  }

  void _showBlockingEventsDialog(EventTypeModel eventType, List<Map<String, dynamic>> events, {required bool canDelete}) {
    final futureEvents = events.where((e) =>
        (e['startDateTime'] as DateTime).isAfter(DateTime.now())).toList();
    final pastEvents = events.where((e) =>
        (e['startDateTime'] as DateTime).isBefore(DateTime.now())).toList();

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(canDelete ? 'Avertissement' : 'Suppression impossible'),
        content: SizedBox(
          width: double.maxFinite,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if (!canDelete) ...[
                const Text(
                  'Impossible de supprimer ce type d\'événement car il est utilisé par des événements futurs :',
                  style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 12),
                ...futureEvents.map((event) => Padding(
                  padding: const EdgeInsets.only(bottom: 4),
                  child: Text(
                    '• ${event['name']} - ${DateFormat('dd/MM/yyyy').format(event['startDateTime'])}',
                    style: const TextStyle(color: Colors.red),
                  ),
                )),
              ],
              if (canDelete && pastEvents.isNotEmpty) ...[
                const Text(
                  'Ce type d\'événement est utilisé par des événements passés :',
                  style: TextStyle(color: Colors.orange, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 12),
                ...pastEvents.take(5).map((event) => Padding(
                  padding: const EdgeInsets.only(bottom: 4),
                  child: Text(
                    '• ${event['name']} - ${DateFormat('dd/MM/yyyy').format(event['startDateTime'])}',
                    style: const TextStyle(color: Colors.orange),
                  ),
                )),
                if (pastEvents.length > 5)
                  Text('... et ${pastEvents.length - 5} autres événements'),
                const SizedBox(height: 12),
                const Text('Voulez-vous vraiment continuer la suppression ?'),
              ],
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Annuler'),
          ),
          if (canDelete)
            ElevatedButton(
              onPressed: () {
                Navigator.pop(context);
                _confirmAndDelete(eventType);
              },
              style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
              child: const Text('Supprimer quand même', style: TextStyle(color: Colors.white)),
            ),
        ],
      ),
    );
  }

  void _confirmAndDelete(EventTypeModel eventType) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Confirmer la suppression'),
        content: Text('Êtes-vous sûr de vouloir supprimer le type "${eventType.name}" ?'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Annuler'),
          ),
          ElevatedButton(
            onPressed: () async {
              Navigator.pop(context);
              try {
                await _dataService.deleteEventType(eventType.id);

                if (mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('Type d\'événement supprimé avec succès')),
                  );
                }
                _loadEventTypes();
              } catch (e) {
                if (mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Erreur lors de la suppression : $e')),
                  );
                }
              }
            },
            style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
            child: const Text('Supprimer', style: TextStyle(color: Colors.white)),
          ),
        ],
      ),
    );
  }

  void _showCreateEditDialog({EventTypeModel? eventType}) {
    showDialog(
      context: context,
      builder: (context) => _EventTypeFormDialog(
        eventType: eventType,
        onSaved: _loadEventTypes,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        children: [
          // Header avec recherche et bouton ajouter
          Row(
            children: [
              Expanded(
                child: TextField(
                  decoration: const InputDecoration(
                    labelText: 'Rechercher un type d\'événement',
                    prefixIcon: Icon(Icons.search),
                    border: OutlineInputBorder(),
                  ),
                  onChanged: (value) => setState(() => _searchQuery = value),
                ),
              ),
              const SizedBox(width: 16),
              ElevatedButton.icon(
                onPressed: () => _showCreateEditDialog(),
                icon: const Icon(Icons.add),
                label: const Text('Nouveau type'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppColors.rouge,
                  foregroundColor: Colors.white,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),

          // Liste des types d'événements
          Expanded(
            child: _loading
                ? const Center(child: CircularProgressIndicator())
                : _filteredEventTypes.isEmpty
                    ? const Center(
                        child: Text(
                          'Aucun type d\'événement trouvé',
                          style: TextStyle(fontSize: 16, color: Colors.grey),
                        ),
                      )
                    : ListView.builder(
                        itemCount: _filteredEventTypes.length,
                        itemBuilder: (context, index) {
                          final eventType = _filteredEventTypes[index];
                          return Card(
                            margin: const EdgeInsets.only(bottom: 8),
                            child: ListTile(
                              leading: CircleAvatar(
                                backgroundColor: AppColors.rouge,
                                child: const Icon(Icons.category, color: Colors.white),
                              ),
                              title: Text(
                                eventType.name,
                                style: const TextStyle(fontWeight: FontWeight.bold),
                              ),
                              subtitle: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    'Prix par défaut : ${eventType.defaultPrice} €',
                                    style: const TextStyle(fontWeight: FontWeight.bold),
                                  ),
                                  const SizedBox(height: 4),
                                  Text(
                                    'Créé le ${DateFormat('dd/MM/yyyy').format(eventType.createdAt)}',
                                    style: TextStyle(
                                      fontSize: 12,
                                      color: Colors.grey[600],
                                    ),
                                  ),
                                ],
                              ),
                              trailing: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  IconButton(
                                    icon: const Icon(Icons.edit, color: Colors.blue),
                                    onPressed: () => _showCreateEditDialog(eventType: eventType),
                                    tooltip: 'Modifier',
                                  ),
                                  IconButton(
                                    icon: const Icon(Icons.delete, color: Colors.red),
                                    onPressed: () => _deleteEventType(eventType),
                                    tooltip: 'Supprimer',
                                  ),
                                ],
                              ),
                            ),
                          );
                        },
                      ),
          ),
        ],
      ),
    );
  }
}

class _EventTypeFormDialog extends StatefulWidget {
  final EventTypeModel? eventType;
  final VoidCallback onSaved;

  const _EventTypeFormDialog({
    this.eventType,
    required this.onSaved,
  });

  @override
  State<_EventTypeFormDialog> createState() => _EventTypeFormDialogState();
}

class _EventTypeFormDialogState extends State<_EventTypeFormDialog> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _defaultPriceController = TextEditingController();
  bool _loading = false;
  String? _error;
  late final DataService _dataService;

  @override
  void initState() {
    super.initState();
    _dataService = DataService(FirebaseFunctionsApiService());
    if (widget.eventType != null) {
      _nameController.text = widget.eventType!.name;
      _defaultPriceController.text = widget.eventType!.defaultPrice.toString();
    }
  }

  @override
  void dispose() {
    _nameController.dispose();
    _defaultPriceController.dispose();
    super.dispose();
  }

  Future<void> _submit() async {
    if (!_formKey.currentState!.validate()) return;

    final name = _nameController.text.trim();
    final defaultPrice = double.tryParse(_defaultPriceController.text.replaceAll(',', '.')) ?? 0.0;

    setState(() {
      _loading = true;
      _error = null;
    });

    try {
      if (widget.eventType == null) {
        // Création
        await _dataService.createEventType(
          name: name,
          defaultPrice: defaultPrice,
        );
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('Type d\'événement créé avec succès')),
          );
        }
      } else {
        // Modification
        await _dataService.updateEventType(
          eventTypeId: widget.eventType!.id,
          name: name,
          defaultPrice: defaultPrice,
        );
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('Type d\'événement modifié avec succès')),
          );
        }
      }

      widget.onSaved();
      if (mounted) Navigator.pop(context);
    } catch (e) {
      setState(() {
        _error = e.toString().replaceFirst('Exception: ', '');
        _loading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text(widget.eventType == null ? 'Nouveau type d\'événement' : 'Modifier le type'),
      content: SizedBox(
        width: 400,
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextFormField(
                controller: _nameController,
                decoration: const InputDecoration(
                  labelText: 'Nom du type *',
                  border: OutlineInputBorder(),
                ),
                validator: (value) {
                  if (value == null || value.trim().isEmpty) {
                    return 'Le nom est obligatoire';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _defaultPriceController,
                decoration: const InputDecoration(
                  labelText: 'Prix par défaut (€) *',
                  border: OutlineInputBorder(),
                  hintText: '1100',
                ),
                keyboardType: const TextInputType.numberWithOptions(decimal: true),
                validator: (value) {
                  if (value == null || value.trim().isEmpty) {
                    return 'Le prix par défaut est obligatoire';
                  }
                  final price = double.tryParse(value.replaceAll(',', '.'));
                  if (price == null || price < 0) {
                    return 'Veuillez entrer un prix valide';
                  }
                  return null;
                },
              ),
              if (_error != null) ...[
                const SizedBox(height: 16),
                Text(
                  _error!,
                  style: const TextStyle(color: Colors.red),
                ),
              ],
            ],
          ),
        ),
      ),
      actions: [
        TextButton(
          onPressed: _loading ? null : () => Navigator.pop(context),
          child: const Text('Annuler'),
        ),
        ElevatedButton(
          onPressed: _loading ? null : _submit,
          style: ElevatedButton.styleFrom(
            backgroundColor: AppColors.rouge,
            foregroundColor: Colors.white,
          ),
          child: _loading
              ? const SizedBox(
                  width: 20,
                  height: 20,
                  child: CircularProgressIndicator(strokeWidth: 2),
                )
              : Text(widget.eventType == null ? 'Créer' : 'Modifier'),
        ),
      ],
    );
  }
}
