import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/app_layout/bloc/home_cubit.dart';
import 'package:syncrow_app/features/scene/bloc/create_scene/create_scene_bloc.dart';
import 'package:syncrow_app/features/scene/enum/create_scene_enum.dart';
import 'package:syncrow_app/features/scene/enum/operation_dialog_type.dart';
import 'package:syncrow_app/features/scene/model/create_automation_model.dart';
import 'package:syncrow_app/features/scene/model/create_scene_model.dart';
import 'package:syncrow_app/features/scene/model/scene_static_function.dart';
import 'package:syncrow_app/features/scene/widgets/alert_dialogs/alert_dialog_countdown.dart';
import 'package:syncrow_app/features/scene/widgets/alert_dialogs/alert_dialog_counter.dart';
import 'package:syncrow_app/features/scene/widgets/alert_dialogs/alert_dialog_functions_body.dart';
import 'package:syncrow_app/features/scene/widgets/alert_dialogs/alert_dialog_slider_steps.dart';
import 'package:syncrow_app/features/scene/widgets/alert_dialogs/alert_dialog_temperature_body.dart';
import 'package:syncrow_app/utils/context_extension.dart';

mixin SceneLogicHelper {
  bool isOnlyDelayOrDelayLast(List<SceneStaticFunction> tasks) {
    final lastTask = tasks.isNotEmpty ? tasks.last : null;

    return tasks.isNotEmpty
        ? tasks.every((task) => task.code == 'delay') ||
            lastTask!.code == 'delay' ||
            lastTask.deviceId == 'delay'
        : false;
  }

  void handleSaveButtonPress(
    BuildContext context, {
    required bool updateScene,
    required String sceneId,
    required bool isAutomation,
    required TextEditingController sceneName,
    required List<SceneStaticFunction> actions,
    required List<SceneStaticFunction> conditions,
  }) {
    final sceneBloc = context.read<CreateSceneBloc>();
    final effectiveTime = sceneBloc.effectiveTime;

    if (isOnlyDelayOrDelayLast(actions)) {
      context.showCustomSnackbar(
        message: 'A single delay or delay-last operations are NOT allowed.',
        icon: const Icon(
          Icons.error,
          color: Colors.red,
        ),
      );
      return;
    }

    if (isAutomation == true && effectiveTime?.loops == '0000000') {
      context.showCustomSnackbar(
        message: 'At least one day in Effective Period must be selected!',
        icon: const Icon(
          Icons.error,
          color: Colors.red,
        ),
      );
      return;
    }

    if (isAutomation) {
      final createAutomationModel = CreateAutomationModel(
        unitUuid: HomeCubit.getInstance().selectedSpace?.id ?? '',
        automationName: sceneName.text,
        decisionExpr: sceneBloc.conditionRule,
        effectiveTime: sceneBloc.effectiveTime ??
            EffectiveTime(start: '00:00', end: '23:59', loops: '1111111'),
        conditions: List.generate(
          conditions.length,
          (index) {
            final task = conditions[index];
            return CreateCondition(
              code: index + 1,
              entityId: task.deviceId,
              entityType: 'device_report',
              expr: ConditionExpr(
                statusCode: task.code,
                comparator: task.comparator ?? '==',
                statusValue: task.functionValue,
              ),
            );
          },
        ),
        actions: [
          ...List.generate(
            actions.length,
            (index) {
              final task = actions[index];
              if (task.deviceId == 'delay') {
                return CreateSceneAction(
                  productType: task.deviceType,
                  entityId: actions[index].deviceId,
                  actionExecutor: 'delay',
                  executorProperty: CreateSceneExecutorProperty(
                    functionCode: '',
                    functionValue: '',
                    delaySeconds: task.functionValue ?? 1,
                  ),
                );
              }
              if (task.code == CreateSceneEnum.smartSceneSelect.name) {
                return CreateSceneAction(
                    productType: task.deviceType,
                    actionType: task.operationName.toLowerCase() == 'automation'
                        ? 'automation'
                        : 'scene',
                    entityId: actions[index].deviceId,
                    actionExecutor: actions[index].functionValue,
                    executorProperty: null);
              }
              return CreateSceneAction(
                productType: task.deviceType,
                entityId: task.deviceId,
                actionExecutor: 'device_issue',
                executorProperty: CreateSceneExecutorProperty(
                  functionCode: task.code,
                  functionValue: task.functionValue,
                  delaySeconds: 0,
                ),
              );
            },
          ),
        ],
      );
      for (var action in createAutomationModel.actions) {
        if (action.productType == 'NCPS') {
          if (action.executorProperty!.functionCode == 'near_detection' ||
              action.executorProperty!.functionCode == 'far_detection') {
            action.executorProperty!.functionValue =
                (action.executorProperty!.functionValue * 100).round();
          } else if (action.executorProperty!.functionCode ==
                  'presence_delay' ||
              action.executorProperty!.functionCode == 'none_delay') {
            action.executorProperty!.functionValue =
                (action.executorProperty!.functionValue * 10).round();
          }
        }
      }
      sceneBloc.add(CreateSceneWithTasksEvent(
        createSceneModel: null,
        updateScene: updateScene,
        sceneId: sceneId,
        createAutomationModel: createAutomationModel,
      ));
    } else {
      final createSceneModel = CreateSceneModel(
        spaceUuid: HomeCubit.getInstance().selectedSpace?.id ?? '',
        iconId: sceneBloc.selectedIcon,
        showInDevice: sceneBloc.showInDeviceScreen,
        sceneName: sceneName.text,
        decisionExpr: 'and',
        actions: [
          ...List.generate(
            actions.length,
            (index) {
              final task = actions[index];
              if (task.deviceId == 'delay') {
                return CreateSceneAction(
                  productType: task.deviceType,
                  entityId: actions[index].deviceId,
                  actionExecutor: 'delay',
                  executorProperty: CreateSceneExecutorProperty(
                    functionCode: '',
                    functionValue: '',
                    delaySeconds: task.functionValue,
                  ),
                );
              }
              if (task.code == CreateSceneEnum.smartSceneSelect.name) {
                return CreateSceneAction(
                    productType: task.deviceType,
                    entityId: actions[index].deviceId,
                    actionExecutor: actions[index].functionValue,
                    executorProperty: null);
              }

              return CreateSceneAction(
                productType: task.deviceType,
                entityId: task.deviceId,
                actionExecutor: 'device_issue',
                executorProperty: CreateSceneExecutorProperty(
                  functionCode: task.code,
                  functionValue: task.functionValue,
                  delaySeconds: 0,
                ),
              );
            },
          ),
        ],
      );
      for (var action in createSceneModel.actions) {
        if (action.productType == 'NCPS') {
          if (action.executorProperty!.functionCode == 'near_detection' ||
              action.executorProperty!.functionCode == 'far_detection') {
            action.executorProperty!.functionValue =
                (action.executorProperty!.functionValue * 100).round();
          } else if (action.executorProperty!.functionCode ==
                  'presence_delay' ||
              action.executorProperty!.functionCode == 'none_delay') {
            action.executorProperty!.functionValue =
                (action.executorProperty!.functionValue * 10).round();
          }
        }
      }
      sceneBloc.add(CreateSceneWithTasksEvent(
        createSceneModel: createSceneModel,
        createAutomationModel: null,
        updateScene: updateScene,
        sceneId: sceneId,
      ));
    }
  }

  Widget getTheCorrectDialogBody(
      SceneStaticFunction taskItem, dynamic functionValue,
      {required bool isAutomation}) {
    if (taskItem.operationDialogType == OperationDialogType.temperature) {
      return AlertDialogTemperatureBody(
        taskItem: taskItem,
        functionValue: functionValue ?? taskItem.functionValue,
      );
    } else if ((taskItem.operationDialogType ==
            OperationDialogType.countdown) ||
        (taskItem.operationDialogType == OperationDialogType.delay)) {
      return AlertDialogCountdown(
        durationValue: taskItem.functionValue ?? 0,
        functionValue: functionValue ?? taskItem.functionValue,
        function: taskItem,
      );
    } else if (taskItem.operationDialogType ==
        OperationDialogType.integerSteps) {
      return AlertDialogSliderSteps(
        taskItem: taskItem,
        functionValue: functionValue ?? taskItem.functionValue,
        isAutomation: isAutomation,
      );
    } else if (taskItem.operationDialogType ==
        OperationDialogType.counterSteps) {
      return AlertDialogCounterSteps(
        taskItem: taskItem,
        functionValue: functionValue ?? taskItem.functionValue,
        isAutomation: isAutomation,
      );
    }

    return AlertDialogFunctionsOperationsBody(
      taskItem: taskItem,
      functionValue: functionValue ?? taskItem.functionValue,
      isAutomation: isAutomation,
    );
  }

  String getTaskDescription(SceneStaticFunction taskItem) {
    if (taskItem.code == CreateSceneEnum.smartSceneSelect.name) {
      if (taskItem.operationName == 'automation') {
        return 'Automation: ';
      } else {
        return 'Tab-To-Run: ';
      }
    } else {
      return "${taskItem.operationName}: ";
    }
  }
}
