import 'package:flutter/material.dart';
import '../../../../../shared/design_system/dashboard_theme_manager.dart';
import '../../../../../shared/design_system/tokens/app_colors.dart';
import '../../../../../shared/design_system/tokens/app_typography.dart';
import '../../../../../shared/design_system/tokens/spacing_tokens.dart';
import '../../../../../shared/design_system/tokens/radius_tokens.dart';
import '../../../../../shared/widgets/core_card.dart';

/// Widget de sélection de thème pour le Dashboard
class ThemeSelectorWidget extends StatefulWidget {
  final Function(String)? onThemeChanged;
  
  const ThemeSelectorWidget({
    super.key,
    this.onThemeChanged,
  });

  @override
  State<ThemeSelectorWidget> createState() => _ThemeSelectorWidgetState();
}

class _ThemeSelectorWidgetState extends State<ThemeSelectorWidget> {
  String _selectedTheme = 'royalTeal';
  
  @override
  void initState() {
    super.initState();
    _selectedTheme = DashboardThemeManager.currentTheme.name == 'Bleu Roi & Pétrole' 
        ? 'royalTeal' : 'royalTeal'; // Par défaut
  }

  @override
  Widget build(BuildContext context) {
    return CoreCard(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Row(
            children: [
              Icon(
                Icons.palette,
                color: AppColors.primaryGreen,
                size: 24,
              ),
              SizedBox(width: 8),
              Text(
                'Thème de l\'interface',
                style: AppTypography.headerSmall,
              ),
            ],
          ),
          const SizedBox(height: SpacingTokens.xl),
          
          // Grille des thèmes
          GridView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              crossAxisSpacing: 12,
              mainAxisSpacing: 12,
              childAspectRatio: 1.5,
            ),
            itemCount: DashboardThemeManager.availableThemes.length,
            itemBuilder: (context, index) {
              final themeOption = DashboardThemeManager.availableThemes[index];
              final isSelected = _selectedTheme == themeOption.key;
              
              return _buildThemeCard(themeOption, isSelected);
            },
          ),
          
          const SizedBox(height: SpacingTokens.xl),
          
          // Aperçu du thème sélectionné
          _buildThemePreview(),
        ],
      ),
    );
  }
  
  Widget _buildThemeCard(ThemeOption themeOption, bool isSelected) {
    return GestureDetector(
      onTap: () => _selectTheme(themeOption.key),
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color: isSelected 
                ? themeOption.theme.primaryColor 
                : const Color(0xFFD1D5DB),
            width: isSelected ? 2 : 1,
          ),
          boxShadow: isSelected 
              ? [
                  BoxShadow(
                    color: themeOption.theme.primaryColor.withOpacity(0.3),
                    blurRadius: 8,
                    offset: const Offset(0, 2),
                  ),
                ]
              : null,
        ),
        child: Column(
          children: [
            // Gradient de démonstration
            Expanded(
              flex: 2,
              child: Container(
                width: double.infinity,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [
                      themeOption.theme.primaryColor,
                      themeOption.theme.secondaryColor,
                    ],
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                  ),
                  borderRadius: const BorderRadius.only(
                    topLeft: Radius.circular(RadiusTokens.lg - 1),
                    topRight: Radius.circular(RadiusTokens.lg - 1),
                  ),
                ),
                child: isSelected
                    ? const Icon(
                        Icons.check_circle,
                        color: Colors.white,
                        size: 24,
                      )
                    : null,
              ),
            ),
            
            // Nom du thème
            Expanded(
              flex: 1,
              child: Container(
                width: double.infinity,
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: themeOption.theme.cardColor,
                  borderRadius: const BorderRadius.only(
                    bottomLeft: Radius.circular(7),
                    bottomRight: Radius.circular(7),
                  ),
                ),
                child: Center(
                  child: Text(
                    themeOption.name,
                    style: TextStyle(
                      fontSize: 12,
                      fontWeight: FontWeight.w600,
                      color: themeOption.theme.textPrimary,
                    ),
                    textAlign: TextAlign.center,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  Widget _buildThemePreview() {
    final currentTheme = DashboardThemeManager.availableThemes
        .firstWhere((theme) => theme.key == _selectedTheme);
    
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: currentTheme.theme.backgroundColor,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: const Color(0xFFD1D5DB)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Aperçu: ${currentTheme.name}',
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w600,
              color: currentTheme.theme.textPrimary,
            ),
          ),
          const SizedBox(height: SpacingTokens.lg),
          
          // Aperçu de carte avec le thème
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: currentTheme.theme.cardColor,
              borderRadius: BorderRadius.circular(4),
              boxShadow: [
                BoxShadow(
                  color: currentTheme.theme.primaryColor.withOpacity(0.1),
                  blurRadius: 4,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Row(
              children: [
                Container(
                  width: 40,
                  height: 40,
                  decoration: BoxDecoration(
                    gradient: currentTheme.theme.primaryGradient,
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: const Icon(
                    Icons.dashboard,
                    color: Colors.white,
                    size: 20,
                  ),
                ),
                const SizedBox(width: SpacingTokens.lg),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Dashboard UnionFlow',
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w600,
                          color: currentTheme.theme.textPrimary,
                        ),
                      ),
                      const SizedBox(height: 2),
                      Text(
                        'Aperçu',
                        style: TextStyle(
                          fontSize: 12,
                          color: currentTheme.theme.textSecondary,
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 8,
                    vertical: 4,
                  ),
                  decoration: BoxDecoration(
                    color: currentTheme.theme.success.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Text(
                    'Actif',
                    style: TextStyle(
                      fontSize: 10,
                      fontWeight: FontWeight.w600,
                      color: currentTheme.theme.success,
                    ),
                  ),
                ),
              ],
            ),
          ),
          
          const SizedBox(height: SpacingTokens.lg),
          
          // Palette de couleurs
          Row(
            children: [
              _buildColorSwatch('Primaire', currentTheme.theme.primaryColor),
              const SizedBox(width: 8),
              _buildColorSwatch('Secondaire', currentTheme.theme.secondaryColor),
              const SizedBox(width: 8),
              _buildColorSwatch('Succès', currentTheme.theme.success),
              const SizedBox(width: 8),
              _buildColorSwatch('Attention', currentTheme.theme.warning),
            ],
          ),
        ],
      ),
    );
  }
  
  Widget _buildColorSwatch(String label, Color color) {
    return Expanded(
      child: Column(
        children: [
          Container(
            width: double.infinity,
            height: 30,
            decoration: BoxDecoration(
              color: color,
              borderRadius: BorderRadius.circular(4),
            ),
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: const TextStyle(
              fontSize: 10,
              color: Color(0xFF4B5563),
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }
  
  void _selectTheme(String themeKey) {
    setState(() {
      _selectedTheme = themeKey;
    });
    
    // Appliquer le thème
    DashboardThemeManager.setTheme(themeKey);
    
    // Notifier le changement
    widget.onThemeChanged?.call(themeKey);
    
    // Afficher un message de confirmation
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
          'Thème "${DashboardThemeManager.availableThemes.firstWhere((t) => t.key == themeKey).name}" appliqué',
        ),
        backgroundColor: DashboardThemeManager.currentTheme.success,
        duration: const Duration(seconds: 2),
      ),
    );
  }
}
