import 'package:flutter/material.dart';
import 'package:em2rp/models/event_model.dart';
import 'package:provider/provider.dart';
import 'package:em2rp/providers/event_provider.dart';
import 'package:em2rp/services/data_service.dart';
import 'package:em2rp/services/api_service.dart';

class EventStatusButton extends StatefulWidget {
  final EventModel event;
  final DateTime? selectedDate;
  final void Function(EventModel, DateTime) onSelectEvent;

  const EventStatusButton({
    super.key,
    required this.event,
    required this.selectedDate,
    required this.onSelectEvent,
  });

  @override
  State<EventStatusButton> createState() => _EventStatusButtonState();
}

class _EventStatusButtonState extends State<EventStatusButton> {
  bool _loading = false;
  EventStatus? _optimisticStatus;
  final DataService _dataService = DataService(FirebaseFunctionsApiService());

  @override
  void didUpdateWidget(EventStatusButton oldWidget) {
    super.didUpdateWidget(oldWidget);
    // Réinitialiser le statut optimiste si on affiche un nouvel événement
    if (oldWidget.event.id != widget.event.id) {
      _optimisticStatus = null;
      _loading = false;
    }
  }

  Future<void> _changeStatus(EventStatus newStatus) async {
    if ((widget.event.status == newStatus) || _loading) return;
    setState(() {
      _loading = true;
      _optimisticStatus = newStatus;
    });
    final oldStatus = widget.event.status;
    try {
      await _dataService.updateEvent(widget.event.id, {
        'status': eventStatusToString(newStatus),
      });
      final result = await _dataService.getEvents();
      final eventsList = result['events'] as List<dynamic>;
      final eventData = eventsList.firstWhere(
        (e) => e['id'] == widget.event.id,
        orElse: () => <String, dynamic>{},
      );
      if (eventData.isNotEmpty) {
        final updatedEvent = EventModel.fromMap(eventData, widget.event.id);
        widget.onSelectEvent(
          updatedEvent,
          widget.selectedDate ?? updatedEvent.startDateTime,
        );
        await Provider.of<EventProvider>(context, listen: false)
            .updateEvent(updatedEvent);
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _optimisticStatus = oldStatus;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Erreur lors du changement de statut: $e')),
        );
      }
    } finally {
      if (mounted) {
        setState(() => _loading = false);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final status = _optimisticStatus ?? widget.event.status;
    String texte;
    Color couleurFond;
    List<Widget> enfants = [];

    if (_loading) {
      return Container(
        padding: const EdgeInsets.all(8),
        child: const SizedBox(
          width: 24,
          height: 24,
          child: CircularProgressIndicator(strokeWidth: 2),
        ),
      );
    }

    switch (status) {
      case EventStatus.waitingForApproval:
        texte = "En Attente";
        couleurFond = Colors.yellow.shade600;
        enfants = [
          _buildIconButton(
            Icons.close,
            Colors.red,
            () => _changeStatus(EventStatus.canceled),
          ),
          _buildLabel(texte, couleurFond),
          _buildIconButton(
            Icons.check,
            Colors.green,
            () => _changeStatus(EventStatus.confirmed),
          ),
        ];
        break;
      case EventStatus.confirmed:
        texte = "Confirmé";
        couleurFond = Colors.green;
        enfants = [
          _buildIconButton(
            Icons.close,
            Colors.red,
            () => _changeStatus(EventStatus.canceled),
          ),
          _buildIconButton(
            Icons.hourglass_empty,
            Colors.yellow.shade700,
            () => _changeStatus(EventStatus.waitingForApproval),
          ),
          _buildLabel(texte, couleurFond),
        ];
        break;
      case EventStatus.canceled:
        texte = "Annulé";
        couleurFond = Colors.red;
        enfants = [
          _buildLabel(texte, couleurFond),
          _buildIconButton(
            Icons.hourglass_empty,
            Colors.yellow.shade700,
            () => _changeStatus(EventStatus.waitingForApproval),
          ),
          _buildIconButton(
            Icons.check,
            Colors.green,
            () => _changeStatus(EventStatus.confirmed),
          ),
        ];
        break;
    }

    return AnimatedContainer(
      duration: const Duration(milliseconds: 200),
      padding: const EdgeInsets.all(2),
      decoration: const BoxDecoration(
        color: Colors.transparent,
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: enfants,
      ),
    );
  }

  Widget _buildLabel(String texte, Color couleur) {
    return AnimatedContainer(
      duration: const Duration(milliseconds: 200),
      margin: const EdgeInsets.symmetric(horizontal: 2),
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: couleur,
        borderRadius: BorderRadius.circular(6),
      ),
      child: AnimatedSwitcher(
        duration: const Duration(milliseconds: 200),
        child: Text(
          texte,
          key: ValueKey(texte),
          style: const TextStyle(
            fontWeight: FontWeight.bold,
            color: Colors.white,
            fontSize: 13,
          ),
        ),
      ),
    );
  }

  Widget _buildIconButton(
    IconData icone,
    Color couleur,
    VoidCallback onPressed,
  ) {
    return AnimatedContainer(
      duration: const Duration(milliseconds: 200),
      margin: const EdgeInsets.symmetric(horizontal: 2),
      decoration: BoxDecoration(
        border: Border.all(color: couleur, width: 1.5),
        borderRadius: BorderRadius.circular(6),
      ),
      child: IconButton(
        icon: Icon(icone, color: couleur, size: 16),
        onPressed: _loading ? null : onPressed,
        splashRadius: 16,
        tooltip: 'Changer statut',
        padding: const EdgeInsets.all(4),
        constraints: const BoxConstraints(minWidth: 28, minHeight: 28),
      ),
    );
  }
}
