import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/pages/routines/bloc/routine_bloc/routine_bloc.dart';
import 'package:syncrow_web/pages/routines/helper/save_routine_helper.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/discard_dialog.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/setting_dialog.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
import 'package:syncrow_web/utils/style.dart';

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

  @override
  State<RoutineSearchAndButtons> createState() => _RoutineSearchAndButtonsState();
}

class _RoutineSearchAndButtonsState extends State<RoutineSearchAndButtons> {
  late TextEditingController _nameController;

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController();
  }

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

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<RoutineBloc, RoutineState>(
      builder: (context, state) {
        _nameController.text = state.routineName ?? '';
        return LayoutBuilder(
          builder: (BuildContext context, BoxConstraints constraints) {
            return Wrap(
              runSpacing: 16,
              children: [
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text(
                    state.errorMessage ?? '',
                    style: const TextStyle(color: Colors.red),
                  ),
                ),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Expanded(
                      child: Wrap(
                        spacing: 12,
                        runSpacing: 12,
                        crossAxisAlignment: WrapCrossAlignment.end,
                        children: [
                          ConstrainedBox(
                            constraints: BoxConstraints(
                                maxWidth:
                                    constraints.maxWidth > 700 ? 450 : constraints.maxWidth - 32),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  children: [
                                    Text('* ',
                                        style: context.textTheme.bodyMedium!
                                            .copyWith(color: ColorsManager.red, fontSize: 13)),
                                    Text(
                                      'Routine Name',
                                      style: context.textTheme.bodyMedium!.copyWith(
                                        fontSize: 13,
                                        fontWeight: FontWeight.w600,
                                        color: ColorsManager.blackColor,
                                      ),
                                    ),
                                  ],
                                ),
                                Container(
                                  width: 450,
                                  height: 40,
                                  decoration: containerWhiteDecoration,
                                  child: TextFormField(
                                    style: context.textTheme.bodyMedium!
                                        .copyWith(color: ColorsManager.blackColor),
                                    controller: _nameController,
                                    decoration: InputDecoration(
                                      hintText: 'Please enter the name',
                                      hintStyle: context.textTheme.bodyMedium!
                                          .copyWith(fontSize: 12, color: ColorsManager.grayColor),
                                      contentPadding:
                                          const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                                      border: InputBorder.none,
                                    ),
                                    onTapOutside: (_) {
                                      context
                                          .read<RoutineBloc>()
                                          .add(SetRoutineName(_nameController.text));
                                    },
                                    validator: (value) {
                                      if (value == null || value.isEmpty) {
                                        return 'This field is required';
                                      }
                                      return null;
                                    },
                                  ),
                                ),
                              ],
                            ),
                          ),
                          (constraints.maxWidth <= 1000)
                              ? const SizedBox()
                              : SizedBox(
                                  height: 40,
                                  width: 200,
                                  child: Center(
                                    child: DefaultButton(
                                      onPressed: state.isAutomation || state.isTabToRun
                                          ? () async {
                                              final result = await SettingHelper.showSettingDialog(
                                                context: context,
                                                iconId: state.selectedIcon ?? '',
                                              );
                                              if (result != null) {
                                                context
                                                    .read<RoutineBloc>()
                                                    .add(AddSelectedIcon(result));
                                              }
                                            }
                                          : null,
                                      borderRadius: 15,
                                      elevation: 0,
                                      borderColor: ColorsManager.greyColor,
                                      backgroundColor: ColorsManager.boxColor,
                                      child: const Text(
                                        'Settings',
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                          fontSize: 12,
                                          color: ColorsManager.primaryColor,
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                        ],
                      ),
                    ),
                    if (constraints.maxWidth > 1000)
                      Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          SizedBox(
                            height: 40,
                            width: 200,
                            child: Center(
                              child: DefaultButton(
                                onPressed: () {
                                  DiscardDialog.show(context);
                                },
                                borderRadius: 15,
                                elevation: 0,
                                borderColor: ColorsManager.greyColor,
                                backgroundColor: ColorsManager.boxColor,
                                child: const Text(
                                  'Cancel',
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                    fontSize: 12,
                                    color: ColorsManager.blackColor,
                                  ),
                                ),
                              ),
                            ),
                          ),
                          const SizedBox(width: 12),
                          SizedBox(
                            height: 40,
                            width: 200,
                            child: Center(
                              child: DefaultButton(
                                onPressed: () async {
                                  if (state.routineName == null || state.routineName!.isEmpty) {
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      SnackBar(
                                        content: const Text('Please enter the routine name'),
                                        duration: const Duration(seconds: 2),
                                        backgroundColor: ColorsManager.red,
                                        action: SnackBarAction(
                                          label: 'Dismiss',
                                          onPressed: () {
                                            // Optional action on Snackbar
                                          },
                                        ),
                                      ),
                                    );
                                    return;
                                  }

                                  if (state.ifItems.isEmpty || state.thenItems.isEmpty) {
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      SnackBar(
                                        content: const Text('Please add if and then condition'),
                                        duration: const Duration(seconds: 2),
                                        backgroundColor: ColorsManager.red,
                                        action: SnackBarAction(
                                          label: 'Dismiss',
                                          onPressed: () {
                                            // Optional action on Snackbar
                                          },
                                        ),
                                      ),
                                    );
                                    return;
                                  }
                                  // final result =
                                  // await
                                  BlocProvider.of<RoutineBloc>(context).add(ResetErrorMessage());
                                  SaveRoutineHelper.showSaveRoutineDialog(context);
                                  // if (result != null && result) {
                                  //   BlocProvider.of<RoutineBloc>(context).add(
                                  //     const CreateNewRoutineViewEvent(createRoutineView: false),
                                  //   );
                                  //   BlocProvider.of<RoutineBloc>(context).add(
                                  //     const TriggerSwitchTabsEvent(isRoutineTab: true),
                                  //   );
                                  // }
                                },
                                borderRadius: 15,
                                elevation: 0,
                                backgroundColor: ColorsManager.primaryColor,
                                child: const Text(
                                  'Save',
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                    fontSize: 12,
                                    color: ColorsManager.whiteColors,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                  ],
                ),
                if (constraints.maxWidth <= 1000)
                  Wrap(
                    runSpacing: 12,
                    children: [
                      SizedBox(
                        height: 40,
                        width: 200,
                        child: Center(
                          child: DefaultButton(
                            onPressed: state.isAutomation || state.isTabToRun
                                ? () async {
                                    final result = await SettingHelper.showSettingDialog(
                                        context: context, iconId: state.selectedIcon ?? '');
                                    if (result != null) {
                                      context.read<RoutineBloc>().add(AddSelectedIcon(result));
                                    }
                                  }
                                : null,
                            borderRadius: 15,
                            elevation: 0,
                            borderColor: ColorsManager.greyColor,
                            backgroundColor: ColorsManager.boxColor,
                            child: const Text(
                              'Settings',
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontSize: 12,
                                color: ColorsManager.primaryColor,
                              ),
                            ),
                          ),
                        ),
                      ),
                      const SizedBox(width: 12),
                      SizedBox(
                        height: 40,
                        width: 200,
                        child: Center(
                          child: DefaultButton(
                            onPressed: () {
                              DiscardDialog.show(context);
                            },
                            borderRadius: 15,
                            elevation: 0,
                            borderColor: ColorsManager.greyColor,
                            backgroundColor: ColorsManager.boxColor,
                            child: const Text(
                              'Cancel',
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontSize: 12,
                                color: ColorsManager.blackColor,
                              ),
                            ),
                          ),
                        ),
                      ),
                      const SizedBox(width: 12),
                      SizedBox(
                        height: 40,
                        width: 200,
                        child: Center(
                          child: DefaultButton(
                            onPressed: () async {
                              if (state.routineName == null || state.routineName!.isEmpty) {
                                ScaffoldMessenger.of(context).showSnackBar(
                                  SnackBar(
                                    content: const Text('Please enter the routine name'),
                                    duration: const Duration(seconds: 2),
                                    backgroundColor: ColorsManager.red,
                                    action: SnackBarAction(
                                      label: 'Dismiss',
                                      onPressed: () {
                                        // Optional action on Snackbar
                                      },
                                    ),
                                  ),
                                );
                                return;
                              }

                              if (state.ifItems.isEmpty || state.thenItems.isEmpty) {
                                ScaffoldMessenger.of(context).showSnackBar(
                                  SnackBar(
                                    content: const Text('Please add if and then condition'),
                                    duration: const Duration(seconds: 2),
                                    backgroundColor: ColorsManager.red,
                                    action: SnackBarAction(
                                      label: 'Dismiss',
                                      onPressed: () {
                                        // Optional action on Snackbar
                                      },
                                    ),
                                  ),
                                );
                                return;
                              }
                              // final result =
                              // await
                              BlocProvider.of<RoutineBloc>(context).add(ResetErrorMessage());
                              SaveRoutineHelper.showSaveRoutineDialog(context);
                              // if (result != null && result) {
                              //   BlocProvider.of<RoutineBloc>(context).add(
                              //     const CreateNewRoutineViewEvent(createRoutineView: false),
                              //   );
                              //   BlocProvider.of<RoutineBloc>(context).add(
                              //     const TriggerSwitchTabsEvent(isRoutineTab: true),
                              //   );
                              // }
                            },
                            borderRadius: 15,
                            elevation: 0,
                            backgroundColor: ColorsManager.primaryColor,
                            child: const Text(
                              'Save',
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontSize: 12,
                                color: ColorsManager.whiteColors,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
              ],
            );
          },
        );
      },
    );
  }
}
