// ===========================================================================
// FILE: lib/services/storage_service.dart
// ===========================================================================

import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import '../core/app_colors.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/foundation.dart';

class StorageService {
  static final StorageService instance = StorageService._internal();
  StorageService._internal();

  late SharedPreferences _prefs;

  Future<void> init() async {
    _prefs = await SharedPreferences.getInstance();
    _checkDailyQuests(); // All'avvio controlliamo se ci sono nuove sfide
  }

  int get savedThemeIndex => _prefs.getInt('theme') ?? AppThemeType.minimal.index;
  Future<void> saveTheme(AppThemeType theme) async => await _prefs.setInt('theme', theme.index);

  int get savedRadius => _prefs.getInt('radius') ?? 2;
  Future<void> saveRadius(int radius) async => await _prefs.setInt('radius', radius);

  bool get isMuted => _prefs.getBool('isMuted') ?? false;
  Future<void> saveMuted(bool muted) async => await _prefs.setBool('isMuted', muted);

  int get totalXP => _prefs.getInt('totalXP') ?? 0;

  // Modificato per sincronizzare automaticamente la classifica su Firebase
  Future<void> addXP(int xp) async {
    await _prefs.setInt('totalXP', totalXP + xp);
    syncLeaderboard();
  }

  int get playerLevel => (totalXP / 100).floor() + 1;

  int get wins => _prefs.getInt('wins') ?? 0;
  Future<void> addWin() async {
    await _prefs.setInt('wins', wins + 1);
    syncLeaderboard();
  }

  int get losses => _prefs.getInt('losses') ?? 0;
  Future<void> addLoss() async => await _prefs.setInt('losses', losses + 1);

  int get cpuLevel => _prefs.getInt('cpuLevel') ?? 1;
  Future<void> saveCpuLevel(int level) async => await _prefs.setInt('cpuLevel', level);

  String get playerName => _prefs.getString('playerName') ?? '';
  Future<void> savePlayerName(String name) async {
    await _prefs.setString('playerName', name);
    syncLeaderboard(); // Aggiorna il nome in classifica
  }

  // --- NUOVO: SINCRONIZZAZIONE CLASSIFICA ONLINE ---
  Future<void> syncLeaderboard() async {
    if (playerName.isNotEmpty) {
      try {
        // Recuperiamo il nostro ID segreto e univoco appena creato
        final user = FirebaseAuth.instance.currentUser;

        if (user != null) {
          // Usiamo user.uid come nome del documento, NON più il playerName!
          await FirebaseFirestore.instance.collection('leaderboard').doc(user.uid).set({
            'name': playerName, // Il nome rimane dentro per mostrarlo nella lista
            'xp': totalXP,
            'level': playerLevel,
            'wins': wins,
            'lastActive': FieldValue.serverTimestamp(),
          }, SetOptions(merge: true));
        }
      } catch(e) {
        // Ignoriamo gli errori se manca la rete, si sincronizzerà dopo
        debugPrint("Errore sinc. classifica: $e");
      }
    }
  }

  // --- NUOVO: GESTIONE SFIDE GIORNALIERE ---
  void _checkDailyQuests() {
    String today = DateTime.now().toIso8601String().substring(0, 10);
    String lastDate = _prefs.getString('quest_date') ?? '';

    if (today != lastDate) {
      // Nuovo giorno, nuove sfide!
      _prefs.setString('quest_date', today);

      // Sfida 1: Gioca partite online
      _prefs.setInt('q1_type', 0);
      _prefs.setInt('q1_prog', 0);
      _prefs.setInt('q1_target', 3);

      // Sfida 2: Vinci contro la CPU
      _prefs.setInt('q2_type', 1);
      _prefs.setInt('q2_prog', 0);
      _prefs.setInt('q2_target', 2);

      // Sfida 3: Partite con forme speciali (Croce, Caos, ecc)
      _prefs.setInt('q3_type', 2);
      _prefs.setInt('q3_prog', 0);
      _prefs.setInt('q3_target', 2);
    }
  }

  Future<void> updateQuestProgress(int type, int amount) async {
    for(int i=1; i<=3; i++) {
      if (_prefs.getInt('q${i}_type') == type) {
        int prog = _prefs.getInt('q${i}_prog') ?? 0;
        int target = _prefs.getInt('q${i}_target') ?? 1;
        if (prog < target) {
          _prefs.setInt('q${i}_prog', prog + amount);
        }
      }
    }
  }

  // --- STORICO PARTITE ---
  List<Map<String, dynamic>> get matchHistory {
    List<String> history = _prefs.getStringList('matchHistory') ?? [];
    return history.map((e) => jsonDecode(e) as Map<String, dynamic>).toList();
  }

  Future<void> saveMatchToHistory({required String myName, required String opponent, required int myScore, required int oppScore, required bool isOnline}) async {
    List<String> history = _prefs.getStringList('matchHistory') ?? [];
    Map<String, dynamic> match = {
      'date': DateTime.now().toIso8601String(),
      'myName': myName, 'opponent': opponent, 'myScore': myScore, 'oppScore': oppScore, 'isOnline': isOnline,
    };
    history.insert(0, jsonEncode(match));
    if (history.length > 50) history = history.sublist(0, 50);
    await _prefs.setStringList('matchHistory', history);
  }
}