import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.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/bloc/scene_bloc/scene_bloc.dart';
import 'package:syncrow_app/features/scene/bloc/scene_bloc/scene_event.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/model/scenes_model.dart';
import 'package:syncrow_app/features/scene/model/scene_settings_route_arguments.dart';
import 'package:syncrow_app/features/scene/model/update_automation.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/navigation/routing_constants.dart';
import 'package:syncrow_app/utils/resource_manager/color_manager.dart';

class SceneItem extends StatelessWidget {
  final ScenesModel scene;
  final bool isLoading;
  final bool isSwitchLoading;
  final bool disablePlayButton;

  const SceneItem({
    required this.scene,
    required this.isLoading,
    super.key,
    required this.disablePlayButton,
    required this.isSwitchLoading,
  });

  @override
  Widget build(BuildContext context) {
    return DefaultContainer(
      onTap: () {
        if (HomeCubit.manageScene) {
          context
              .read<SmartSceneSelectBloc>()
              .add(const SmartSceneClearEvent());
          if (disablePlayButton == false) {
            BlocProvider.of<CreateSceneBloc>(context).add(
                FetchSceneTasksEvent(sceneId: scene.id, isAutomation: false));

            /// the state to set the scene type must be after the fetch
            BlocProvider.of<CreateSceneBloc>(context)
                .add(const SceneTypeEvent(CreateSceneEnum.tabToRun));
          } else {
            BlocProvider.of<CreateSceneBloc>(context).add(
                FetchSceneTasksEvent(sceneId: scene.id, isAutomation: true));

            /// the state to set the scene type must be after the fetch
            BlocProvider.of<CreateSceneBloc>(context)
                .add(const SceneTypeEvent(CreateSceneEnum.deviceStatusChanges));
          }

          Navigator.pushNamed(
            context,
            Routes.sceneTasksRoute,
            arguments: SceneSettingsRouteArguments(
              sceneType: disablePlayButton == false
                  ? CreateSceneEnum.tabToRun.name
                  : CreateSceneEnum.deviceStatusChanges.name,
              sceneId: scene.id,
              sceneName: scene.name,
            ),
          );
        }
      },
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              if (!disablePlayButton && scene.iconInBytes.isNotEmpty)
                Image.memory(
                  scene.iconInBytes,
                  height: 32,
                  width: 32,
                  fit: BoxFit.fill,
                  errorBuilder: (context, error, stackTrace) => Image.asset(
                      Assets.assetsIconsLogo,
                      height: 32,
                      width: 32,
                      fit: BoxFit.fill),
                ),
              if (disablePlayButton || scene.iconInBytes.isEmpty)
                SvgPicture.asset(
                  Assets.automationIcon,
                  height: 32,
                  width: 32,
                  fit: BoxFit.fill,
                ),
              disablePlayButton == false
                  ? IconButton(
                      padding: EdgeInsets.zero,
                      onPressed: () {
                        context
                            .read<SceneBloc>()
                            .add(SceneTrigger(scene.id, scene.name));
                      },
                      icon: isLoading
                          ? const Center(
                              child: CircularProgressIndicator(),
                            )
                          : const Icon(
                              Icons.play_circle,
                              size: 40,
                              color: ColorsManager.greyColor,
                            ),
                    )
                  : isSwitchLoading
                      ? Center(
                          child: CircularProgressIndicator(
                            color: ColorsManager.primaryColorWithOpacity,
                          ),
                        )
                      : CupertinoSwitch(
                          activeColor: ColorsManager.primaryColor,
                          value: scene.status == 'enable' ? true : false,
                          onChanged: (value) {
                            context.read<SceneBloc>().add(
                                UpdateAutomationStatus(
                                    automationStatusUpdate:
                                        AutomationStatusUpdate(
                                            isEnable: value,
                                            spaceUuid: HomeCubit.getInstance()
                                                .selectedSpace!
                                                .id),
                                    communityId: HomeCubit.getInstance()
                                        .selectedSpace!
                                        .community
                                        .uuid,
                                    automationId: scene.id));
                          },
                        ),
            ],
          ),
          const SizedBox(height: 10),
          FittedBox(
            child: BodyMedium(
              text: scene.name,
              maxLines: 1,
              overflow: TextOverflow.fade,
              fontWeight: FontWeight.bold,
              fontSize: 16,
            ),
          ),
        ],
      ),
    );
  }
}
