import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:sigap/src/features/personalization/presentasion/controllers/settings/base_settings_controller.dart';

class TextSizeController extends BaseSettingsController {
  // Text size settings
  final RxDouble textScaleFactor = 1.0.obs;

  // Min and max scale values
  final double minTextScale = 0.8;
  final double maxTextScale = 1.4;

  // Preset text sizes
  final List<Map<String, dynamic>> textSizePresets = [
    {'label': 'Small', 'scale': 0.8},
    {'label': 'Normal', 'scale': 1.0},
    {'label': 'Large', 'scale': 1.2},
    {'label': 'Extra Large', 'scale': 1.4},
  ];

  @override
  void onInit() {
    super.onInit();
    loadSettings();
  }

  // Change text size
  void changeTextSize(double scale) {
    if (scale < minTextScale) scale = minTextScale;
    if (scale > maxTextScale) scale = maxTextScale;

    textScaleFactor.value = scale;
    _applyTextScale();
    saveSettings();
  }

  // Apply text scale to app
  void _applyTextScale() {
    // In a real app, you would need to update the MediaQuery data to affect the entire app
    // This is a simplified version for demonstration

    // MediaQuery approach (would require wrapping MaterialApp with a builder)
    // final MediaQueryData mediaQuery = MediaQuery.of(Get.context!);
    // final MediaQueryData updatedMediaQuery = mediaQuery.copyWith(textScaleFactor: textScaleFactor.value);

    // Since we can't directly modify MediaQuery here, we'll use this as a placeholder
    // The actual implementation would depend on your app's architecture
    debugPrint('Applied text scale factor: ${textScaleFactor.value}');
  }

  @override
  Future<bool> saveSettings() async {
    try {
      setLoading(true);

      // TODO: Save text size setting to persistent storage
      final prefs = Get.find<dynamic>(); // Replace with your storage solution
      // await prefs.setDouble('text_scale_factor', textScaleFactor.value);

      return true;
    } catch (e) {
      setError('Failed to save text size settings: ${e.toString()}');
      return false;
    } finally {
      setLoading(false);
    }
  }

  @override
  Future<void> loadSettings() async {
    try {
      setLoading(true);

      // TODO: Load text size setting from persistent storage
      final prefs = Get.find<dynamic>(); // Replace with your storage solution
      // final savedScale = prefs.getDouble('text_scale_factor') ?? 1.0;
      // textScaleFactor.value = savedScale;

      // Apply the loaded text scale
      _applyTextScale();
    } catch (e) {
      setError('Failed to load text size settings: ${e.toString()}');
    } finally {
      setLoading(false);
    }
  }
}
