import 'package:flutter/material.dart';
import 'package:em2rp/models/event_model.dart';
import 'package:em2rp/utils/colors.dart';
import 'package:provider/provider.dart';
import 'package:em2rp/providers/local_user_provider.dart';
import 'package:em2rp/views/event_add_page.dart';
import 'package:em2rp/services/ics_export_service.dart';
import 'package:em2rp/services/data_service.dart';
import 'package:em2rp/services/api_service.dart';
import 'package:web/web.dart' as web;
import 'dart:convert';
import 'dart:js_interop';

class EventDetailsHeader extends StatefulWidget {
  final EventModel event;

  const EventDetailsHeader({
    super.key,
    required this.event,
  });

  @override
  State<EventDetailsHeader> createState() => _EventDetailsHeaderState();
}

class _EventDetailsHeaderState extends State<EventDetailsHeader> {
  String? _eventTypeName;
  bool _isLoadingEventType = true;

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

  @override
  void didUpdateWidget(EventDetailsHeader oldWidget) {
    super.didUpdateWidget(oldWidget);
    // Recharger le type d'événement si l'événement a changé
    if (oldWidget.event.id != widget.event.id ||
        oldWidget.event.eventTypeId != widget.event.eventTypeId) {
      _fetchEventTypeName();
    }
  }

  Future<void> _fetchEventTypeName() async {
    setState(() => _isLoadingEventType = true);

    try {
      if (widget.event.eventTypeId.isEmpty) {
        setState(() {
          _eventTypeName = null;
          _isLoadingEventType = false;
        });
        return;
      }

      // Charger tous les types d'événements via l'API
      final dataService = DataService(FirebaseFunctionsApiService());
      final eventTypes = await dataService.getEventTypes();

      // Trouver le type correspondant
      final eventType = eventTypes.firstWhere(
        (type) => type['id'] == widget.event.eventTypeId,
        orElse: () => <String, dynamic>{},
      );

      setState(() {
        _eventTypeName = eventType['name'] as String? ?? widget.event.eventTypeId;
        _isLoadingEventType = false;
      });
    } catch (e) {
      setState(() {
        _eventTypeName = widget.event.eventTypeId;
        _isLoadingEventType = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                constraints: const BoxConstraints(maxHeight: 80),
                child: SelectableText(
                  widget.event.name,
                  style: Theme.of(context).textTheme.headlineMedium?.copyWith(
                        color: AppColors.noir,
                        fontWeight: FontWeight.bold,
                      ),
                ),
              ),
              const SizedBox(height: 4),
              Text(
                _isLoadingEventType
                    ? 'Chargement...'
                    : _eventTypeName ?? widget.event.eventTypeId,
                style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                      color: AppColors.rouge,
                    ),
              ),
            ],
          ),
        ),
        const SizedBox(width: 12),
        _buildStatusIcon(widget.event.status),
        const SizedBox(width: 8),
        IconButton(
          icon: const Icon(Icons.add_to_home_screen, color: AppColors.rouge),
          tooltip: 'Ajouter a mon application de calendrier',
          onPressed: _exportToCalendar,
        ),
        if (Provider.of<LocalUserProvider>(context, listen: false)
            .hasPermission('edit_event')) ...[
          const SizedBox(width: 8),
          IconButton(
            icon: const Icon(Icons.edit, color: AppColors.rouge),
            tooltip: 'Modifier',
            onPressed: () {
              Navigator.of(context).push(
                MaterialPageRoute(
                  builder: (context) => EventAddEditPage(event: widget.event),
                ),
              );
            },
          ),
        ],
      ],
    );
  }

  Future<void> _exportToCalendar() async {
    try {
      // Afficher un indicateur de chargement
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Row(
            children: [
              SizedBox(
                width: 20,
                height: 20,
                child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),
              ),
              SizedBox(width: 16),
              Text('Génération du fichier ICS...'),
            ],
          ),
          duration: Duration(seconds: 2),
        ),
      );

      // Charger les utilisateurs pour résoudre leurs noms
      final dataService = DataService(FirebaseFunctionsApiService());
      final users = await dataService.getUsers();

      // Créer une Map des IDs utilisateurs vers leurs noms complets
      final Map<String, String> userNames = {};
      for (final user in users) {
        final userId = user['id'] as String?;
        final firstName = user['firstName'] as String? ?? '';
        final lastName = user['lastName'] as String? ?? '';
        if (userId != null && (firstName.isNotEmpty || lastName.isNotEmpty)) {
          userNames[userId] = '$firstName $lastName'.trim();
        }
      }

      // Générer le contenu ICS avec le nom du type et les noms des utilisateurs
      final icsContent = await IcsExportService.generateIcsContent(
        widget.event,
        eventTypeName: _eventTypeName ?? 'Non spécifié',
        userNames: userNames, // Passer les noms des utilisateurs
      );
      final fileName = IcsExportService.generateFileName(widget.event);

      // Créer un blob et télécharger le fichier
      final bytes = utf8.encode(icsContent);
      final blob = web.Blob([bytes.toJS].toJS, web.BlobPropertyBag(type: 'text/calendar'));
      final url = web.URL.createObjectURL(blob);
      final anchor = web.document.createElement('a') as web.HTMLAnchorElement;
      anchor.href = url;
      anchor.download = fileName;
      anchor.click();
      web.URL.revokeObjectURL(url);

      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Événement exporté : $fileName'),
          backgroundColor: Colors.green,
          action: SnackBarAction(
            label: 'OK',
            textColor: Colors.white,
            onPressed: () {},
          ),
        ),
      );
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Erreur lors de l\'export : $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  Widget _buildStatusIcon(EventStatus status) {
    Color color;
    IconData icon;
    String tooltip;
    switch (status) {
      case EventStatus.confirmed:
        color = Colors.green;
        icon = Icons.check_circle;
        tooltip = 'Confirmé';
        break;
      case EventStatus.canceled:
        color = Colors.red;
        icon = Icons.cancel;
        tooltip = 'Annulé';
        break;
      case EventStatus.waitingForApproval:
        color = Colors.amber;
        icon = Icons.hourglass_empty;
        tooltip = 'En attente de validation';
        break;
    }
    return Tooltip(
      message: tooltip,
      child: Icon(icon, color: color, size: 28),
    );
  }
}
