import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/common/buttons/cancel_button.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_event.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/bloc/create_space_model_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/bloc/create_space_model_event.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/bloc/create_space_model_state.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/bloc/space_model_state.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/tag_chips_display_widget.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/bloc/space_model_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/bloc/space_model_event.dart';

import 'package:syncrow_web/pages/spaces_management/space_model/widgets/subspace_model_create_widget.dart';
import 'package:syncrow_web/services/space_model_mang_api.dart';
import 'package:syncrow_web/utils/color_manager.dart';

class CreateSpaceModelDialog extends StatelessWidget {
  final List<ProductModel>? products;
  final List<String>? allTags;
  final SpaceTemplateModel? spaceModel;
  final BuildContext? pageContext;
  final List<String>? otherSpaceModels;
  final List<SpaceTemplateModel>? allSpaceModels;
  final List<Tag> projectTags;

  const CreateSpaceModelDialog(
      {Key? key,
      this.products,
      this.allTags,
      this.spaceModel,
      this.pageContext,
      this.otherSpaceModels,
      this.allSpaceModels,
      required this.projectTags})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    final SpaceModelManagementApi _spaceModelApi = SpaceModelManagementApi();

    final screenWidth = MediaQuery.of(context).size.width;
    final TextEditingController spaceNameController = TextEditingController(
      text: spaceModel?.modelName ?? '',
    );

