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/view/space_tree_view.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/community_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/community_structure_widget.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/gradient_canvas_border_widget.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/sidebar_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/models/space_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/view/space_model_page.dart';
import 'package:syncrow_web/services/space_model_mang_api.dart';

class LoadedSpaceView extends StatefulWidget {
  final List<CommunityModel> communities;
  final CommunityModel? selectedCommunity;
  final SpaceModel? selectedSpace;
  final List<ProductModel>? products;
  final List<SpaceTemplateModel>? spaceModels;
  final bool shouldNavigateToSpaceModelPage;
  final List<Tag> projectTags;

  const LoadedSpaceView(
      {super.key,
      required this.communities,
      this.selectedCommunity,
      this.selectedSpace,
      this.products,
      this.spaceModels,
      required this.shouldNavigateToSpaceModelPage,
      required this.projectTags});

  @override
  _LoadedSpaceViewState createState() => _LoadedSpaceViewState();
}

class _LoadedSpaceViewState extends State<LoadedSpaceView> {
  late List<SpaceTemplateModel> _spaceModels;

  @override
  void initState() {
    super.initState();
    _spaceModels = List.from(widget.spaceModels ?? []);
  }

  @override
  @override
  void didUpdateWidget(covariant LoadedSpaceView oldWidget) {
    super.didUpdateWidget(oldWidget);

    if (widget.spaceModels != oldWidget.spaceModels) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) {
          setState(() {
            _spaceModels = List.from(widget.spaceModels ?? []);
          });
        }
      });
    }
  }

  void _onSpaceModelsUpdated(List<SpaceTemplateModel> updatedModels) {
    if (mounted && updatedModels != _spaceModels) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) {
          setState(() {
            _spaceModels = updatedModels;
          });
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      clipBehavior: Clip.none,
      children: [
        widget.shouldNavigateToSpaceModelPage
            ? Row(
                children: [
                  SizedBox(width: 300, child: SpaceTreeView(onSelect: () {})),
                  Expanded(
                    child: BlocProvider(
                      create: (context) => SpaceModelBloc(
                        BlocProvider.of<SpaceTreeBloc>(context),
                        api: SpaceModelManagementApi(),
                        initialSpaceModels: widget.spaceModels ?? [],
                      ),
                      child: SpaceModelPage(
                        products: widget.products,
                        onSpaceModelsUpdated: _onSpaceModelsUpdated,
                        projectTags: widget.projectTags,
                      ),
                    ),
                  ),
                ],
              )
            : Row(
                children: [
                  SidebarWidget(
                    communities: widget.communities,
                    selectedSpaceUuid:
                        widget.selectedSpace?.uuid ?? widget.selectedCommunity?.uuid ?? '',
                    onCreateCommunity: (name, description) {
                      context.read<SpaceManagementBloc>().add(
                            CreateCommunityEvent(name, description, context),
                          );
                    },
                  ),
                  CommunityStructureArea(
                    selectedCommunity: widget.selectedCommunity,
                    selectedSpace: widget.selectedSpace,
                    spaces: widget.selectedCommunity?.spaces ?? [],
                    products: widget.products,
                    communities: widget.communities,
                    spaceModels: _spaceModels,
                    projectTags: widget.projectTags,
                  ),
                ],
              ),
        const GradientCanvasBorderWidget(),
      ],
    );
  }
}
