import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../core/config/app_constants.dart';
import '../providers/pokedex_provider.dart';
import '../providers/theme_provider.dart';

class SystemPage extends ConsumerWidget {
  const SystemPage({super.key});

  Future<int> _loadBestScore() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getInt(AppConstants.prefsBestScore) ?? 0;
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final paletteIndex = ref.watch(themeProvider);
    final palette = appPalettes[paletteIndex];
    final pokedexAsync = ref.watch(pokedexProvider);

    return Container(
      color: const Color(0xFFC8D1D8),
      child: Column(
        children: [
          _Header(primaryColor: palette.primary),
          Expanded(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  _SectionTitle(text: 'STATISTIQUES', color: palette.primary),
                  const SizedBox(height: 8),
                  pokedexAsync.when(
                    loading: () => const Center(child: CircularProgressIndicator()),
                    error: (_, __) => const Text('Erreur de chargement'),
                    data: (pokemons) {
                      final total = pokemons.length;
                      final caught = pokemons.where((p) => p.isCaught).length;
                      final seen = pokemons.where((p) => p.isSeen).length;
                      final pct = total > 0 ? (caught / total * 100).toStringAsFixed(1) : '0.0';
                      return FutureBuilder<int>(
                        future: _loadBestScore(),
                        builder: (context, snap) {
                          final best = snap.data ?? 0;
                          return _StatsGrid(
                            primaryColor: palette.primary,
                            items: [
                              _StatItem(label: 'Meilleur score', value: '$best', icon: Icons.emoji_events),
                              _StatItem(label: 'Attrapés', value: '$caught / $total', icon: Icons.catching_pokemon),
                              _StatItem(label: 'Vus', value: '$seen / $total', icon: Icons.visibility),
                              _StatItem(label: 'Complétion', value: '$pct%', icon: Icons.pie_chart),
                            ],
                          );
                        },
                      );
                    },
                  ),
                  const SizedBox(height: 24),
                  _SectionTitle(text: 'PALETTE DE COULEURS', color: palette.primary),
                  const SizedBox(height: 8),
                  _PalettePicker(
                    selectedIndex: paletteIndex,
                    onSelect: (i) => ref.read(themeProvider.notifier).setPalette(i),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _Header extends StatelessWidget {
  final Color primaryColor;
  const _Header({required this.primaryColor});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(vertical: 16),
      decoration: BoxDecoration(
        color: primaryColor,
        border: Border(bottom: BorderSide(color: primaryColor.withAlpha(180), width: 3)),
      ),
      child: const Text(
        'SYSTÈME',
        textAlign: TextAlign.center,
        style: TextStyle(
          color: Colors.white,
          fontSize: 28,
          fontWeight: FontWeight.bold,
          letterSpacing: 4,
        ),
      ),
    );
  }
}

class _SectionTitle extends StatelessWidget {
  final String text;
  final Color color;
  const _SectionTitle({required this.text, required this.color});

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Container(width: 4, height: 20, color: color),
        const SizedBox(width: 8),
        Text(
          text,
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: color,
            letterSpacing: 2,
          ),
        ),
      ],
    );
  }
}

class _StatItem {
  final String label;
  final String value;
  final IconData icon;
  const _StatItem({required this.label, required this.value, required this.icon});
}

class _StatsGrid extends StatelessWidget {
  final Color primaryColor;
  final List<_StatItem> items;
  const _StatsGrid({required this.primaryColor, required this.items});

  @override
  Widget build(BuildContext context) {
    return GridView.count(
      crossAxisCount: 2,
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      crossAxisSpacing: 12,
      mainAxisSpacing: 12,
      childAspectRatio: 1.4,
      children: items.map((item) => _StatCard(item: item, color: primaryColor)).toList(),
    );
  }
}

class _StatCard extends StatelessWidget {
  final _StatItem item;
  final Color color;
  const _StatCard({required this.item, required this.color});

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: color.withAlpha(80), width: 2),
        boxShadow: [
          BoxShadow(color: Colors.black.withAlpha(25), blurRadius: 4, offset: const Offset(0, 2)),
        ],
      ),
      padding: const EdgeInsets.all(12),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(item.icon, color: color, size: 28),
          const SizedBox(height: 6),
          Text(
            item.value,
            style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: color),
          ),
          Text(
            item.label,
            textAlign: TextAlign.center,
            style: const TextStyle(fontSize: 12, color: Colors.black54),
          ),
        ],
      ),
    );
  }
}

class _PalettePicker extends StatelessWidget {
  final int selectedIndex;
  final void Function(int) onSelect;
  const _PalettePicker({required this.selectedIndex, required this.onSelect});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: List.generate(appPalettes.length, (i) {
        final p = appPalettes[i];
        final isSelected = i == selectedIndex;
        return GestureDetector(
          onTap: () => onSelect(i),
          child: AnimatedContainer(
            duration: const Duration(milliseconds: 200),
            margin: const EdgeInsets.only(bottom: 10),
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            decoration: BoxDecoration(
              color: isSelected ? p.primary : Colors.white,
              borderRadius: BorderRadius.circular(12),
              border: Border.all(
                color: isSelected ? p.primary : Colors.grey.shade300,
                width: isSelected ? 3 : 1.5,
              ),
              boxShadow: isSelected
                  ? [BoxShadow(color: p.primary.withAlpha(80), blurRadius: 8, offset: const Offset(0, 3))]
                  : [],
            ),
            child: Row(
              children: [
                Container(
                  width: 32,
                  height: 32,
                  decoration: BoxDecoration(
                    color: p.primary,
                    shape: BoxShape.circle,
                    border: Border.all(color: Colors.white, width: 2),
                  ),
                ),
                const SizedBox(width: 8),
                Container(
                  width: 20,
                  height: 20,
                  decoration: BoxDecoration(
                    color: p.surface,
                    shape: BoxShape.circle,
                    border: Border.all(color: Colors.white, width: 1.5),
                  ),
                ),
                const SizedBox(width: 16),
                Text(
                  p.name,
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: isSelected ? Colors.white : Colors.black87,
                  ),
                ),
                const Spacer(),
                if (isSelected)
                  const Icon(Icons.check_circle, color: Colors.white, size: 22),
              ],
            ),
          ),
        );
      }),
    );
  }
}
