import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart';
import 'package:syncrow_app/features/app_layout/bloc/home_cubit.dart';
import 'package:syncrow_app/features/devices/bloc/6_scene_switch_bloc/6_scene_bloc.dart';
import 'package:syncrow_app/features/devices/bloc/6_scene_switch_bloc/6_scene_event.dart';
import 'package:syncrow_app/features/devices/bloc/6_scene_switch_bloc/6_scene_state.dart';
import 'package:syncrow_app/features/devices/view/widgets/restart_status_dialog.dart';
import 'package:syncrow_app/features/shared_widgets/default_container.dart';
import 'package:syncrow_app/features/shared_widgets/default_scaffold.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_medium.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_small.dart';
import 'package:syncrow_app/generated/assets.dart';
import 'package:syncrow_app/utils/resource_manager/color_manager.dart';

class SixSelectSceneFourPage extends StatelessWidget {
  final String? switchSelected;
  final String? deviceId;
  SixSelectSceneFourPage({super.key, this.switchSelected, this.deviceId});

  final TextEditingController _searchController = TextEditingController();
  final int? selectedSwitchIndex = 0;
  final spaces = HomeCubit.getInstance().spaces;

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => SixSceneBloc(sixSceneId: deviceId!)
        ..add(LoadScenes(
          unit: spaces!.first,
          unitId: spaces!.first.id,
          showInDevice: false,
        ))
        ..add(GetSceneBySwitchName(switchName: switchSelected)),
      child: BlocBuilder<SixSceneBloc, SixSceneState>(
        builder: (context, state) {
          final sensorBloc = BlocProvider.of<SixSceneBloc>(context);
          if (state is SaveSelectionSuccessState) {
            Future.delayed(const Duration(milliseconds: 250), () {
              Navigator.of(context).pop(true);
              Navigator.of(context).pop(true);
            });
          }
          return DefaultScaffold(
            title: 'Select Scene',
            actions: [_buildSaveButton(context, state, sensorBloc)],
            child: _buildSceneContent(context, sensorBloc, state),
          );
        },
      ),
    );
  }

  // Save button builder
  Widget _buildSaveButton(
      BuildContext context, SixSceneState state, SixSceneBloc sensorBloc) {
    final bool canSave = state is SceneSelectionUpdatedState;

    return GestureDetector(
      onTap: canSave
          ? () {
              context.read<SixSceneBloc>().add(AssignDeviceScene(
                  sceneUuid: sensorBloc.selectedSceneId,
                  switchName: switchSelected,
                  unit: spaces!.first));
            }
          : null,
      child: Padding(
        padding: const EdgeInsets.only(left: 10, right: 10),
        child: BodyMedium(
          text: 'Save',
          fontWeight: FontWeight.w700,
          fontSize: 16,
          fontColor: canSave
              ? ColorsManager.slidingBlueColor
              : ColorsManager.primaryTextColor,
        ),
      ),
    );
  }

  // Loading indicator
  Widget _buildLoadingIndicator() {
    return const Center(
      child: DefaultContainer(
        width: 50,
        height: 50,
        child: CircularProgressIndicator(),
      ),
    );
  }

  // Main scene content with search bar and grid
  Widget _buildSceneContent(
      BuildContext context, SixSceneBloc sensorBloc, SixSceneState state) {
    return Column(
      children: [
        _buildSearchBar(sensorBloc),
        const SizedBox(height: 20),
        Expanded(
          child: state is SixSceneLoadingState
              ? _buildLoadingIndicator()
              : sensorBloc.filteredScenes.isEmpty
                  ? const Center(
                      child: SizedBox(
                        child: BodySmall(text: 'No Scenes available'),
                      ),
                    )
                  : _buildSceneGrid(sensorBloc, state),
        ),
      ],
    );
  }

  // Search bar widget
  Widget _buildSearchBar(SixSceneBloc sensorBloc) {
    return TextFormField(
      controller: _searchController,
      onChanged: (value) {
        sensorBloc.add(SearchScenesEvent(query: value));
      },
      decoration: InputDecoration(
        hintText: 'Search',
        hintStyle: const TextStyle(
            color: ColorsManager.textGray,
            fontSize: 16,
            fontWeight: FontWeight.w400),
        suffixIcon: Container(
          padding: const EdgeInsets.all(5.0),
          margin: const EdgeInsets.all(10.0),
          child: SvgPicture.asset(
            Assets.searchIcon,
            fit: BoxFit.contain,
          ),
        ),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8.0),
        ),
      ),
    );
  }

  // Scene grid builder
  Widget _buildSceneGrid(SixSceneBloc sensorBloc, SixSceneState state) {
    final scenes = sensorBloc.filteredScenes;

    return GridView.builder(
      itemCount: scenes.length,
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        mainAxisSpacing: 16,
        crossAxisSpacing: 16,
        mainAxisExtent: 120,
      ),
      itemBuilder: (context, index) {
        final scene = scenes[index];
        bool isSelected = scene.id ==
            (state is SceneSelectionUpdatedState
                ? state.selectedSceneId
                : sensorBloc.selectedFormApiSceneId);
        return SceneItem(
          id: scene.id,
          value: isSelected,
          disablePlayButton: false,
          onChanged: (isSelected) {
            sensorBloc.add(SelectOptionEvent(selectedOption: scene.id));
            sensorBloc.add(SelectSceneEvent(
                selectedSceneId: scene.id, isSelected: isSelected));
          },
          icon: scene.iconInBytes,
          title: scene.name,
        );

        // if (index == scenes.length) {
        //   return InkWell(
        //     onTap: () => Navigator.pushNamed(
        //       NavigationService.navigatorKey.currentContext!,
        //       Routes.sceneTasksRoute,
        //       arguments: SceneSettingsRouteArguments(
        //         sceneType: '',
        //         sceneId: '',
        //         sceneName: '',
        //       ),
        //     ),
        //     child: CreateSceneItem(),
        //   );
        // } else {
        //   final scene = scenes[index];
        //   bool isSelected = scene.id ==
        //       (state is SceneSelectionUpdatedState
        //           ? state.selectedSceneId
        //           : sensorBloc.selectedFormApiSceneId);
        //   return SceneItem(
        //     id: scene.id,
        //     value: isSelected,
        //     disablePlayButton: false,
        //     onChanged: (isSelected) {
        //       sensorBloc.add(SelectOptionEvent(selectedOption: scene.id));

        //       sensorBloc.add(SelectSceneEvent(unitId: scene.id));
        //     },
        //     icon: scene.iconInBytes,
        //     title: scene.name,
        //   );
        // }
      },
    );
  }
}

