import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/routines/bloc/routine_bloc/routine_bloc.dart';
import 'package:syncrow_web/pages/routines/widgets/dragable_card.dart';
import 'package:syncrow_web/utils/constants/assets.dart';

class ScenesAndAutomations extends StatefulWidget {
  const ScenesAndAutomations({
    super.key,
  });

  @override
  State<ScenesAndAutomations> createState() => _ScenesAndAutomationsState();
}

class _ScenesAndAutomationsState extends State<ScenesAndAutomations> {
  @override
  void initState() {
    super.initState();
    context.read<RoutineBloc>()
      ..add(const LoadScenes())
      ..add(const LoadAutomation());
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<RoutineBloc, RoutineState>(
      builder: (context, state) {
        if (!state.isLoading) {
          var scenes = [...state.scenes, ...state.automations];
          return Wrap(
            spacing: 10,
            runSpacing: 10,
            children: scenes.asMap().entries.map((entry) {
              final scene = entry.value;
              if (state.searchText != null && state.searchText!.isNotEmpty) {
                return scene.name.toLowerCase().contains(state.searchText!.toLowerCase())
                    ? DraggableCard(
                        imagePath: scene.icon ?? Assets.loginLogo,
                        title: scene.name,
                        deviceData: {
                          'deviceId': scene.id,
                          'name': scene.name,
                          'status': scene.status,
                          'type': scene.type,
                          'icon': scene.icon,
                        },
                      )
                    : Container();
              } else {
                return DraggableCard(
                  imagePath: scene.icon ?? Assets.loginLogo,
                  title: scene.name,
                  deviceData: {
                    'deviceId': scene.id,
                    'name': scene.name,
                    'status': scene.status,
                    'type': scene.type,
                    'icon': scene.icon,
                  },
                );
              }
            }).toList(),
          );
        }
        return const Center(child: CircularProgressIndicator());
      },
    );
  }
}
