import 'package:flutter/material.dart';

import '../../core/utils/date_formatter.dart';
import 'event_menu.dart';

/// En-tête d'événement avec informations du créateur et actions.
///
/// Ce widget affiche les informations du créateur de l'événement,
/// la date, le lieu, et des actions (menu, fermeture).
///
/// **Usage:**
/// ```dart
/// EventHeader(
///   creatorFirstName: 'John',
///   creatorLastName: 'Doe',
///   profileImageUrl: 'https://example.com/avatar.jpg',
///   eventDate: '2024-01-01',
///   location: 'Paris, France',
///   menuKey: menuKey,
///   menuContext: context,
///   onClose: () => handleClose(),
/// )
/// ```
class EventHeader extends StatelessWidget {
  const EventHeader({
    required this.creatorFirstName,
    required this.creatorLastName,
    required this.profileImageUrl,
    required this.location,
    required this.menuKey,
    required this.menuContext,
    required this.onClose,
    this.eventDate,
    this.imageUrl,
    super.key,
  });

  final String creatorFirstName;
  final String creatorLastName;
  final String profileImageUrl;
  final String? eventDate;
  final String? imageUrl;
  final String location;
  final GlobalKey menuKey;
  final BuildContext menuContext;
  final VoidCallback onClose;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final formattedDate = _formatDate();

    return Stack(
      children: [
        Row(
          children: [
            _buildAvatar(theme),
            const SizedBox(width: 12),
            Expanded(
              child: _buildCreatorInfo(theme, formattedDate),
            ),
          ],
        ),
        _buildActions(theme),
      ],
    );
  }

  /// Construit l'avatar du créateur.
  Widget _buildAvatar(ThemeData theme) {
    return CircleAvatar(
      radius: 20,
      backgroundColor: theme.colorScheme.surfaceVariant,
      backgroundImage: _getImageProvider(),
      onBackgroundImageError: (exception, stackTrace) {
        // Gestion silencieuse de l'erreur
      },
      child: profileImageUrl.isEmpty
          ? Icon(
              Icons.person,
              color: theme.colorScheme.onSurfaceVariant,
              size: 20,
            )
          : null,
    );
  }

  /// Obtient le provider d'image.
  ImageProvider? _getImageProvider() {
    if (profileImageUrl.isEmpty) return null;

    if (profileImageUrl.startsWith('http://') ||
        profileImageUrl.startsWith('https://')) {
      return NetworkImage(profileImageUrl);
    }

    return AssetImage(profileImageUrl);
  }

  /// Construit les informations du créateur.
  Widget _buildCreatorInfo(ThemeData theme, String formattedDate) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        Text(
          '$creatorFirstName $creatorLastName',
          style: theme.textTheme.bodyLarge?.copyWith(
            fontWeight: FontWeight.w600,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        const SizedBox(height: 4),
        Row(
          children: [
            Icon(
              Icons.calendar_today,
              size: 12,
              color: theme.colorScheme.onSurface.withOpacity(0.6),
            ),
            const SizedBox(width: 4),
            Expanded(
              child: Text(
                formattedDate,
                style: theme.textTheme.bodySmall?.copyWith(
                  color: theme.colorScheme.onSurface.withOpacity(0.6),
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
        const SizedBox(height: 4),
        Row(
          children: [
            Icon(
              Icons.location_on,
              size: 12,
              color: theme.colorScheme.onSurface.withOpacity(0.6),
            ),
            const SizedBox(width: 4),
            Expanded(
              child: Text(
                location.isNotEmpty ? location : 'Lieu non spécifié',
                style: theme.textTheme.bodySmall?.copyWith(
                  color: theme.colorScheme.onSurface.withOpacity(0.6),
                  fontStyle: FontStyle.italic,
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// Construit les actions (menu et fermeture).
  Widget _buildActions(ThemeData theme) {
    return Positioned(
      top: 0,
      right: 0,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          IconButton(
            key: menuKey,
            icon: Icon(
              Icons.more_vert,
              color: theme.colorScheme.onSurface.withOpacity(0.6),
              size: 20,
            ),
            padding: EdgeInsets.zero,
            constraints: const BoxConstraints(),
            splashRadius: 20,
            onPressed: () {
              showEventOptions(menuContext, menuKey);
            },
          ),
          IconButton(
            icon: Icon(
              Icons.close,
              color: theme.colorScheme.onSurface.withOpacity(0.6),
              size: 20,
            ),
            padding: EdgeInsets.zero,
            constraints: const BoxConstraints(),
            splashRadius: 20,
            onPressed: onClose,
          ),
        ],
      ),
    );
  }

  /// Formate la date de l'événement.
  String _formatDate() {
    if (eventDate == null || eventDate!.isEmpty) {
      return 'Date inconnue';
    }

    try {
      final date = DateTime.parse(eventDate!);
      return DateFormatter.formatDate(date);
    } catch (e) {
      return 'Date invalide';
    }
  }
}