class SceneItem extends StatelessWidget {
  final String id;
  final Uint8List icon;
  final String title;
  final bool disablePlayButton;
  final bool value;
  final Function(bool) onChanged;

  const SceneItem({
    required this.id,
    required this.icon,
    required this.title,
    this.disablePlayButton = false,
    required this.value,
    required this.onChanged,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        boxShadow: const [
          BoxShadow(
            color: Colors.black12,
            blurRadius: 2,
            spreadRadius: 1,
            offset: Offset(0, 3),
          ),
        ],
      ),
      padding: const EdgeInsets.all(16),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  if (!disablePlayButton)
                    Image.memory(
                      icon,
                      height: 32,
                      width: 32,
                      fit: BoxFit.fill,
                      errorBuilder: (context, error, stackTrace) => Image.asset(
                          Assets.assetsIconsLogo,
                          height: 32,
                          width: 32,
                          fit: BoxFit.fill),
                    ),
                ],
              ),
              CircularCheckbox(
                value: value,
                onChanged: (isSelected) => onChanged(isSelected!),
              ),
            ],
          ),
          BodyMedium(
            text: title,
            style: const TextStyle(
                fontSize: 17,
                fontWeight: FontWeight.w700,
                color: ColorsManager.secondaryTextColor),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }
}

// Widget for the static "Create Scene" button
class CreateSceneItem extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        boxShadow: const [
          BoxShadow(
            color: Colors.black12,
            blurRadius: 5,
            spreadRadius: 2,
            offset: Offset(0, 3),
          ),
        ],
      ),
      padding: const EdgeInsets.all(16),
      child: const Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(Icons.add_circle,
              color: ColorsManager.grayButtonColors, size: 36),
          BodyMedium(
            text: 'Create Scene',
            style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w400,
                color: ColorsManager.secondaryTextColor),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }
}
