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

class ThemeProvider extends ChangeNotifier {
  final _storage = const FlutterSecureStorage();

  ThemeMode _themeMode = ThemeMode.system;
  Color _accentColor = const Color(0xFF24A1DE);
  String? _wallpaperPath;

  ThemeMode get themeMode => _themeMode;
  Color get accentColor => _accentColor;
  String? get wallpaperPath => _wallpaperPath;

  bool isLight = false;

  ThemeProvider() {
    _loadSettings();
  }

  // Загрузка при старте
  Future<void> _loadSettings() async {
    final mode = await _storage.read(key: 'theme_mode');
    final color = await _storage.read(key: 'accent_color');
    final wallpaper = await _storage.read(key: 'wallpaper_path');

    if (mode != null) {
      _themeMode = mode == 'dark' ? ThemeMode.dark : ThemeMode.light;
      isLight = mode == 'light';
    }
    if (color != null) _accentColor = Color(int.parse(color));
    _wallpaperPath = wallpaper;
    notifyListeners();
  }

  void toggleTheme(bool isDark) {
    _themeMode = isDark ? ThemeMode.dark : ThemeMode.light;
    isLight = !isDark;
    _storage.write(key: 'theme_mode', value: isDark ? 'dark' : 'light');
    notifyListeners();
  }

  void updateAccentColor(Color newColor) {
    _accentColor = newColor;
    _storage.write(key: 'accent_color', value: newColor.value.toString());
    notifyListeners();
  }

  void updateWallpaper(String? path) {
    _wallpaperPath = path;
    if (path != null) {
      _storage.write(key: 'wallpaper_path', value: path);
    } else {
      _storage.delete(key: 'wallpaper_path');
    }
    notifyListeners();
  }

  ThemeData get themeData => ThemeData(
    useMaterial3: true,
    brightness: _themeMode == ThemeMode.dark
        ? Brightness.dark
        : Brightness.light,
    colorScheme: ColorScheme.fromSeed(
      seedColor: _accentColor,
      brightness: _themeMode == ThemeMode.dark
          ? Brightness.dark
          : Brightness.light,
    ),
    // Настраиваем глобальные стили текста
    textTheme: const TextTheme(
      bodyLarge: TextStyle(fontSize: 16.0),
      bodyMedium: TextStyle(fontSize: 14.0),
    ),
    appBarTheme: AppBarTheme(
      backgroundColor: _accentColor,
      foregroundColor: Colors.white,
      elevation: 0,
    ),
  );
}