    return AlertDialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
      backgroundColor: ColorsManager.whiteColors,
      content: SizedBox(
        width: screenWidth * 0.3,
        child: BlocProvider(
          create: (_) {
            final bloc = CreateSpaceModelBloc(
              _spaceModelApi,
            );
            if (spaceModel != null) {
              bloc.add(UpdateSpaceTemplate(spaceModel!, otherSpaceModels));
            } else {
              bloc.add(UpdateSpaceTemplate(
                  SpaceTemplateModel(
                    modelName: '',
                    subspaceModels: const [],
                  ),
                  otherSpaceModels));
            }

            spaceNameController.addListener(() {
              bloc.add(UpdateSpaceTemplateName(
                  name: spaceNameController.text, allModels: otherSpaceModels ?? []));
            });

            return bloc;
          },
          child: BlocBuilder<CreateSpaceModelBloc, CreateSpaceModelState>(
            builder: (context, state) {
              if (state is CreateSpaceModelLoading) {
                return const Center(child: CircularProgressIndicator());
              } else if (state is CreateSpaceModelLoaded) {
                final updatedSpaceModel = state.space;
                final subspaces = updatedSpaceModel.subspaceModels ?? [];
                final isNameValid = spaceNameController.text.trim().isNotEmpty;

                return Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      spaceModel?.uuid == null ? 'Create New Space Model' : 'Edit Space Model',
                      style: Theme.of(context)
                          .textTheme
                          .headlineLarge
                          ?.copyWith(color: ColorsManager.blackColor),
                    ),
                    const SizedBox(height: 16),
                    SizedBox(
                      width: screenWidth * 0.25,
                      child: TextField(
                        controller: spaceNameController,
                        onChanged: (value) {
                          context.read<CreateSpaceModelBloc>().add(UpdateSpaceTemplateName(
                              name: value, allModels: otherSpaceModels ?? []));
                        },
                        style: Theme.of(context)
                            .textTheme
                            .bodySmall!
                            .copyWith(color: ColorsManager.blackColor),
                        decoration: InputDecoration(
                          filled: true,
                          fillColor: ColorsManager.textFieldGreyColor,
                          hintText: 'Please enter the name',
                          errorText: state.errorMessage,
                          hintStyle: Theme.of(context)
                              .textTheme
                              .bodySmall!
                              .copyWith(color: ColorsManager.lightGrayColor),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide.none,
                          ),
                          contentPadding: const EdgeInsets.symmetric(
                            vertical: 12.0,
                            horizontal: 16.0,
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(height: 16),
                    SubspaceModelCreate(
                      subspaces: state.space.subspaceModels ?? [],
                      tags: state.space.tags ?? [],
                      onSpaceModelUpdate: (updatedSubspaces, updatedTags) {
                        context
                            .read<CreateSpaceModelBloc>()
                            .add(AddSubspacesToSpaceTemplate(updatedSubspaces));
                        if (updatedTags != null) {
                          context
                              .read<CreateSpaceModelBloc>()
                              .add(AddTagsToSpaceTemplate(updatedTags));
                        }
                      },
                    ),
                    const SizedBox(height: 10),
                    TagChipDisplay(
                      spaceModel: updatedSpaceModel,
                      products: products,
                      subspaces: subspaces,
                      allTags: allTags,
                      spaceName: spaceNameController.text,
                      pageContext: pageContext,
                      otherSpaceModels: otherSpaceModels,
                      allSpaceModels: allSpaceModels,
                      projectTags: projectTags,
                    ),
                    const SizedBox(height: 20),
                    SizedBox(
                      width: screenWidth * 0.25,
                      child: Row(
                        children: [
                          Expanded(
                            child: CancelButton(
                              label: 'Cancel',
                              onPressed: () {
                                Navigator.of(context).pop();
                              },
                            ),
                          ),
                          const SizedBox(width: 10),
                          Expanded(
                            child: DefaultButton(
                              onPressed: ((state.errorMessage != null &&
                                          state.errorMessage != '') ||
                                      !isNameValid)
                                  ? null
                                  : () {
                                      final updatedSpaceTemplate = updatedSpaceModel.copyWith(
                                        modelName: spaceNameController.text.trim(),
                                      );
                                      if (updatedSpaceModel.uuid == null) {
                                        context.read<CreateSpaceModelBloc>().add(
                                              CreateSpaceTemplate(
                                                spaceTemplate: updatedSpaceTemplate,
                                                onCreate: (newModel) {
                                                  if (pageContext != null) {
                                                    pageContext!.read<SpaceModelBloc>().add(
                                                        CreateSpaceModel(newSpaceModel: newModel));
                                                    pageContext!
                                                        .read<SpaceManagementBloc>()
                                                        .add(UpdateSpaceModelCache(newModel));
                                                  }
                                                  Navigator.of(context).pop(); // Close the dialog
                                                },
                                              ),
                                            );
                                      } else {
                                        if (pageContext != null) {
                                          final currentState =
                                              pageContext!.read<SpaceModelBloc>().state;
                                          if (currentState is SpaceModelLoaded) {
                                            final spaceModels = List<SpaceTemplateModel>.from(
                                                currentState.spaceModels);

                                            final SpaceTemplateModel? currentSpaceModel =
                                                spaceModels.cast<SpaceTemplateModel?>().firstWhere(
                                                      (sm) => sm?.uuid == updatedSpaceModel.uuid,
                                                      orElse: () => null,
                                                    );
                                            if (currentSpaceModel != null) {
                                              context
                                                  .read<CreateSpaceModelBloc>()
                                                  .add(ModifySpaceTemplate(
                                                      spaceTemplate: currentSpaceModel,
                                                      updatedSpaceTemplate: updatedSpaceTemplate,
                                                      onUpdate: (newModel) {
                                                        if (pageContext != null) {
                                                          pageContext!.read<SpaceModelBloc>().add(
                                                              UpdateSpaceModel(
                                                                  spaceModelUuid:
                                                                      newModel.uuid ?? ''));
                                                          pageContext!
                                                              .read<SpaceManagementBloc>()
                                                              .add(UpdateSpaceModelCache(newModel));
                                                        }
                                                        Navigator.of(context).pop();
                                                      }));
                                            }
                                          }
                                        }
                                      }
                                    },
                              backgroundColor: ColorsManager.secondaryColor,
                              borderRadius: 10,
                              foregroundColor:
                                  ((state.errorMessage != null && state.errorMessage != '') ||
                                          !isNameValid)
                                      ? ColorsManager.whiteColorsWithOpacity
                                      : ColorsManager.whiteColors,
                              child: const Text('OK'),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                );
              } else if (state is CreateSpaceModelError) {
                return Text(
                  'Error: ${state.message}',
                  style: Theme.of(context)
                      .textTheme
                      .bodyMedium!
                      .copyWith(color: ColorsManager.warningRed),
                );
              }

              return const Center(child: Text('Initializing...'));
            },
          ),
        ),
      ),
    );
  }
}
