import 'package:flutter/material.dart';
import 'package:syncrow_web/pages/device_managment/shared/device_controls_container.dart';
import 'package:syncrow_web/pages/device_managment/shared/increament_decreament.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';

class PresenceUpdateData extends StatefulWidget {
  const PresenceUpdateData({
    super.key,
    required this.title,
    required this.value,
    required this.action,
    required this.minValue,
    required this.maxValue,
    required this.steps,
    this.description,
    this.valuesPercision = 0,
  });

  final String title;
  final double value;
  final double minValue;
  final double maxValue;
  final double steps;
  final Function action;
  final String? description;
  final int valuesPercision;

  @override
  State<PresenceUpdateData> createState() => _CurrentTempState();
}

class _CurrentTempState extends State<PresenceUpdateData> {
  late double _adjustedValue;

  @override
  void initState() {
    super.initState();
    _adjustedValue = _initialAdjustedValue(widget.value);
  }

  double _initialAdjustedValue(dynamic value) {
    if (value is int || value is double) {
      return value;
    } else {
      throw ArgumentError('Invalid value type: Expected int or double');
    }
  }

  void _onValueChanged(double newValue) {
    widget.action(newValue);
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return DeviceControlsContainer(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            widget.title,
            style: context.textTheme.bodySmall?.copyWith(
              color: ColorsManager.blackColor,
              fontWeight: FontWeight.w400,
              fontSize: 10,
            ),
          ),
          IncrementDecrementWidget(
              value: widget.value.toStringAsFixed(widget.valuesPercision),
              description: widget.description ?? '',
              descriptionColor: ColorsManager.blackColor,
              onIncrement: () {
                if (_adjustedValue < widget.maxValue) {
                  setState(() {
                    _adjustedValue = _adjustedValue + widget.steps;
                  });
                  _onValueChanged(_adjustedValue);
                }
              },
              onDecrement: () {
                if (_adjustedValue > widget.minValue) {
                  setState(() {
                    _adjustedValue = _adjustedValue - widget.steps;
                  });
                  _onValueChanged(_adjustedValue);
                }
              }),
        ],
      ),
    );
  }
}
