import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_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/space_model_bloc.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/add_space_model_widget.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dialog/create_space_model_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/space_model_card_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart';

class SpaceModelPage extends StatelessWidget {
  final List<ProductModel>? products;
  final Function(List<SpaceTemplateModel>)? onSpaceModelsUpdated;
  final List<Tag> projectTags;

  const SpaceModelPage(
      {Key? key, this.products, this.onSpaceModelsUpdated, required this.projectTags})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<SpaceModelBloc, SpaceModelState>(
      builder: (context, state) {
        if (state is SpaceModelLoading) {
          return const Center(child: CircularProgressIndicator());
        } else if (state is SpaceModelLoaded) {
          final spaceModels = state.spaceModels;
          context.read<SpaceTreeBloc>().add(ClearCachedData());

          final allTagValues = _getAllTagValues(spaceModels);
          final allSpaceModelNames = _getAllSpaceModelName(spaceModels);

          if (onSpaceModelsUpdated != null) {
            onSpaceModelsUpdated!(spaceModels);
          }

          return Scaffold(
            backgroundColor: ColorsManager.whiteColors,
            body: Padding(
              padding: const EdgeInsets.fromLTRB(20.0, 16.0, 16.0, 16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Expanded(
                    child: GridView.builder(
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 3,
                        crossAxisSpacing: 10.0,
                        mainAxisSpacing: 10.0,
                        childAspectRatio: _calculateChildAspectRatio(context),
                      ),
                      itemCount: spaceModels.length + 1,
                      itemBuilder: (context, index) {
                        if (index == spaceModels.length) {
                          // Add Button
                          return GestureDetector(
                            onTap: () {
                              showDialog(
                                context: context,
                                builder: (BuildContext dialogContext) {
                                  return CreateSpaceModelDialog(
                                    products: products,
                                    allTags: allTagValues,
                                    pageContext: context,
                                    otherSpaceModels: allSpaceModelNames,
                                    projectTags: projectTags,
                                  );
                                },
                              );
                            },
                            child: const AddSpaceModelWidget(),
                          );
                        }
                        // Render existing space model
                        final model = spaceModels[index];
                        final otherModel = List<String>.from(allSpaceModelNames);
                        otherModel.remove(model.modelName);
                        return GestureDetector(
                            onTap: () {
                              showDialog(
                                context: context,
                                builder: (BuildContext dialogContext) {
                                  return CreateSpaceModelDialog(
                                    products: products,
                                    allTags: allTagValues,
                                    spaceModel: model,
                                    otherSpaceModels: otherModel,
                                    pageContext: context,
                                    allSpaceModels: spaceModels,
                                    projectTags: projectTags,
                                  );
                                },
                              );
                            },
                            child: Container(
                              margin: const EdgeInsets.all(8.0),
                              child: SpaceModelCardWidget(
                                model: model,
                                pageContext: context,
                                topActionsDisabled: false,
                              ),
                            ));
                      },
                    ),
                  ),
                ],
              ),
            ),
          );
        } else if (state is SpaceModelError) {
          return Center(
            child: Text(
              'Error: ${state.message}',
              style:
                  Theme.of(context).textTheme.bodySmall?.copyWith(color: ColorsManager.warningRed),
            ),
          );
        }
        return const Center(child: Text('Initializing...'));
      },
    );
  }

  double _calculateChildAspectRatio(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;
    if (screenWidth > 1600) {
      return 1.5; // Decrease to make cards taller
    }
    if (screenWidth > 1200) {
      return 2.0;
    } else if (screenWidth > 800) {
      return 2.5;
    } else {
      return 3.0;
    }
  }

  List<String> _getAllTagValues(List<SpaceTemplateModel> spaceModels) {
    final List<String> allTags = [];
    for (final spaceModel in spaceModels) {
      if (spaceModel.tags != null) {
        allTags.addAll(spaceModel.listAllTagValues());
      }
    }
    return allTags;
  }

  List<String> _getAllSpaceModelName(List<SpaceTemplateModel> spaceModels) {
    final List<String> names = [];
    for (final spaceModel in spaceModels) {
      names.add(spaceModel.modelName);
    }
    return names;
  }
}
