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';
import '../widgets/system/system_header.dart';
import '../widgets/system/section_title.dart';
import '../widgets/system/system_stats.dart';
import '../widgets/system/palette_picker.dart';

/// Page "Système" : statistiques de jeu et sélection de la palette de couleurs.
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: [
          SystemHeader(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),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
