// ===========================================================================
// FILE: lib/ui/settings/settings_screen.dart
// ===========================================================================

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/theme_manager.dart';
import '../../core/app_colors.dart';
import '../../services/storage_service.dart';

class SettingsScreen extends StatefulWidget {
  const SettingsScreen({super.key});

  @override
  State<SettingsScreen> createState() => _SettingsScreenState();
}

class _SettingsScreenState extends State<SettingsScreen> {
  @override
  Widget build(BuildContext context) {
    final themeManager = context.watch<ThemeManager>();
    final theme = themeManager.currentColors;

    int playerLevel = StorageService.instance.playerLevel;

    return Scaffold(
      backgroundColor: theme.background,
      appBar: AppBar(
        title: Text("SELEZIONA TEMA", style: TextStyle(fontWeight: FontWeight.bold, color: theme.text)),
        backgroundColor: Colors.transparent,
        elevation: 0,
        iconTheme: IconThemeData(color: theme.text),
      ),
      body: ListView(
        padding: const EdgeInsets.all(20),
        children: [
          _ThemeCard(
            title: "Minimal",
            subtitle: "Linee pulite, sfondo chiaro",
            type: AppThemeType.minimal,
            previewColors: AppColors.minimal,
            requiredLevel: 1,
            currentLevel: playerLevel,
          ),
          const SizedBox(height: 15),
          _ThemeCard(
            title: "Legno & Fiammiferi",
            subtitle: "Tavolo di legno, linee come fiammiferi",
            type: AppThemeType.wood,
            previewColors: AppColors.wood,
            requiredLevel: 3,
            currentLevel: playerLevel,
          ),
          const SizedBox(height: 15),
          _ThemeCard(
            title: "Quaderno (Doodle)",
            subtitle: "Sfondo a quadretti, tratto a penna",
            type: AppThemeType.doodle,
            previewColors: AppColors.doodle,
            requiredLevel: 5,
            currentLevel: playerLevel,
          ),
          const SizedBox(height: 15),
          _ThemeCard(
            title: "Cyberpunk",
            subtitle: "Nero profondo, luci al neon",
            type: AppThemeType.cyberpunk,
            previewColors: AppColors.cyberpunk,
            requiredLevel: 7,
            currentLevel: playerLevel,
          ),
          const SizedBox(height: 15),
          _ThemeCard(
            title: "8-Bit Arcade",
            subtitle: "Sale giochi, fosfori verdi e pixel",
            type: AppThemeType.arcade,
            previewColors: AppColors.arcade,
            requiredLevel: 10,
            currentLevel: playerLevel,
          ),
          const SizedBox(height: 15),
          _ThemeCard(
            title: "Grimorio",
            subtitle: "Incantesimi antichi, rune magiche",
            type: AppThemeType.grimorio,
            previewColors: AppColors.grimorio,
            requiredLevel: 15,
            currentLevel: playerLevel,
          ),
        ],
      ),
    );
  }
}

class _ThemeCard extends StatelessWidget {
  final String title;
  final String subtitle;
  final AppThemeType type;
  final ThemeColors previewColors;
  final int requiredLevel;
  final int currentLevel;

  const _ThemeCard({
    required this.title,
    required this.subtitle,
    required this.type,
    required this.previewColors,
    required this.requiredLevel,
    required this.currentLevel,
  });

  @override
  Widget build(BuildContext context) {
    final themeManager = context.watch<ThemeManager>();
    bool isSelected = themeManager.currentThemeType == type;
    bool isLocked = currentLevel < requiredLevel;

    return GestureDetector(
      onTap: () {
        if (isLocked) {
          ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text("Gioca per raggiungere il Liv. $requiredLevel e sbloccare questo tema!", style: const TextStyle(fontWeight: FontWeight.bold, color: Colors.white)),
                backgroundColor: Colors.redAccent,
                behavior: SnackBarBehavior.floating,
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                duration: const Duration(seconds: 2),
              )
          );
          return;
        }

        themeManager.setTheme(type);
        Navigator.pop(context);
      },
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 300),
        padding: const EdgeInsets.all(20),
        decoration: BoxDecoration(
          color: isLocked ? previewColors.background.withOpacity(0.4) : previewColors.background,
          borderRadius: BorderRadius.circular(20),
          border: Border.all(
            color: isSelected
                ? previewColors.playerBlue
                : (isLocked ? Colors.grey.withOpacity(0.3) : previewColors.gridLine.withOpacity(0.5)),
            width: isSelected ? 4 : 2,
          ),
          boxShadow: isSelected ? [BoxShadow(color: previewColors.playerBlue.withOpacity(0.4), blurRadius: 10, spreadRadius: 2)] : [],
        ),
        child: Stack(
          alignment: Alignment.center,
          children: [
            Opacity(
              opacity: isLocked ? 0.25 : 1.0,
              child: Row(
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(title, style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: previewColors.text)),
                        Text(subtitle, style: TextStyle(fontSize: 14, color: previewColors.text.withOpacity(0.7))),
                      ],
                    ),
                  ),
                  Container(width: 20, height: 20, decoration: BoxDecoration(color: previewColors.playerRed, shape: BoxShape.circle)),
                  const SizedBox(width: 10),
                  Container(width: 20, height: 20, decoration: BoxDecoration(color: previewColors.playerBlue, shape: BoxShape.circle)),
                ],
              ),
            ),
            if (isLocked)
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.85),
                  borderRadius: BorderRadius.circular(20),
                  border: Border.all(color: Colors.white.withOpacity(0.2), width: 1.5),
                  boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.5), blurRadius: 10, offset: const Offset(0, 4))],
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const Icon(Icons.lock_rounded, color: Colors.white, size: 20),
                    const SizedBox(width: 8),
                    Text(
                        "LIV. $requiredLevel",
                        style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w900, fontSize: 16, letterSpacing: 2)
                    ),
                  ],
                ),
              ),
          ],
        ),
      ),
    );
  }
}