import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/scene/bloc/create_scene/create_scene_bloc.dart';
import 'package:syncrow_app/features/scene/model/scene_static_function.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/title_medium.dart';
import 'package:syncrow_app/utils/context_extension.dart';
import 'package:syncrow_app/utils/resource_manager/color_manager.dart';

class AlertDialogSliderSteps extends StatefulWidget {
  const AlertDialogSliderSteps(
      {super.key,
      this.functionValue,
      required this.taskItem,
      required this.isAutomation,
      });

  final dynamic functionValue;
  final SceneStaticFunction taskItem;
  final bool isAutomation;

  @override
  State<AlertDialogSliderSteps> createState() => _AlertDialogSliderStepsState();
}

class _AlertDialogSliderStepsState extends State<AlertDialogSliderSteps> {
  double? groupValue;
  int selectedToggleIndex = 1;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final createSceneBloc = context.read<CreateSceneBloc>();

    if (widget.taskItem.comparator != null) {
      selectedToggleIndex = _comparatorToIndex(widget.taskItem.comparator);
    }

    if (widget.isAutomation) {
      final automationTempTaskList = createSceneBloc.automationTempTasksList;
      final automationComparatorValues =
          createSceneBloc.automationComparatorValues;

      for (var element in automationTempTaskList) {
        if (element.code == widget.taskItem.code) {
          groupValue = element.functionValue;
          selectedToggleIndex =
              _comparatorToIndex(automationComparatorValues[element.code]);
        }
      }
    }
    if (widget.taskItem.code == 'temp_current') {
      if (widget.functionValue != null) {
        groupValue = _normalizeValue(
            double.tryParse(widget.functionValue.toString()) ??
                widget.taskItem.operationalValues[0].minValue);
      } else {
        groupValue = widget.taskItem.operationalValues[0].minValue;
      }
    } else {
      if (widget.functionValue != null) {
        groupValue = _normalizeValue(widget.functionValue);
      } else {
        groupValue =
            _normalizeValue(widget.taskItem.operationalValues[0].minValue);
      }
    }

    setState(() {});

    context.read<CreateSceneBloc>().add(
          SelectedValueEvent(
            value: _deNormalizeValue(groupValue),
            code: widget.taskItem.code,
            isAutomation: widget.isAutomation,
            comparator: _indexToComparator(selectedToggleIndex),
          ),
        );
  }

  int _comparatorToIndex(String? comparator) {
    switch (comparator) {
      case "<":
        return 0;
      case "==":
        return 1;
      case ">":
        return 2;
      default:
        return 1;
    }
  }

  String _indexToComparator(int index) {
    switch (index) {
      case 0:
        return "<";
      case 1:
        return "==";
      case 2:
        return ">";
      default:
        return "==";
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        widget.isAutomation
            ? ToggleButtons(
                isSelected: [
                  selectedToggleIndex == 0,
                  selectedToggleIndex == 1,
                  selectedToggleIndex == 2
                ],
                onPressed: (index) {
                  setState(() {
                    selectedToggleIndex = index;
                  });
                  context.read<CreateSceneBloc>().add(
                        SelectedValueEvent(
                          value: _deNormalizeValue(groupValue),
                          code: widget.taskItem.code,
                          isAutomation: widget.isAutomation,
                          comparator: _indexToComparator(selectedToggleIndex),
                        ),
                      );
                },
                borderRadius: BorderRadius.circular(30),
                selectedColor: Colors.white,
                color: ColorsManager.blackColor,
                fillColor: ColorsManager.primaryColorWithOpacity,
                borderColor: ColorsManager.greyColor,
                constraints: BoxConstraints.tight(const Size(70, 30)),
                children: [
                  SizedBox(
                    width: 70,
                    height: 30,
                    child: Container(
                      color: selectedToggleIndex == 0
                          ? ColorsManager.primaryColorWithOpacity
                          : ColorsManager.greyColor,
                      alignment: Alignment.center,
                      child: const Text("<"),
                    ),
                  ),
                  SizedBox(
                    width: 70,
                    height: 30,
                    child: Container(
                      color: selectedToggleIndex == 1
                          ? ColorsManager.primaryColorWithOpacity
                          : ColorsManager.greyColor,
                      alignment: Alignment.center,
                      child: const Text("="),
                    ),
                  ),
                  SizedBox(
                    width: 70,
                    height: 30,
                    child: Container(
                      color: selectedToggleIndex == 2
                          ? ColorsManager.primaryColorWithOpacity
                          : ColorsManager.greyColor,
                      alignment: Alignment.center,
                      child: const Text(">"),
                    ),
                  ),
                ],
              )
            : SizedBox(),
        const SizedBox(height: 12),
        ...widget.taskItem.operationalValues.map(
          (operation) => BlocBuilder<CreateSceneBloc, CreateSceneState>(
            builder: (context, state) {
              return Column(
                children: [
                  const SizedBox(height: 12),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      TitleMedium(
                        text: groupValue != null
                            ? (groupValue! % 1 == 0
                                ? groupValue!.toStringAsFixed(0)
                                : groupValue!.toStringAsFixed(1))
                            : "0",
                        style: context.titleMedium.copyWith(
                          color: ColorsManager.primaryColorWithOpacity,
                          fontSize: 30,
                        ),
                      ),
                      const SizedBox(width: 8),
                      TitleMedium(
                        text: operation.description.toString(),
                        style: context.titleMedium.copyWith(
                          color: ColorsManager.primaryColorWithOpacity,
                          fontSize: 30,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 8),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 8),
                    child: Slider(
                      value: groupValue ?? 0,
                      min: operation.minValue ?? 0,
                      max: operation.maxValue ?? 0,
                      inactiveColor: ColorsManager.primaryColorWithOpacity
                          .withOpacity(0.2),
                      divisions: operation.stepValue != null
                          ? ((operation.maxValue!.toDouble() -
                                      operation.minValue!.toDouble()) /
                                  operation.stepValue!.toDouble())
                              .round()
                          : null,
                      onChanged: (value) {
                        setState(() {
                          groupValue = normalizeToDoubleValue(value);
                        });
                        context.read<CreateSceneBloc>().add(SelectedValueEvent(
                            value: _deNormalizeValue(groupValue),
                            code: widget.taskItem.code,
                            isAutomation: widget.isAutomation,
                            comparator:
                                _indexToComparator(selectedToggleIndex)));
                      },
                    ),
                  ),
                  const SizedBox(height: 12),
                ],
              );
            },
          ),
        ),
      ],
    );
  }

  double _normalizeValue(dynamic value) {
    if ((widget.taskItem.code == "temp_set" && value > 199) ||
        (widget.taskItem.code == "temp_current" && value >= -99.0)) {
      return (value) / 10;
    }
    return value.toDouble();
  }

  double? normalizeToDoubleValue(double value) {
    return double.tryParse(value.toStringAsFixed(1));
  }

  double _deNormalizeValue(double? value) {
    if (widget.taskItem.code == "temp_set" ||
        widget.taskItem.code == "temp_current") {
      return (value ?? 0) * 10;
    }
    return value ?? 0;
  }
}
