import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/device_managment/ac/bloc/ac_bloc.dart';
import 'package:syncrow_web/pages/device_managment/ac/bloc/ac_event.dart';
import 'package:syncrow_web/pages/device_managment/shared/celciuse_symbol.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';

class BatchCurrentTemp extends StatefulWidget {
  const BatchCurrentTemp({
    super.key,
    required this.code,
    required this.devicesIds,
    required this.currentTemp,
    required this.tempSet,
    this.isBatch,
  });

  final String code;
  final List<String> devicesIds;
  final int currentTemp;
  final int tempSet;
  final bool? isBatch;

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

class _CurrentTempState extends State<BatchCurrentTemp> {
  late double _adjustedValue;
  Timer? _debounce;

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

  double _initialAdjustedValue(dynamic value) {
    if (value is int || value is double) {
      double doubleValue = value.toDouble();
      return doubleValue > 99 ? doubleValue / 10 : doubleValue;
    } else {
      throw ArgumentError('Invalid value type: Expected int or double');
    }
  }

  void _onValueChanged(double newValue) {
    if (_debounce?.isActive ?? false) {
      _debounce?.cancel();
    }
    _debounce = Timer(const Duration(milliseconds: 500), () {
      context.read<AcBloc>().add(
            AcBatchControlEvent(
              devicesIds: widget.devicesIds,
              code: widget.code,
              value: (newValue * 10).toInt(),
            ),
          );
    });
  }

  @override
  void dispose() {
    _debounce?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return DeviceControlsContainer(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          widget.isBatch == true
              ? Text(
                  'Set Temperature',
                  style: Theme.of(context).textTheme.bodySmall!.copyWith(color: Colors.grey),
                )
              : Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'Current Temperature',
                      style: Theme.of(context).textTheme.bodySmall!.copyWith(color: Colors.grey),
                    ),
                    const SizedBox(
                      height: 5,
                    ),
                    Row(
                      children: [
                        Text(
                          (widget.currentTemp > 99 ? widget.currentTemp / 10 : widget.currentTemp).toString(),
                          style: Theme.of(context).textTheme.bodySmall!.copyWith(color: Colors.grey),
                        ),
                        const CelsiusSymbol(
                          color: Colors.grey,
                        )
                      ],
                    ),
                  ],
                ),
          const Spacer(),
          IncrementDecrementWidget(
              value: _adjustedValue.toString(),
              description: '°C',
              descriptionColor: ColorsManager.dialogBlueTitle,
              onIncrement: () {
                if (_adjustedValue < 30) {
                  setState(() {
                    _adjustedValue = _adjustedValue + 0.5;
                  });
                  _onValueChanged(_adjustedValue);
                }
              },
              onDecrement: () {
                if (_adjustedValue > 20) {
                  setState(() {
                    _adjustedValue = _adjustedValue - 0.5;
                  });
                  _onValueChanged(_adjustedValue);
                }
              }),
        ],
      ),
    );
  }
}
