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/devices/bloc/devices_cubit.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_event.dart';
import 'package:syncrow_app/features/scene/widgets/scene_devices/scene_devices_body.dart';
import 'package:syncrow_app/features/shared_widgets/default_scaffold.dart';
import 'package:syncrow_app/navigation/navigate_to_route.dart';
import 'package:syncrow_app/navigation/routing_constants.dart';
import 'package:syncrow_app/utils/resource_manager/strings_manager.dart';

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

  @override
  State<SceneRoomsTabBarDevicesView> createState() =>
      _SceneRoomsTabBarDevicesViewState();
}

class _SceneRoomsTabBarDevicesViewState extends State<SceneRoomsTabBarDevicesView>
    with SingleTickerProviderStateMixin {
  late final TabController _tabController;
  late final SpaceModel selectedSpace;
  var rooms = <SubSpaceModel>[];

  @override
  void initState() {
    super.initState();

    selectedSpace = HomeCubit.getInstance().selectedSpace!;

    rooms = List.from(selectedSpace.subspaces);
    final defaultSubSpaceModel = SubSpaceModel(
      name: 'All Devices',
      devices: context.read<DevicesCubit>().allDevices,
      id: '-1',
    );

    if (rooms.isNotEmpty) {
      final isFirstRoomIdValid = rooms[0].id != '-1';
      if (isFirstRoomIdValid) {
        rooms.insert(0, defaultSubSpaceModel);
      }
    } else {
      rooms = [defaultSubSpaceModel];
    }

    _tabController = TabController(length: rooms.length, vsync: this);
    _tabController.addListener(_handleTabSwitched);
  }

  @override
  void dispose() {
    super.dispose();
    _tabController.removeListener(() {});
    _tabController.dispose();
  }

  void _handleTabSwitched() {
    if (_tabController.indexIsChanging) {
      final index = _tabController.index;

      context.read<TabBarBloc>().add(
            TabBarTabChangedEvent(
              selectedIndex: index,
              roomId: rooms[index].id ?? '',
              unit: selectedSpace,
            ),
          );
      return;
    }
  }

  @override
  Widget build(BuildContext context) {
    return DefaultScaffold(
      padding: EdgeInsetsDirectional.zero,
      leading: IconButton(
        onPressed: () => navigateToRoute(context, Routes.sceneTasksRoute),
        icon: const Icon(Icons.arrow_back_ios),
      ),
      title: StringsManager.createScene,
      child: SceneDevicesBody(tabController: _tabController, rooms: rooms),
    );
  }
}
