import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:share_plus/share_plus.dart';

import '../../core/constants/colors.dart';
import '../../core/constants/design_system.dart';
import '../../domain/entities/social_post.dart';
import 'animated_widgets.dart';
import 'custom_snackbar.dart';

/// Dialog moderne pour partager un post avec plusieurs options.
///
/// Propose plusieurs méthodes de partage:
/// - Copier le lien du post
/// - Partager vers des amis (à implémenter)
/// - Partager en externe (si share plugin disponible)
class SharePostDialog extends StatelessWidget {
  const SharePostDialog({
    required this.post,
    required this.onShareConfirmed,
    super.key,
  });

  final SocialPost post;
  final VoidCallback onShareConfirmed;

  /// Affiche le dialogue de partage
  static Future<void> show({
    required BuildContext context,
    required SocialPost post,
    required VoidCallback onShareConfirmed,
  }) {
    return showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => SharePostDialog(
        post: post,
        onShareConfirmed: onShareConfirmed,
      ),
    );
  }

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

    return Container(
      decoration: BoxDecoration(
        color: theme.scaffoldBackgroundColor,
        borderRadius: const BorderRadius.vertical(
          top: Radius.circular(DesignSystem.radiusLg),
        ),
      ),
      padding: EdgeInsets.only(
        bottom: MediaQuery.of(context).viewInsets.bottom + DesignSystem.spacingLg,
        top: DesignSystem.spacingMd,
        left: DesignSystem.spacingLg,
        right: DesignSystem.spacingLg,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // Handle bar
          Center(
            child: Container(
              width: 36,
              height: 3,
              margin: const EdgeInsets.only(bottom: DesignSystem.spacingMd),
              decoration: BoxDecoration(
                color: theme.colorScheme.onSurface.withOpacity(0.2),
                borderRadius: BorderRadius.circular(DesignSystem.radiusSm),
              ),
            ),
          ),

          // Titre
          Text(
            'Partager ce post',
            style: theme.textTheme.titleMedium?.copyWith(
              fontWeight: FontWeight.bold,
              fontSize: 17,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: DesignSystem.spacingMd),

          // Description du post
          Container(
            padding: const EdgeInsets.all(DesignSystem.spacingMd),
            decoration: BoxDecoration(
              color: theme.colorScheme.surfaceVariant.withOpacity(0.3),
              borderRadius: BorderRadius.circular(DesignSystem.radiusMd),
              border: Border.all(
                color: theme.dividerColor.withOpacity(0.3),
                width: 1,
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    CircleAvatar(
                      radius: 14,
                      backgroundImage: post.userProfileImageUrl.isNotEmpty
                          ? NetworkImage(post.userProfileImageUrl)
                          : null,
                      backgroundColor: theme.colorScheme.primary.withOpacity(0.15),
                      child: post.userProfileImageUrl.isEmpty
                          ? Icon(
                              Icons.person_rounded,
                              size: 14,
                              color: theme.colorScheme.primary,
                            )
                          : null,
                    ),
                    const SizedBox(width: DesignSystem.spacingSm),
                    Expanded(
                      child: Text(
                        post.authorFullName,
                        style: theme.textTheme.bodyMedium?.copyWith(
                          fontWeight: FontWeight.w600,
                          fontSize: 14,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: DesignSystem.spacingSm),
                Text(
                  post.content,
                  style: theme.textTheme.bodySmall?.copyWith(
                    fontSize: 13,
                    height: 1.4,
                  ),
                  maxLines: 3,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
          ),
          const SizedBox(height: DesignSystem.spacingLg),

          // Options de partage
          _buildShareOption(
            context: context,
            icon: Icons.link,
            iconColor: AppColors.primary,
            title: 'Copier le lien',
            subtitle: 'Copiez l\'URL du post dans le presse-papiers',
            onTap: () => _copyLink(context),
          ),
          const SizedBox(height: DesignSystem.spacingSm),

          _buildShareOption(
            context: context,
            icon: Icons.people,
            iconColor: Colors.green,
            title: 'Partager à des amis',
            subtitle: 'Envoyez ce post à vos amis sur Afterwork',
            onTap: () => _shareToFriends(context),
          ),
          const SizedBox(height: DesignSystem.spacingSm),

          _buildShareOption(
            context: context,
            icon: Icons.ios_share,
            iconColor: Colors.blue,
            title: 'Partager via...',
            subtitle: 'WhatsApp, Messenger, Email, etc.',
            onTap: () => _shareExternal(context),
          ),
          const SizedBox(height: DesignSystem.spacingSm),

          _buildShareOption(
            context: context,
            icon: Icons.send,
            iconColor: Colors.orange,
            title: 'Partager sur le fil',
            subtitle: 'Incrémenter le compteur de partages',
            onTap: () => _shareToFeed(context),
          ),
          const SizedBox(height: DesignSystem.spacingMd),

          // Bouton annuler
          AnimatedScaleButton(
            onTap: () => Navigator.pop(context),
            child: Container(
              padding: const EdgeInsets.symmetric(
                vertical: DesignSystem.spacingMd,
              ),
              decoration: BoxDecoration(
                color: theme.colorScheme.surfaceVariant.withOpacity(0.5),
                borderRadius: BorderRadius.circular(DesignSystem.radiusMd),
              ),
              child: Text(
                'Annuler',
                style: theme.textTheme.bodyMedium?.copyWith(
                  fontWeight: FontWeight.w600,
                  fontSize: 14,
                  color: theme.colorScheme.onSurface.withOpacity(0.7),
                ),
                textAlign: TextAlign.center,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildShareOption({
    required BuildContext context,
    required IconData icon,
    required Color iconColor,
    required String title,
    required String subtitle,
    required VoidCallback onTap,
  }) {
    final theme = Theme.of(context);

    return AnimatedScaleButton(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.all(DesignSystem.spacingMd),
        decoration: BoxDecoration(
          color: theme.colorScheme.surface,
          borderRadius: BorderRadius.circular(DesignSystem.radiusMd),
          border: Border.all(
            color: theme.dividerColor.withOpacity(0.3),
            width: 1,
          ),
        ),
        child: Row(
          children: [
            Container(
              padding: const EdgeInsets.all(DesignSystem.spacingSm),
              decoration: BoxDecoration(
                color: iconColor.withOpacity(0.1),
                borderRadius: BorderRadius.circular(DesignSystem.radiusSm),
              ),
              child: Icon(
                icon,
                color: iconColor,
                size: 20,
              ),
            ),
            const SizedBox(width: DesignSystem.spacingMd),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: theme.textTheme.bodyMedium?.copyWith(
                      fontWeight: FontWeight.w600,
                      fontSize: 14,
                    ),
                  ),
                  const SizedBox(height: 2),
                  Text(
                    subtitle,
                    style: theme.textTheme.bodySmall?.copyWith(
                      color: theme.colorScheme.onSurface.withOpacity(0.5),
                      fontSize: 12,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
            Icon(
              Icons.chevron_right_rounded,
              color: theme.colorScheme.onSurface.withOpacity(0.3),
              size: 20,
            ),
          ],
        ),
      ),
    );
  }

  /// Copie le lien du post dans le presse-papiers
  void _copyLink(BuildContext context) {
    // Génère un lien fictif pour le post (à remplacer par le vrai lien depuis le backend)
    final link = 'https://afterwork.app/posts/${post.id}';

    Clipboard.setData(ClipboardData(text: link));
    Navigator.pop(context);
    context.showSuccess('Lien copié dans le presse-papiers');
  }

  /// Partage le post à des amis spécifiques
  void _shareToFriends(BuildContext context) {
    Navigator.pop(context);

    // Afficher le dialog de sélection d'amis
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Partager avec des amis'),
        content: SizedBox(
          width: double.maxFinite,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text(
                'Cette fonctionnalité permet de partager ce post directement avec vos amis par message privé.',
                style: TextStyle(fontSize: 14),
              ),
              const SizedBox(height: DesignSystem.spacingLg),
              // Future enhancement: Liste d'amis avec sélection multiple
              Container(
                padding: const EdgeInsets.all(DesignSystem.spacingLg),
                decoration: BoxDecoration(
                  color: Colors.grey.shade100,
                  borderRadius: BorderRadius.circular(DesignSystem.radiusMd),
                ),
                child: Row(
                  children: [
                    Icon(Icons.info_outline, color: Colors.grey.shade600),
                    const SizedBox(width: DesignSystem.spacingMd),
                    Expanded(
                      child: Text(
                        'Liste des amis à venir dans une prochaine version',
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.grey.shade700,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Fermer'),
          ),
        ],
      ),
    );
  }

  /// Partage le post via des applications externes
  Future<void> _shareExternal(BuildContext context) async {
    Navigator.pop(context);

    try {
      final postUrl = 'https://afterwork.app/post/${post.id}';
      final shareText = '${post.content}\n\nVoir sur AfterWork: $postUrl';

      await Share.share(
        shareText,
        subject: 'Publication AfterWork de ${post.userFirstName} ${post.userLastName}',
      );

      if (context.mounted) {
        context.showSuccess('Post partagé avec succès');
        onShareConfirmed();
      }
    } catch (e) {
      if (context.mounted) {
        context.showError('Erreur lors du partage');
      }
    }
  }

  /// Partage le post sur le fil (incrémente le compteur)
  void _shareToFeed(BuildContext context) {
    Navigator.pop(context);
    onShareConfirmed();
  }
}
