import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../../core/services/theme_service.dart';

/// Settings state
class SettingsState {
  final ThemeMode themeMode;
  final bool isDarkModeAvailable;
  final bool isLoading;

  const SettingsState({
    required this.themeMode,
    required this.isDarkModeAvailable,
    this.isLoading = false,
  });

  SettingsState copyWith({
    ThemeMode? themeMode,
    bool? isDarkModeAvailable,
    bool? isLoading,
  }) {
    return SettingsState(
      themeMode: themeMode ?? this.themeMode,
      isDarkModeAvailable: isDarkModeAvailable ?? this.isDarkModeAvailable,
      isLoading: isLoading ?? this.isLoading,
    );
  }
}

/// Settings notifier
class SettingsNotifier extends StateNotifier<SettingsState> {
  SettingsNotifier()
    : super(
        SettingsState(
          themeMode: ThemeMode.light,
          isDarkModeAvailable: ThemeService.isDarkModeAvailable(),
        ),
      ) {
    loadSettings();
  }

  /// Set theme mode
  Future<void> setThemeMode(ThemeMode themeMode) async {
    state = state.copyWith(isLoading: true);
    await ThemeService.setThemeMode(themeMode);
    state = state.copyWith(themeMode: themeMode, isLoading: false);
  }

  /// Load settings from storage
  Future<void> loadSettings() async {
    state = state.copyWith(isLoading: true);
    final themeMode = await ThemeService.getStoredThemeMode();
    final isDarkModeAvailable = ThemeService.isDarkModeAvailable();
    state = state.copyWith(
      themeMode: themeMode,
      isDarkModeAvailable: isDarkModeAvailable,
      isLoading: false,
    );
  }

  /// Reset settings to default
  Future<void> resetSettings() async {
    state = state.copyWith(isLoading: true);
    await ThemeService.resetTheme();
    final themeMode = await ThemeService.getStoredThemeMode();
    state = state.copyWith(themeMode: themeMode, isLoading: false);
  }
}

/// Settings provider
final settingsProvider = StateNotifierProvider<SettingsNotifier, SettingsState>(
  (ref) => SettingsNotifier(),
);

/// Theme mode provider (convenience)
final themeModeProvider = Provider<ThemeMode>(
  (ref) => ref.watch(settingsProvider).themeMode,
);

/// Dark mode available provider (convenience)
final isDarkModeAvailableProvider = Provider<bool>(
  (ref) => ref.watch(settingsProvider).isDarkModeAvailable,
);
