import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_status.dart';
import 'package:syncrow_web/pages/device_managment/curtain_module/bloc/curtain_module_bloc.dart';
import 'package:syncrow_web/pages/device_managment/curtain_module/models/curtain_module_model.dart';
import 'package:syncrow_web/pages/device_managment/curtain_module/widgets/curtain_action_widget.dart';
import 'package:syncrow_web/pages/device_managment/shared/device_controls_container.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';

class ControlCurtainMovementWidget extends StatelessWidget {
  final List<String> devicesId;
  const ControlCurtainMovementWidget({
    super.key,
    required this.devicesId,
  });

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 550,
      child: DeviceControlsContainer(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CurtainActionWidget(
              icon: Assets.openCurtain,
              onTap: () {
                if (devicesId.length == 1) {
                  context.read<CurtainModuleBloc>().add(
                        OpenCurtainEvent(deviceId: devicesId.first),
                      );
                } else {
                  context.read<CurtainModuleBloc>().add(
                        OpenCurtainBatchEvent(devicesId: devicesId),
                      );
                }
              },
            ),
            const SizedBox(
              width: 30,
            ),
            CurtainActionWidget(
              icon: Assets.pauseCurtain,
              onTap: () {
                if (devicesId.length == 1) {
                  context.read<CurtainModuleBloc>().add(
                        StopCurtainEvent(deviceId: devicesId.first),
                      );
                } else {
                  context.read<CurtainModuleBloc>().add(
                        StopCurtainBatchEvent(devicesId: devicesId),
                      );
                }
              },
            ),
            const SizedBox(
              width: 30,
            ),
            CurtainActionWidget(
              icon: Assets.closeCurtain,
              onTap: () {
                if (devicesId.length == 1) {
                  context.read<CurtainModuleBloc>().add(
                        CloseCurtainEvent(deviceId: devicesId.first),
                      );
                } else {
                  context.read<CurtainModuleBloc>().add(
                        CloseCurtainBatchEvent(devicesId: devicesId),
                      );
                }
              },
            ),
            BlocBuilder<CurtainModuleBloc, CurtainModuleState>(
              builder: (context, state) {
                if (state is CurtainModuleError) {
                  return Center(
                    child: Text(
                      state.message,
                      style: const TextStyle(
                        color: ColorsManager.minBlueDot,
                        fontSize: 16,
                      ),
                    ),
                  );
                } else if (state is CurtainModuleLoading) {
                  return const Center(
                    child: CircularProgressIndicator(
                      color: ColorsManager.minBlueDot,
                    ),
                  );
                } else if (state is CurtainModuleInitial) {
                  return const Center(
                    child: Text(
                      'No data available',
                      style: TextStyle(
                        color: ColorsManager.minBlueDot,
                        fontSize: 16,
                      ),
                    ),
                  );
                } else if (state is CurtainModuleStatusLoaded) {
                  return CurtainSliderWidget(
                    status: state.curtainModuleStatus,
                    devicesId: devicesId,
                  );
                } else {
                  return const Center(
                    child: Text(
                      'Unknown state',
                      style: TextStyle(
                        color: ColorsManager.minBlueDot,
                        fontSize: 16,
                      ),
                    ),
                  );
                }
              },
            )
          ],
        ),
      ),
    );
  }
}

class CurtainSliderWidget extends StatefulWidget {
  final CurtainModuleStatusModel status;
  final List<String> devicesId;

  const CurtainSliderWidget({
    super.key,
    required this.status,
    required this.devicesId,
  });

  @override
  State<CurtainSliderWidget> createState() => _CurtainSliderWidgetState();
}

class _CurtainSliderWidgetState extends State<CurtainSliderWidget> {
  double? _localValue; // For temporary drag state

  @override
  Widget build(BuildContext context) {
    // If user is dragging, use local value. Otherwise, use Firebase-synced state
    final double currentSliderValue =
        _localValue ?? widget.status.percentControl / 100;

    return Column(
      children: [
        Text(
          '${(currentSliderValue * 100).round()}%',
          style: const TextStyle(
            color: ColorsManager.minBlueDot,
            fontSize: 25,
            fontWeight: FontWeight.bold,
          ),
        ),
        Slider(
          value: currentSliderValue,
          min: 0,
          max: 1,
          divisions: 10, // 10% step
          activeColor: ColorsManager.minBlueDot,
          thumbColor: ColorsManager.primaryColor,
          inactiveColor: ColorsManager.whiteColors,

          // Start dragging — use local control
          onChangeStart: (_) {
            setState(() {
              _localValue = currentSliderValue;
            });
          },

          // While dragging — update temporary value
          onChanged: (value) {
            final steppedValue = (value * 10).roundToDouble() / 10;
            setState(() {
              _localValue = steppedValue;
            });
          },

          // On release — send API and return to Firebase-controlled state
          onChangeEnd: (value) {
            final int targetPercent = (value * 100).round();

            if (widget.devicesId.length == 1) {
              context.read<CurtainModuleBloc>().add(
                    SendCurtainPercentToApiEvent(
                      deviceId: widget.devicesId.first,
                      status: Status(
                        code: 'percent_control',
                        value: targetPercent,
                      ),
                    ),
                  );
            } else {
              context.read<CurtainModuleBloc>().add(
                    SendCurtainBatchPercentToApiEvent(
                      devicesId: widget.devicesId,
                      status: Status(
                        code: 'percent_control',
                        value: targetPercent,
                      ),
                    ),
                  );
            }

            // Revert back to Firebase-synced stream
            setState(() {
              _localValue = null;
            });
          },
        ),
      ],
    );
  }
}
