import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/scene/bloc/create_scene/create_scene_bloc.dart';
import 'package:syncrow_app/features/scene/enum/create_scene_enum.dart';
import 'package:syncrow_app/features/scene/helper/scene_logic_helper.dart';
import 'package:syncrow_app/features/shared_widgets/default_button.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_large.dart';
import 'package:syncrow_app/navigation/navigate_to_route.dart';
import 'package:syncrow_app/navigation/routing_constants.dart';
import 'package:syncrow_app/utils/context_extension.dart';
import 'package:syncrow_app/utils/helpers/snack_bar.dart';
import 'package:syncrow_app/utils/resource_manager/color_manager.dart';

class CreateSceneSaveButton extends StatefulWidget {
  const CreateSceneSaveButton({
    super.key,
    required this.sceneName,
    required this.sceneId,
  });
  final String sceneName;
  final String sceneId;

  @override
  State<CreateSceneSaveButton> createState() => _CreateSceneSaveButtonState();
}

class _CreateSceneSaveButtonState extends State<CreateSceneSaveButton> with SceneLogicHelper {
  late TextEditingController sceneNameController;

  @override
  void initState() {
    sceneNameController =
        TextEditingController(text: widget.sceneName.isNotEmpty ? widget.sceneName : '');
    super.initState();
  }

  @override
  void dispose() {
    sceneNameController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<CreateSceneBloc, CreateSceneState>(
      listener: (context, state) {
        if (state is CreateSceneWithTasks) {
          if (state.success) {
            navigateToRoute(context, Routes.homeRoute);
            sceneNameController.text = '';
          }
        } else if (state is CreateSceneError) {
          CustomSnackBar.displaySnackBar(state.message);
        }
      },
      builder: (context, state) {
        return DefaultButton(
          onPressed: () {
            final sceneBloc = context.read<CreateSceneBloc>();
            if (sceneBloc.tasksList.isEmpty && sceneBloc.automationTasksList.isEmpty) {
              return;
            }
            final isAutomation = sceneBloc.sceneType == CreateSceneEnum.deviceStatusChanges;

            if (isAutomation && sceneBloc.automationTasksList.isEmpty) {
              CustomSnackBar.displaySnackBar(
                'Conditions Must not be empty!',
              );
              return;
            }

            if (isAutomation && sceneBloc.tasksList.isEmpty) {
              CustomSnackBar.displaySnackBar(
                'Actions Must not be empty!',
              );
              return;
            }

            if (widget.sceneName.isNotEmpty) {
              handleSaveButtonPress(
                context,
                sceneName: sceneNameController,
                actions: sceneBloc.tasksList,
                updateScene: true,
                sceneId: widget.sceneId,
                isAutomation: isAutomation,
                conditions: sceneBloc.automationTasksList,
              );
            } else {
              context.customAlertDialog(
                alertBody: Padding(
                  padding: const EdgeInsets.only(left: 8, right: 8, bottom: 8),
                  child: SizedBox(
                    height: 40,
                    child: SearchBar(
                      controller: sceneNameController,
                      elevation: WidgetStateProperty.all(0),
                      textStyle: WidgetStateProperty.all(context.bodyMedium),
                      hintStyle: WidgetStateProperty.all(
                        context.bodyMedium
                            .copyWith(fontSize: 14, color: ColorsManager.secondaryTextColor),
                      ),
                      hintText: 'Enter scene name',
                      backgroundColor: WidgetStateProperty.all(ColorsManager.backgroundColor),
                    ),
                  ),
                ),
                title: 'Scene Name',
                onConfirm: () {
                  Navigator.pop(context);
                  if (sceneNameController.text.isNotEmpty) {
                    handleSaveButtonPress(
                      context,
                      sceneName: sceneNameController,
                      actions: sceneBloc.tasksList,
                      updateScene: false,
                      sceneId: widget.sceneId,
                      isAutomation: isAutomation,
                      conditions: sceneBloc.automationTasksList,
                    );
                  }
                },
              );
            }
          },
          customButtonStyle: ButtonStyle(
            backgroundColor: WidgetStateProperty.all<Color>(
              ColorsManager.primaryColor,
            ),
          ),
          isLoading: state is CreateSceneLoading,
          child: BodyLarge(
            text: widget.sceneName.isNotEmpty ? 'Update' : 'Save',
            style: context.bodyLarge.copyWith(color: Colors.white),
          ),
        );
      },
    );
  }
}
