import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/routines/bloc/automation_scene_trigger_bloc/automation_status_update.dart';
import 'package:syncrow_web/pages/routines/bloc/routine_bloc/routine_bloc.dart';
import 'package:syncrow_web/pages/routines/widgets/main_routine_view/routine_view_card.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart';

class FetchRoutineScenesAutomation extends StatelessWidget
    with HelperResponsiveLayout {
  const FetchRoutineScenesAutomation({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<RoutineBloc, RoutineState>(
      builder: (context, state) {
        if (state.isLoading)
          return const Center(child: CircularProgressIndicator());

        return SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.symmetric(vertical: 16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                _buildListTitle(context, "Scenes (Tap to Run)"),
                const SizedBox(height: 10),
                Visibility(
                  visible: state.scenes.isNotEmpty,
                  replacement: _buildEmptyState(context, "No scenes found"),
                  child: SizedBox(
                    height: 200,
                    child: _buildScenes(state),
                  ),
                ),
                const SizedBox(height: 10),
                _buildListTitle(context, "Automations"),
                const SizedBox(height: 3),
                Visibility(
                  visible: state.automations.isNotEmpty,
                  replacement:
                      _buildEmptyState(context, "No automations found"),
                  child: SizedBox(
                    height: 200,
                    child: _buildAutomations(state),
                  ),
                )
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildAutomations(RoutineState state) {
    return ListView.builder(
      scrollDirection: Axis.horizontal,
      itemCount: state.automations.length,
      itemBuilder: (context, index) {
        final isLoading =
            state.automations.contains(state.automations[index].id);

        return Column(
          children: [
            Padding(
              padding: EdgeInsets.only(
                right: isSmallScreenSize(context) ? 4.0 : 8.0,
              ),
              child: RoutineViewCard(
                isLoading: isLoading,
                onChanged: (v) {
                  context.read<RoutineBloc>().add(
                        UpdateAutomationStatus(
                          automationId: state.automations[index].id,
                          automationStatusUpdate: AutomationStatusUpdate(
                            spaceUuid: state.automations[index].spaceId,
                            isEnable: v,
                          ),
                          communityId: state.automations[index].communityId,
                        ),
                      );
                },
                status: state.automations[index].status,
                communityId: '',
                spaceId: state.automations[index].spaceId,
                sceneId: '',
                automationId: state.automations[index].id,
                cardType: 'automations',
                spaceName: state.automations[index].spaceName,
                onTap: () {
                  BlocProvider.of<RoutineBloc>(context).add(
                    const CreateNewRoutineViewEvent(
                      createRoutineView: true,
                    ),
                  );
                  context.read<RoutineBloc>().add(
                        GetAutomationDetails(
                          automationId: state.automations[index].id,
                          isAutomation: true,
                          isUpdate: true,
                        ),
                      );
                },
                textString: state.automations[index].name,
                icon: state.automations[index].icon ?? Assets.automation,
              ),
            ),
          ],
        );
      },
    );
  }

  Widget _buildScenes(RoutineState state) {
    return ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: state.scenes.length,
        itemBuilder: (context, index) {
          final scene = state.scenes[index];
          final isLoading = state.loadingSceneId == scene.id;

          return Padding(
            padding: EdgeInsets.only(
              right: isSmallScreenSize(context) ? 4.0 : 8.0,
            ),
            child: Column(
              children: [
                RoutineViewCard(
                  isLoading: isLoading,
                  sceneOnTap: () {
                    context.read<RoutineBloc>().add(
                          SceneTrigger(
                            sceneId: scene.id,
                            name: scene.name,
                          ),
                        );
                  },
                  status: state.scenes[index].status,
                  communityId: state.scenes[index].communityId,
                  spaceId: state.scenes[index].spaceId,
                  sceneId: state.scenes[index].sceneTuyaId!,
                  automationId: state.scenes[index].id,
                  cardType: 'scenes',
                  spaceName: state.scenes[index].spaceName,
                  onTap: () {
                    BlocProvider.of<RoutineBloc>(context).add(
                      const CreateNewRoutineViewEvent(
                        createRoutineView: true,
                      ),
                    );
                    context.read<RoutineBloc>().add(
                          GetSceneDetails(
                            sceneId: state.scenes[index].id,
                            isTabToRun: true,
                            isUpdate: true,
                          ),
                        );
                  },
                  textString: state.scenes[index].name,
                  icon: state.scenes[index].icon ?? Assets.logoHorizontal,
                  isFromScenes: true,
                  iconInBytes: state.scenes[index].iconInBytes,
                ),
              ],
            ),
          );
        });
  }

  Widget _buildListTitle(BuildContext context, String title) {
    return Text(
      title,
      style: Theme.of(context).textTheme.titleLarge?.copyWith(
            color: ColorsManager.grayColor,
            fontWeight: FontWeight.bold,
          ),
    );
  }

  Widget _buildEmptyState(BuildContext context, String title) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 100),
      child: Text(
        title,
        style: context.textTheme.bodyMedium?.copyWith(
          color: ColorsManager.grayColor,
        ),
      ),
    );
  }
}
