import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:smooth_page_indicator/smooth_page_indicator.dart';
import 'package:syncrow_app/features/app_layout/bloc/home_cubit.dart';
import 'package:syncrow_app/features/devices/bloc/devices_cubit.dart';
import 'package:syncrow_app/features/devices/view/widgets/all_devices.dart';
import 'package:syncrow_app/features/devices/view/widgets/room_page.dart';
import 'package:syncrow_app/features/devices/view/widgets/rooms_slider.dart';
import 'package:syncrow_app/features/devices/view/widgets/wizard_page.dart';
import 'package:syncrow_app/features/scene/view/scene_view.dart';
import 'package:syncrow_app/features/shared_widgets/create_unit.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_large.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/title_medium.dart';
import 'package:syncrow_app/utils/context_extension.dart';
import 'package:syncrow_app/utils/resource_manager/strings_manager.dart';

class DevicesViewBody extends StatelessWidget {
  const DevicesViewBody({super.key});
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<HomeCubit, HomeState>(
      builder: (context, homeState) {
        final homeCubit = HomeCubit.getInstance();
        // Handle state priority: Errors first
        if (homeState is ActivationError) {
          return const CreateUnitWidget();
        }
        // Handle loading states
        if (homeState is GetSpacesLoading || homeState is HomeLoading) {
          return const Center(child: CircularProgressIndicator());
        }
        // Handle error states
        if (homeState is GetSpacesError) {
          return const CreateUnitWidget();
        }
        // Handle success states
        if (homeState is GetSpacesSuccess ||
            homeState is RoomUnSelected ||
            homeState is RoomSelected ||
            homeState is NavChangePage ||
            homeState is GetSpaceRoomsSuccess) {
          // Show empty state if no spaces
          if (homeCubit.spaces.isEmpty) {
            return const CreateUnitWidget();
          }
          return BlocBuilder<DevicesCubit, DevicesState>(
            builder: (context, devicesState) {
              // Devices loading states
              if (devicesState is DevicesLoading ||
                  devicesState is DevicesCategoriesLoading ||
                  devicesState is GetDevicesLoading) {
                return const Center(child: CircularProgressIndicator());
              }
              // Devices error state
              if (devicesState is GetDevicesError) {
                return Center(child: BodyLarge(text: devicesState.errorMsg));
              }
              // Main content for both GetSpacesSuccess and RoomUnSelected
              return _buildMainContent(context, homeCubit);
            },
          );
        }
        // Fallback for unknown states
        return const Center(child: BodyLarge(text: ''));
      },
    );
  }

  Widget _buildMainContent(BuildContext context, HomeCubit homeCubit) {
    final devicesCubit = context.read<DevicesCubit>();
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Row(
          children: [
            TitleMedium(
              text: StringsManager.devices,
              style: context.titleMedium.copyWith(fontSize: 25),
            ),
          ],
        ),
        const SceneView(pageType: true),
        const SizedBox(height: 20),
        const RoomsSlider(),
        const SizedBox(height: 10),
        Expanded(
          child: PageView(
            controller: homeCubit.devicesPageController,
            onPageChanged: (index) {
              homeCubit.devicesPageChanged(index);
              if (index == 0) {
                devicesCubit.fetchAllDevices(homeCubit.selectedSpace);
              }
            },
            children: [
              AllDevices(
                allDevices: devicesCubit.allDevices,
              ),
              WizardPage(
                groupsList: devicesCubit.allCategories ?? [],
              ),
              if (homeCubit.selectedSpace != null)
                ...homeCubit.selectedSpace!.subspaces.map(
                  (room) => RoomPage(room: room),
                ),
            ],
          ),
        ),
        _buildPageIndicator(homeCubit),
      ],
    );
  }

  Widget _buildPageIndicator(HomeCubit homeCubit) {
    return homeCubit.selectedSpace != null
        ? Padding(
            padding: const EdgeInsets.symmetric(vertical: 7),
            child: SmoothPageIndicator(
              controller: homeCubit.devicesPageController,
              count: homeCubit.selectedSpace!.subspaces.length + 2,
              effect: const WormEffect(
                paintStyle: PaintingStyle.stroke,
                dotHeight: 8,
                dotWidth: 8,
              ),
            ),
          )
        : const Center(
            child: BodyLarge(text: 'No Home Found'),
          );
  }
}
