import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/prank_sound.dart';
import '../models/prank_category.dart';

class DataManager {
  static final DataManager _instance = DataManager._internal();
  factory DataManager() => _instance;
  DataManager._internal();

  List<PrankCategory> categories = [];
  bool isLoading = true;

  final ValueNotifier<List<PrankSound>> favoritesNotifier = ValueNotifier([]);

  Future<void> loadData() async {
    if (categories.isNotEmpty) return;

    try {
      try {
        final String jsonString = await rootBundle.loadString('assets/data.json');
        final List<dynamic> jsonList = json.decode(jsonString);
        categories = jsonList.asMap().entries.map((entry) {
          return PrankCategory.fromJson(entry.value, entry.key);
        }).toList();
      } catch (e) {
        debugPrint("Assets not found, using dummy data.");
        categories = _generateDummyData();
      }

      await _loadFavoritesFromPrefs();

    } catch (e) {
      categories = _generateDummyData();
    } finally {
      isLoading = false;
    }
  }

  Future<void> _loadFavoritesFromPrefs() async {
    final prefs = await SharedPreferences.getInstance();
    final List<String> favTitles = prefs.getStringList('fav_titles') ?? [];

    List<PrankSound> tempFavs = [];
    for (var cat in categories) {
      for (var sound in cat.list) {
        if (favTitles.contains(sound.title)) {
          sound.isFavorite = true;
          tempFavs.add(sound);
        }
      }
    }
    favoritesNotifier.value = List.from(tempFavs);
  }

  Future<void> toggleFavorite(PrankSound sound) async {
    sound.isFavorite = !sound.isFavorite;

    final currentList = List<PrankSound>.from(favoritesNotifier.value);
    if (sound.isFavorite) {
      if (!currentList.contains(sound)) currentList.add(sound);
    } else {
      currentList.remove(sound);
    }
    favoritesNotifier.value = currentList;

    final prefs = await SharedPreferences.getInstance();
    final List<String> favTitles = currentList.map((e) => e.title).toList();
    await prefs.setStringList('fav_titles', favTitles);
  }

  List<PrankCategory> _generateDummyData() {
    const String sampleAudio = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3";

    return List.generate(6, (index) {
      return PrankCategory(
        categoryId: '$index',
        categoryName: ['Air Horn', 'Fart', 'Hair Clipper', 'Sneeze', 'Gun', 'Scream'][index],
        categoryUrl: 'https://via.placeholder.com/150',
        themeColor: [
          const Color(0xFF6C63FF),
          const Color(0xFFFF6584),
          const Color(0xFF32D74B),
          const Color(0xFFFF9F0A),
          const Color(0xFF30B0C7),
          const Color(0xFFFF453A)
        ][index],
        list: List.generate(5, (i) => PrankSound(
            title: 'Effect ${index + 1}-${i + 1}',
            mp3Url: sampleAudio,
            preUrl: ''
        )),
      );
    });
  }
}
