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/app_layout/model/space_model.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/helper/scene_bloc_factory.dart';
import 'package:syncrow_app/features/scene/widgets/empty_routines_widget.dart';
import 'package:syncrow_app/features/scene/widgets/routines_expansion_tile.dart';
import 'package:syncrow_app/features/scene/widgets/scene_view_widget/scene_header.dart';
import 'package:syncrow_app/features/shared_widgets/app_loading_indicator.dart';
import 'package:syncrow_app/utils/context_extension.dart';

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

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => SceneBlocFactory.create(
        pageType: false,
        homeCubit: HomeCubit.getInstance(),
      ),
      child: BlocBuilder<CreateSceneBloc, CreateSceneState>(
        builder: (context, state) {
          final selectedSpace = HomeCubit.getInstance().selectedSpace;
          if (state is DeleteSceneSuccess) {
            if (state.success) _loadScenesAndAutomations(context, selectedSpace);
          }
          if (state is CreateSceneWithTasks) {
            if (state.success) {
              _loadScenesAndAutomations(context, selectedSpace);
              context.read<SmartSceneSelectBloc>().add(const SmartSceneClearEvent());
            }
          }
          return BlocListener<SceneBloc, SceneState>(
            listener: (context, state) {
              if (state is SceneTriggerSuccess) {
                context.showCustomSnackbar(
                  message: 'Scene ${state.sceneName} triggered successfully!',
                );
              }
            },
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                const SceneHeader(),
                const SizedBox(height: 8),
                Expanded(
                  child: BlocBuilder<SceneBloc, SceneState>(
                    builder: (context, state) {
                      if (state is SceneLoading) {
                        return const AppLoadingIndicator();
                      }
                      if (state is SceneError) {
                        return Center(
                          child: Text(state.message),
                        );
                      }
                      if (state is SceneLoaded) {
                        final scenes = state.scenes;
                        final automationList = state.automationList;
                        final routinesIsEmpty =
                            scenes.isEmpty && automationList.isEmpty;

                        if (routinesIsEmpty) return const EmptyRoutinesWidget();

                        return Theme(
                          data: Theme.of(context).copyWith(
                            dividerColor: Colors.transparent,
                          ),
                          child: Expanded(
                            child: ListView(
                              children: [
                                RoutinesExpansionTile(
                                  title: 'Tap to run routines',
                                  emptyRoutinesMessage:
                                      'No scenes have been added yet',
                                  routines: state.scenes,
                                  loadingStates: state.loadingStates,
                                  loadingSceneId: state.loadingSceneId,
                                  disablePlayButton: false,
                                ),
                                RoutinesExpansionTile(
                                  title: 'Automation',
                                  emptyRoutinesMessage:
                                      'No automations have been added yet',
                                  routines: state.automationList,
                                  loadingStates: state.loadingStates,
                                  loadingSceneId: state.loadingSceneId,
                                  disablePlayButton: true,
                                ),
                                const SizedBox(height: 15),
                              ],
                            ),
                          ),
                        );
                      }
                      return const SizedBox.shrink();
                    },
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  void _loadScenesAndAutomations(BuildContext context, SpaceModel? selectedSpace) {
    context.read<SceneBloc>()
      ..add(LoadScenes(selectedSpace!.id, selectedSpace, showInDevice: false))
      ..add(LoadAutomation(selectedSpace.id, selectedSpace.community.uuid));
  }
}
