import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/devices/bloc/device_manager_bloc/device_manager_bloc.dart';
import 'package:syncrow_app/features/devices/bloc/device_manager_bloc/device_manager_state.dart';
import 'package:syncrow_app/features/devices/model/subspace_model.dart';
import 'package:syncrow_app/features/scene/bloc/tab_change/tab_change_bloc.dart';
import 'package:syncrow_app/features/scene/bloc/tab_change/tab_change_state.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/widgets/scene_devices/scene_devices_body_tab_bar.dart';
import 'package:syncrow_app/features/scene/widgets/scene_devices/scene_devices_list.dart';
import 'package:syncrow_app/features/shared_widgets/app_loading_indicator.dart';

class SceneDevicesBody extends StatelessWidget {
  const SceneDevicesBody({
    required this.tabController,
    required this.rooms,
    super.key,
  });

  final TabController tabController;
  final List<SubSpaceModel> rooms;

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<TabBarBloc, TabBarState>(
      builder: (context, state) {
        return Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SceneDevicesBodyTabBar(
              tabController: tabController,
              rooms: rooms,
              selectedRoomId: state is TabBarTabSelectedState ? state.roomId : '-1',
            ),
            Expanded(
              child: TabBarView(
                physics: const NeverScrollableScrollPhysics(),
                controller: tabController,
                children: rooms
                    .map(
                      (room) => _buildRoomTab(
                        room,
                        _isAutomationDeviceStatus(context),
                      ),
                    )
                    .toList(),
              ),
            ),
          ],
        );
      },
    );
  }

  bool _isAutomationDeviceStatus(BuildContext context) {
    final routeArguments =
        ModalRoute.of(context)?.settings.arguments as SceneSettingsRouteArguments?;
    final deviceStatusChangesScene = CreateSceneEnum.deviceStatusChanges.name;
    final sceneType = routeArguments?.sceneType;

    return sceneType == deviceStatusChangesScene;
  }

  Widget _buildRoomTab(
    SubSpaceModel room,
    bool isAutomationDeviceStatus,
  ) {
    return BlocBuilder<DeviceManagerBloc, DeviceManagerState>(
      builder: (context, state) {
        final isLoading = state.loading && state.devices == null;
        final hasData =
            state.devices != null && (state.devices?.isNotEmpty ?? false);
        final hasError = state.error != null;

        final widgets = <bool, Widget>{
          isLoading: const AppLoadingIndicator(),
          hasError: Center(child: Text('${state.error}')),
          hasData: SceneDevicesList(
            devices: state.devices ?? [],
            isAutomationDeviceStatus: isAutomationDeviceStatus,
          ),
        };

        final invalidWidgetEntry = MapEntry(
          true,
          Center(child: Text('This subspace has no devices')),
        );

        final validWidgetEntry = widgets.entries.firstWhere(
          (entry) => entry.key == true,
          orElse: () => invalidWidgetEntry,
        );

        return validWidgetEntry.value;
      },
    );
  }
}
