import 'package:flutter/material.dart';
import '../theme/app_theme.dart';

class XPBreakdownCard extends StatelessWidget {
  final Map<String, int> breakdown;

  const XPBreakdownCard({
    super.key,
    required this.breakdown,
  });

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                const Icon(Icons.pie_chart, color: AppTheme.primaryColor),
                const SizedBox(width: 8),
                Text(
                  'XP Sources Today',
                  style: Theme.of(context).textTheme.titleLarge?.copyWith(
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            if (breakdown.isEmpty)
              const Center(
                child: Padding(
                  padding: EdgeInsets.all(20),
                  child: Text('No XP earned today'),
                ),
              )
            else
              ..._buildXPSourceItems(),
          ],
        ),
      ),
    );
  }

  List<Widget> _buildXPSourceItems() {
    final totalXP = breakdown.values.fold(0, (sum, xp) => sum + xp);
    
    final sortedEntries = breakdown.entries
        .where((entry) => entry.value > 0)
        .toList();
    
    sortedEntries.sort((a, b) => b.value.compareTo(a.value));
    
    return sortedEntries
        .take(5)
        .map((entry) => _XPSourceItem(
              source: entry.key,
              xp: entry.value,
              totalXP: totalXP,
            ))
        .toList();
  }
}

class _XPSourceItem extends StatelessWidget {
  final String source;
  final int xp;
  final int totalXP;

  const _XPSourceItem({
    required this.source,
    required this.xp,
    required this.totalXP,
  });

  @override
  Widget build(BuildContext context) {
    final percentage = totalXP > 0 ? (xp / totalXP * 100) : 0.0;
    final color = AppTheme.getXPSourceColor(source);

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                width: 12,
                height: 12,
                decoration: BoxDecoration(
                  color: color,
                  borderRadius: BorderRadius.circular(2),
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: Text(
                  _formatSourceName(source),
                  style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
              Text(
                '+$xp XP',
                style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                  fontWeight: FontWeight.bold,
                  color: color,
                ),
              ),
            ],
          ),
          const SizedBox(height: 4),
          Row(
            children: [
              Expanded(
                child: Container(
                  height: 4,
                  decoration: BoxDecoration(
                    color: Colors.grey.shade200,
                    borderRadius: BorderRadius.circular(2),
                  ),
                  child: FractionallySizedBox(
                    alignment: Alignment.centerLeft,
                    widthFactor: percentage / 100,
                    child: Container(
                      decoration: BoxDecoration(
                        color: color,
                        borderRadius: BorderRadius.circular(2),
                      ),
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 8),
              Text(
                '${percentage.toStringAsFixed(1)}%',
                style: Theme.of(context).textTheme.bodySmall?.copyWith(
                  color: Colors.grey.shade600,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  String _formatSourceName(String source) {
    switch (source) {
      case 'coding':
        return 'Coding';
      case 'focused_browsing':
        return 'Focused Browsing';
      case 'collaboration':
        return 'Collaboration';
      case 'meetings':
        return 'Meetings';
      case 'misc':
        return 'Miscellaneous';
      case 'uncategorized':
        return 'Uncategorized';
      case 'focus_session':
        return 'Focus Sessions';
      case 'achievement':
        return 'Achievements';
      case 'manual_boost':
        return 'Manual Boosts';
      default:
        return source.replaceAll('_', ' ').split(' ').map((word) => 
          word.isEmpty ? word : word[0].toUpperCase() + word.substring(1)
        ).join(' ');
    }
  }
}
