import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_app/features/devices/bloc/devices_cubit.dart';
import 'package:syncrow_app/features/devices/model/device_control_model.dart';
import 'package:syncrow_app/features/devices/model/device_model.dart';
import 'package:syncrow_app/generated/assets.dart';
import 'package:syncrow_app/utils/resource_manager/color_manager.dart';

class CustomSwitch extends StatefulWidget {
  const CustomSwitch({Key? key, required this.device}) : super(key: key);

  final DeviceModel device;

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

bool isCurtainOpen(DeviceModel device) {
  // Find the status with code == 'percent_control'
  final curtainStatus = device.status.firstWhere(
    (s) => s.code == 'percent_control',
    // orElse: () => null,
  );

  // We consider it "on/open" if percent_control == 100
  return curtainStatus.value >= 20;
}

class _CustomSwitchState extends State<CustomSwitch> {
  bool _isLoading = false;

  bool isDeviceOn(DeviceModel device) {
    // If it's a curtain, check percent_control
    if (device.type == "CUR") {
      return isCurtainOpen(device);
    }

    // Otherwise, default to your existing switch logic
    final switchStatuses = device.status.where(
      (s) => (s.code?.startsWith('switch') ?? false),
    );
    final anySwitchFalse = switchStatuses.any((s) => s.value == false);
    return !anySwitchFalse;
  }

  Widget _buildLoadingIndicator() {
    return const SizedBox(
      width: 45,
      height: 28,
      child: Center(
        child: SizedBox(
          width: 22,
          height: 22,
          child: CircularProgressIndicator(
            strokeWidth: 2,
            color: ColorsManager.primaryColor,
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final isSwitch = widget.device.categoryName == 'Switch';
    if (!isSwitch &&
        widget.device.type != "AC" &&
        widget.device.type != "GD" &&
        widget.device.type != "CUR") {
      return const SizedBox();
    }
    final isOn = isDeviceOn(widget.device);

    return GestureDetector(
      onTap: () async {
        setState(() {
          _isLoading = true;
        });

        final newValue = !isOn;
        String code;
        dynamic controlValue;

        if (widget.device.type == "AC") {
          code = "switch";
          controlValue = newValue;
        } else if (widget.device.type == "CUR") {
          code = "percent_control";
          controlValue = newValue ? "close" : "open";
        } else {
          code = "switch_1";
          controlValue = newValue;
        }

        final control = DeviceControlModel(
          code: code,
          value: controlValue,
          deviceId: widget.device.uuid!,
        );
        try {
          if (widget.device.type == "CUR") {
            await context
                .read<DevicesCubit>()
                .changeCurtainSwitch(control, widget.device.uuid!);
          } else if (widget.device.type == "1GT") {
            await context
                .read<DevicesCubit>()
                .oneGTGangToggle(control, widget.device.uuid!);
          } else if (widget.device.type == "2GT") {
            await context
                .read<DevicesCubit>()
                .towGTGangToggle(control, widget.device.uuid!);
          } else if (widget.device.type == "3G") {
            await context
                .read<DevicesCubit>()
                .threeGangToggle(control, widget.device.uuid!);
          } else if (widget.device.type == "2G") {
            await context
                .read<DevicesCubit>()
                .towGangToggle(control, widget.device.uuid!);
          } else if (widget.device.type == "1G") {
            await context
                .read<DevicesCubit>()
                .oneGangToggle(control, widget.device.uuid!);
          } else {
            await context
                .read<DevicesCubit>()
                .deviceControl(control, widget.device.uuid!);
          }
        } finally {
          setState(() {
            _isLoading = false;
          });
        }
      },
      child: _isLoading
          ? _buildLoadingIndicator()
          : SizedBox(
              child: SvgPicture.asset(
                isOn ? Assets.toggleSwitchSmall : Assets.offToggleSwitchSmall,
              ),
            ),
    );
  }
}
