import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hmg_patient_app_new/features/profile_settings/profile_settings_view_model.dart';
import 'package:provider/provider.dart';

/// Widget that preserves original SVG icon colors even when visual mode filters are active
/// Wraps any SvgPicture widget and applies reverse filters to cancel out accessibility filters
class PreserveSvgColors extends StatelessWidget {
  final Widget child;

  const PreserveSvgColors({
    super.key,
    required this.child,
  });

  @override
  Widget build(BuildContext context) {
    return Consumer<ProfileSettingsViewModel>(
      builder: (context, profileVm, _) {
        final visualMode = profileVm.visualMode;

        // If no filter is active, just return the child
        if (visualMode == 'off') {
          return child;
        }

        // Apply reverse filter to cancel out the app-wide filter
        return _applyReverseFilter(visualMode, child);
      },
    );
  }

  /// Apply reverse filter to cancel out the parent filter effect
  Widget _applyReverseFilter(String visualMode, Widget child) {
    switch (visualMode) {
      case 'invert':
        // Apply invert filter again to reverse the inversion (double negative = positive)
        return ColorFiltered(
          colorFilter: const ColorFilter.matrix(<double>[
            -1, 0, 0, 0, 255, // Red channel inverted back
            0, -1, 0, 0, 255, // Green channel inverted back
            0, 0, -1, 0, 255, // Blue channel inverted back
            0, 0, 0, 1, 0, // Alpha channel unchanged
          ]),
          child: child,
        );

      case 'dim':
        // Dim mode uses screen brightness control only - no filters applied
        // So no reverse filter needed
        return child;

      case 'highContrast':
        // For high contrast, apply color saturation to restore colors
        // This won't perfectly restore original colors but helps icons stand out
        return ColorFiltered(
          colorFilter: const ColorFilter.matrix(<double>[
            1.5, 0, 0, 0, 0, // Boost red
            0, 1.5, 0, 0, 0, // Boost green
            0, 0, 1.5, 0, 0, // Boost blue
            0, 0, 0, 1, 0, // Alpha unchanged
          ]),
          child: child,
        );

      default:
        return child;
    }
  }
}

/// Extension on SvgPicture to easily wrap with PreserveSvgColors
extension SvgAccessibility on SvgPicture {
  Widget preserveColors() {
    return PreserveSvgColors(child: this);
  }
}

