import 'package:flutter/material.dart';
import 'package:syncrow_app/features/devices/model/device_model.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_medium.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/helpers/snack_bar.dart';
import 'package:syncrow_app/utils/resource_manager/color_manager.dart';
import 'package:syncrow_app/utils/resource_manager/font_manager.dart';

class MaxDistanceControl extends StatefulWidget {
  final String title;
  final String measurement;
  final DeviceModel sensor;
  final String value;

  final double min;
  final double max;

  const MaxDistanceControl({
    super.key,
    required this.title,
    required this.measurement,
    required this.sensor,
    required this.value,
    required this.min,
    required this.max,
  });

  @override
  MaxDistanceControlState createState() => MaxDistanceControlState();
}

int _parseValue(String value) {
  if (value.endsWith('s')) {
    return int.parse(value.replaceAll('s', '').trim());
  } else if (value.endsWith('min')) {
    return int.parse(value.replaceAll('min', '').trim()) * 60;
  } else if (value.endsWith('hour')) {
    return int.parse(value.replaceAll('hour', '').trim()) * 3600;
  }
  return 0; // Default to 0 if the format is unrecognized
}

class MaxDistanceControlState extends State<MaxDistanceControl> {
  final List<double> _stepValues = [
    0,
    10,
    30,
    60,
    120,
    300,
    600,
    1800,
    3600,
  ];

  late int _currentIndex;

  String _formatLabel(double seconds) {
    if (seconds == 0) return 'None';
    if (seconds < 60) return '${seconds.toInt()}s';
    if (seconds < 3600) {
      final minutes = (seconds / 60).round();
      return '${minutes}min';
    }
    final hours = (seconds / 3600).round();
    return '${hours}hr';
  }

  int _nearestStepIndex(double initialValue) {
    double minDiff = double.infinity;
    int nearestIndex = 0;
    for (int i = 0; i < _stepValues.length; i++) {
      final diff = (initialValue - _stepValues[i]).abs();
      if (diff < minDiff) {
        minDiff = diff;
        nearestIndex = i;
      }
    }
    return nearestIndex;
  }

  @override
  void initState() {
    super.initState();
    final int parsedSeconds = _parseValue(widget.value);
    _currentIndex = _nearestStepIndex(parsedSeconds.toDouble());
  }

  @override
  Widget build(BuildContext context) {
    final double currentSeconds = _stepValues[_currentIndex];
    return Dialog(
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(20),
        ),
        padding: const EdgeInsets.only(top: 20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            BodyMedium(
              text: widget.title,
              style: context.bodyMedium.copyWith(
                color: ColorsManager.primaryColorWithOpacity,
                fontWeight: FontsManager.extraBold,
              ),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(
                vertical: 15,
                horizontal: 50,
              ),
              child: Container(
                height: 1,
                width: double.infinity,
                color: ColorsManager.greyColor,
              ),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(
                vertical: 10,
              ),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  TitleMedium(
                    text: _formatLabel(currentSeconds)
                        .replaceAll('1hr', '1hour')
                        .replaceAllMapped(RegExp(r's$'), (match) => 'sec'),
                    style: context.titleMedium.copyWith(
                      color: Colors.black,
                      fontWeight: FontsManager.bold,
                    ),
                  ),
                  const SizedBox(width: 5),
                  TitleMedium(
                    text: widget.measurement,
                    style: context.titleMedium.copyWith(
                      color: Colors.black,
                      fontWeight: FontsManager.bold,
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(
              width: MediaQuery.sizeOf(context).width,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  IconButton(
                    onPressed: () {
                      setState(() {
                        _currentIndex =
                            (_currentIndex > 0) ? _currentIndex - 1 : 0;
                      });
                    },
                    icon: const Icon(
                      Icons.remove,
                      color: Colors.grey,
                    ),
                  ),
                  Flexible(
                    child: Slider(
                      min: 0,
                      max: (_stepValues.length - 1).toDouble(),
                      divisions: _stepValues.length - 1,
                      value: _currentIndex.toDouble(),
                      onChanged: (double newIndex) {
                        setState(() {
                          _currentIndex = newIndex.round();
                        });
                      },
                      label: _formatLabel(_stepValues[_currentIndex]),
                      inactiveColor: ColorsManager.greyColor,
                    ),
                  ),
                  IconButton(
                    onPressed: () {
                      setState(() {
                        _currentIndex = (_currentIndex < _stepValues.length - 1)
                            ? _currentIndex + 1
                            : _currentIndex;
                      });
                    },
                    icon: const Icon(
                      Icons.add,
                      color: Colors.grey,
                    ),
                  ),
                ],
              ),
            ),
            Container(
              height: 1,
              width: double.infinity,
              color: ColorsManager.greyColor,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                InkWell(
                  onTap: () => Navigator.pop(context),
                  child: Center(
                    child: BodyMedium(
                      text: 'Cancel',
                      style: context.bodyMedium.copyWith(
                        color: ColorsManager.greyColor,
                      ),
                    ),
                  ),
                ),
                Container(
                  height: 50,
                  width: 1,
                  color: ColorsManager.greyColor,
                ),
                InkWell(
                  onTap: () {
                    Future.delayed(const Duration(seconds: 1), () {
                      Navigator.pop(context, _formatLabel(currentSeconds));

                      if (widget.sensor.isOnline == null ||
                          widget.sensor.isOnline == false) {
                        CustomSnackBar.displaySnackBar('The device is offline');
                        return;
                      }
                    });
                  },
                  child: Center(
                    child: BodyMedium(
                      text: 'Confirm',
                      style: context.bodyMedium.copyWith(
                        color: ColorsManager.primaryColorWithOpacity,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
