import 'package:flutter/material.dart';
import 'package:flutter/widgets.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/enum/create_scene_enum.dart';
import 'package:syncrow_app/features/scene/model/scene_settings_route_arguments.dart';
import 'package:syncrow_app/features/scene/view/create_scene_view.dart';
import 'package:syncrow_app/features/scene/widgets/if_then_containers/then_added_tasks.dart';
import 'package:syncrow_app/features/scene/widgets/scene_list_tile.dart';
import 'package:syncrow_app/features/shared_widgets/default_container.dart';
import 'package:syncrow_app/features/shared_widgets/light_divider.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_large.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_medium.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_small.dart';
import 'package:syncrow_app/generated/assets.dart';
import 'package:syncrow_app/navigation/routing_constants.dart';
import 'package:syncrow_app/utils/context_extension.dart';
import 'package:syncrow_app/utils/helpers/custom_page_route.dart';
import 'package:syncrow_app/utils/resource_manager/color_manager.dart';
import 'package:syncrow_app/utils/resource_manager/strings_manager.dart';

class IFDefaultContainer extends StatelessWidget {
  const IFDefaultContainer({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<CreateSceneBloc, CreateSceneState>(
      builder: (context, state) {
        final sceneType = context.read<CreateSceneBloc>().sceneType;
        return DefaultContainer(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 2),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              SceneListTile(
                leadingWidget: InkWell(
                  onTap: () {
                    if (sceneType.name ==
                        CreateSceneEnum.deviceStatusChanges.name) {
                      context.customAlertDialog(
                        hideConfirmButton: true,
                        alertBody: Column(
                          children: [
                            ListTile(
                              title: const BodyMedium(
                                  text: "When all conditions are met"),
                              onTap: () {
                                context.read<CreateSceneBloc>().add(
                                    const SelectConditionEvent(
                                        "When all conditions are met"));
                                Navigator.pop(context);
                              },
                            ),
                            ListTile(
                              title: const BodyMedium(
                                  text: "When any condition is met"),
                              onTap: () {
                                context.read<CreateSceneBloc>().add(
                                    const SelectConditionEvent(
                                        "When any condition is met"));
                                Navigator.pop(context);
                              },
                            ),
                          ],
                        ),
                        title: 'Conditions Rule',
                        onConfirm: () {},
                      );
                    }
                  },
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      BodyLarge(
                        text: 'IF',
                        style: context.bodyLarge.copyWith(
                          fontWeight: FontWeight.bold,
                          color: ColorsManager.primaryTextColor,
                        ),
                      ),
                      Visibility(
                        visible: sceneType.name ==
                            CreateSceneEnum.deviceStatusChanges.name,
                        child: BlocBuilder<CreateSceneBloc, CreateSceneState>(
                          builder: (context, state) {
                            String conditionText = "When any condition is met";
                            if (state is AddSceneTask) {
                              if (state.condition == 'or') {
                                conditionText = "When any condition is met";
                              } else {
                                conditionText = "When all conditions are met";
                              }
                            }
                            return SizedBox(
                              width: context.width * 0.6,
                              child: Row(children: [
                                BodySmall(text: conditionText),
                                const Icon(Icons.keyboard_arrow_down)
                              ]),
                            );
                          },
                        ),
                      ),
                    ],
                  ),
                ),
                trailingWidget: BlocBuilder<CreateSceneBloc, CreateSceneState>(
                  builder: (context, state) {
                    bool isClickable = false;
                    if (state is AddSceneTask) {
                      isClickable =
                          state.automationTasksList?.isNotEmpty ?? false;
                    }
                    return GestureDetector(
                      onTap: isClickable
                          ? () => Navigator.pushNamed(
                                context,
                                Routes.sceneControlDevicesRoute,
                                arguments: SceneSettingsRouteArguments(
                                  sceneType:
                                      CreateSceneEnum.deviceStatusChanges.name,
                                  sceneId: '',
                                  sceneName: '',
                                ),
                              )
                          : null,
                      child: SvgPicture.asset(
                        Assets.addIcon,
                        colorFilter: ColorFilter.mode(
                          isClickable
                              ? ColorsManager.primaryColor
                              : ColorsManager.greyColor,
                          BlendMode.srcIn,
                        ),
                      ),
                    );
                  },
                ),
                padding: EdgeInsets.zero,
              ),
              const LightDivider(),
              BlocBuilder<CreateSceneBloc, CreateSceneState>(
                builder: (context, state) {
                  if (state is AddSceneTask) {
                    final automationTasksList = state.automationTasksList;
                    if (automationTasksList?.isNotEmpty == true) {
                      return ListView.builder(
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        itemCount: automationTasksList?.length,
                        reverse: true,
                        itemBuilder: (context, index) {
                          return ThenAddedTasksContainer(
                            taskItem: automationTasksList![index],
                            isAutomation: true,
                          );
                        },
                      );
                    }
                  }
                  final sceneType = context.read<CreateSceneBloc>().sceneType;
                  if (sceneType.name == CreateSceneEnum.tabToRun.name) {
                    return const SceneListTile(
                      padding: EdgeInsets.symmetric(horizontal: 2),
                      assetPath: Assets.handClickIcon,
                      titleString: StringsManager.tapToRun,
                      subtitleString: '',
                    );
                  }
                  return SceneListTile(
                      titleString: '+ Add Condition',
                      textAlign: TextAlign.center,
                      onPressed: () {
                        final sceneType =
                            context.read<CreateSceneBloc>().sceneType;
                        if (sceneType.name == CreateSceneEnum.none.name) {
                          Navigator.push(
                              context,
                              CustomPageRoute(
                                  builder: (context) =>
                                      const CreateSceneView()));
                        } else {
                          Navigator.pushNamed(
                            context,
                            Routes.sceneControlDevicesRoute,
                            arguments: SceneSettingsRouteArguments(
                              sceneType:
                                  CreateSceneEnum.deviceStatusChanges.name,
                              sceneId: '',
                              sceneName: '',
                            ),
                          );
                        }
                      });
                },
              )
            ],
          ),
        );
      },
    );
  }
}
