// ignore_for_file: must_be_immutable

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_app/features/scene/bloc/create_scene/create_scene_bloc.dart';
import 'package:syncrow_app/features/scene/bloc/smart_scene/smart_scene_select_dart_bloc.dart';
import 'package:syncrow_app/features/scene/enum/create_scene_enum.dart';
import 'package:syncrow_app/features/scene/helper/scene_logic_helper.dart';
import 'package:syncrow_app/features/scene/helper/scene_operations_data_helper.dart';
import 'package:syncrow_app/features/scene/model/scene_static_function.dart';

import 'package:syncrow_app/features/scene/widgets/scene_list_tile.dart';
import 'package:syncrow_app/features/scene/widgets/select_smart_scene/smart_automation_list.dart';
import 'package:syncrow_app/features/shared_widgets/default_container.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_medium.dart';
import 'package:syncrow_app/generated/assets.dart';
import 'package:syncrow_app/utils/context_extension.dart';
import 'package:syncrow_app/utils/helpers/snack_bar.dart';
import 'package:syncrow_app/utils/resource_manager/color_manager.dart';

import '../../../../navigation/navigation_service.dart';

class ThenAddedTasksContainer extends StatelessWidget
    with SceneOperationsDataHelper, SceneLogicHelper {
  ThenAddedTasksContainer({
    super.key,
    required this.taskItem,
    this.sceneId,
    this.index,
    this.isAutomation,
  });

  final SceneStaticFunction taskItem;
  String? sceneId;
  int? index;
  bool? isAutomation;

  @override
  Widget build(BuildContext context) {
    final createSceneBloc = context.read<CreateSceneBloc>();
    String operationValue = '';
    if ((taskItem.code.contains('countdown') && isAutomation != true) ||
        taskItem.deviceId.contains('delay')) {
      final functionValue =
          taskItem.functionValue ?? taskItem.operationalValues.first.value;
      final duration =
          Duration(seconds: int.tryParse(functionValue.toString()) ?? 0);
      operationValue =
          "${duration.inHours}h ${duration.inMinutes.remainder(60)}m ";
    } else if (taskItem.code.contains('temp_set') ||
        taskItem.code.contains('temp_current')) {
      if ((taskItem.functionValue != null || taskItem.functionValue != 0)) {
        operationValue =
            '${((taskItem.functionValue / 10) as double).toStringAsFixed(1)}°C';
      } else {
        operationValue = '0°C';
      }
    } else {
      var functionValue =
          taskItem.functionValue ?? taskItem.operationalValues.first.value;

      if (functionValue is double) {
        functionValue = double.parse(functionValue.toStringAsFixed(1));
      }

      operationValue = functionValue.toString();
    }
    return DefaultContainer(
      onTap: taskItem.operationName == 'tap_to_run' ||
              taskItem.operationName == 'scene'
          ? null
          : () {
              List<SceneStaticFunction> functionOperation = [];

              /// get the task functions
              functionOperation = List.from(getOperationsForOneFunction(
                  taskItem: taskItem,
                  deviceId: taskItem.deviceId,
                  isAutomation: isAutomation ?? false));

              if (taskItem.code == CreateSceneEnum.smartSceneSelect.name) {
                context.customAlertDialog(
                  alertBody: EnableDisableAutomationDialog(
                    automationId: taskItem.deviceId,
                    descriptionSelected: taskItem.functionValue == 'rule_enable'
                        ? 'Enable'
                        : "Disable",
                    sceneORAutomationName: taskItem.deviceName,
                    type: taskItem.operationName,
                  ),
                  title: taskItem.deviceName,
                  onConfirm: () {
                    context
                        .read<SmartSceneSelectBloc>()
                        .add(const SmartSceneConfirmSelectionEvent());
                    Navigator.pop(context);
                  },
                  onDismiss: () {
                    context
                        .read<SmartSceneSelectBloc>()
                        .add(const SmartSceneClearEvent());
                    Navigator.pop(context);
                  },
                );
              } else {
                /// show alert dialog based on type
                context.customAlertDialog(
                  alertBody: getTheCorrectDialogBody(
                      functionOperation.first, null,
                      isAutomation: isAutomation ?? false),
                  title: functionOperation.first.operationName,
                  onConfirm: () {
                    final savedCode =
                        functionOperation.first.deviceId.contains('delay')
                            ? 'delay'
                            : functionOperation.first.code;
                    if (isAutomation == true) {
                      final automationSelectedValue =
                          createSceneBloc.automationSelectedValues[savedCode];

                      try {
                        createSceneBloc.add(
                          UpdateTaskEvent(
                            newValue: automationSelectedValue,
                            taskId: taskItem.uniqueCustomId!,
                            isAutomation: true,
                          ),
                        );
                      } catch (e) {
                        debugPrint('Error adding UpdateTaskEvent: $e');
                      }
                    } else {
                      final selectedValue =
                          createSceneBloc.selectedValues[savedCode];

                      try {
                        createSceneBloc.add(
                          UpdateTaskEvent(
                            newValue: selectedValue,
                            taskId: taskItem.uniqueCustomId!,
                          ),
                        );
                      } catch (e) {
                        debugPrint('Error adding UpdateTaskEvent: $e');
                      }
                    }

                    WidgetsBinding.instance.addPostFrameCallback((_) {
                      Navigator.pop(
                          NavigationService.navigatorKey.currentContext!);
                    });
                  },
                );
              }
            },
      padding: EdgeInsets.zero,
      child: Dismissible(
        key: Key(taskItem.uniqueCustomId.toString()),
        background: Container(
          padding: const EdgeInsets.only(right: 10),
          alignment: AlignmentDirectional.centerEnd,
          decoration: const ShapeDecoration(
            color: Color(0xFFFF0000),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20),
                bottomRight: Radius.circular(20),
              ),
            ),
          ),
          child: SvgPicture.asset(
            Assets.assetsDeleteIcon,
            width: 20,
            height: 22,
          ),
        ),
        direction: DismissDirection.endToStart,
        onDismissed: (direction) {
          String removeFunctionById = taskItem.uniqueCustomId!;

          if (isAutomation == true) {
            context.read<CreateSceneBloc>().add(RemoveTaskByIdEvent(
                  taskId: removeFunctionById,
                  isAutomation: true,
                ));
          } else {
            context.read<CreateSceneBloc>().add(RemoveTaskByIdEvent(
                  taskId: removeFunctionById,
                ));
          }
          context
              .read<SmartSceneSelectBloc>()
              .add(const SmartSceneClearEvent());

          String removeFunction =
              "${taskItem.operationName} with value ${taskItem.operationalValues.first.value}";

          CustomSnackBar.displaySnackBar('$removeFunction removed');
        },
        child: SceneListTile(
          padding: EdgeInsets.zero,
          leadingWidget: SvgPicture.asset(
            taskItem.deviceIcon ?? taskItem.icon,
            fit: BoxFit.fill,
          ),
          minLeadingWidth: 32,
          titleWidget: BodyMedium(
            text: taskItem.deviceName,
            style: context.bodyMedium.copyWith(
              fontWeight: FontWeight.bold,
            ),
          ),
          subtitleWidget: Row(
            children: [
              BodyMedium(
                text: getTaskDescription(taskItem),
                fontColor: ColorsManager.secondaryTextColor,
                fontWeight: FontWeight.normal,
              ),
              BodyMedium(
                text: taskItem.code == CreateSceneEnum.smartSceneSelect.name
                    ? taskItem.functionValue == 'rule_enable'
                        ? 'Enable'
                        : "Disable"
                    : operationValue,
                fontColor: ColorsManager.secondaryTextColor,
                fontWeight: FontWeight.normal,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
