import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:syncrow_web/pages/routines/widgets/condition_toggle.dart';
import 'package:syncrow_web/pages/routines/widgets/function_slider.dart';
import 'package:syncrow_web/pages/routines/widgets/value_display.dart';

class SliderValueSelector extends StatelessWidget {
  final String? currentCondition;
  final String dialogType;
  final (double, double) sliderRange;
  final String displayedValue;
  final Object? initialValue;
  final void Function(String condition) onConditionChanged;
  final void Function(double value) onSliderChanged;
  final String unit;
  final double dividendOfRange;

  const SliderValueSelector({
    required this.dialogType,
    required this.sliderRange,
    required this.displayedValue,
    required this.initialValue,
    required this.onConditionChanged,
    required this.onSliderChanged,
    required this.currentCondition,
    required this.unit,
    required this.dividendOfRange,
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      spacing: 16,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        if (dialogType == 'IF')
          ConditionToggle(
            currentCondition: currentCondition,
            onChanged: onConditionChanged,
          ),
        ValueDisplay(
          value: initialValue,
          label: displayedValue,
          unit: unit,
        ),
        FunctionSlider(
          initialValue: initialValue,
          range: sliderRange,
          onChanged: onSliderChanged,
          dividendOfRange: dividendOfRange,
        ),
      ],
    );
  }
}

class RangeInputFormatter extends TextInputFormatter {
  const RangeInputFormatter({required this.min, required this.max});

  final double min;
  final double max;

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    final text = newValue.text;
    if (text.isEmpty) {
      return newValue;
    }

    final value = double.tryParse(text);
    if (value == null || value < min || value > max) {
      return oldValue;
    }

    return newValue;
  }
}
