import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../auth/auth_provider.dart';

const _kThemeModeKey = 'theme_mode';

enum AppThemeMode { system, dark, light }

extension AppThemeModeMaterial on AppThemeMode {
  ThemeMode get materialMode => switch (this) {
        AppThemeMode.system => ThemeMode.system,
        AppThemeMode.dark => ThemeMode.dark,
        AppThemeMode.light => ThemeMode.light,
      };
}

class ThemeModeController extends AsyncNotifier<AppThemeMode> {
  @override
  Future<AppThemeMode> build() async {
    final storage = ref.watch(secureStorageProvider);
    final raw = await storage.read(key: _kThemeModeKey);
    return switch (raw) {
      'dark' => AppThemeMode.dark,
      'light' => AppThemeMode.light,
      _ => AppThemeMode.system,
    };
  }

  Future<void> set(AppThemeMode mode) async {
    final storage = ref.read(secureStorageProvider);
    await storage.write(key: _kThemeModeKey, value: mode.name);
    state = AsyncData(mode);
  }
}

final themeModeProvider =
    AsyncNotifierProvider<ThemeModeController, AppThemeMode>(
  ThemeModeController.new,
);
