import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart';
import 'package:syncrow_web/pages/spaces_management/link_space_model/bloc/link_space_to_model_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/link_space_model/bloc/link_space_to_model_event.dart';
import 'package:syncrow_web/pages/spaces_management/link_space_model/bloc/link_space_to_model_state.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/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/models/space_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dialog/custom_loading_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dialog/link_space_model_spaces_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dialog/linking_successful.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dialog/overwrite_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dialog/delete_space_model_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dynamic_product_widget.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dynamic_room_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart';
import 'package:syncrow_web/utils/string_utils.dart';

class SpaceModelCardWidget extends StatelessWidget with HelperResponsiveLayout {
  final SpaceTemplateModel model;
  final BuildContext? pageContext;
  final bool topActionsDisabled;

  const SpaceModelCardWidget({
    Key? key,
    required this.model,
    this.pageContext,
    this.topActionsDisabled = true,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final Map<String, int> productTagCount = {};

    if (model.tags != null) {
      for (var tag in model.tags!) {
        final prodIcon = tag.product?.icon ?? 'Unknown';
        productTagCount[prodIcon] = (productTagCount[prodIcon] ?? 0) + 1;
      }
    }

    if (model.subspaceModels != null) {
      for (var subspace in model.subspaceModels!) {
        if (subspace.tags != null) {
          for (var tag in subspace.tags!) {
            final prodIcon = tag.product?.icon ?? 'Unknown';
            productTagCount[prodIcon] = (productTagCount[prodIcon] ?? 0) + 1;
          }
        }
      }
    }

    return LayoutBuilder(
      builder: (context, constraints) {
        bool showOnlyName = constraints.maxWidth < 250;
        return Container(
          padding: const EdgeInsets.all(16.0),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(10),
            boxShadow: [
              BoxShadow(
                color: Colors.grey.withOpacity(0.5),
                spreadRadius: 2,
                blurRadius: 5,
                offset: const Offset(0, 3),
              ),
            ],
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Text(
                      StringUtils.capitalizeFirstLetter(model.modelName),
                      style: Theme.of(context).textTheme.headlineMedium?.copyWith(
                            color: ColorsManager.blackColor,
                            fontWeight: FontWeight.bold,
                            fontSize: isSmallScreenSize(context) ? 13 : 20,
                          ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  if (!topActionsDisabled)
                    Row(
                      children: [
                        InkWell(
                          onTap: () {
                            showDialog(
                              context: context,
                              builder: (BuildContext dialogContext) {
                                return BlocProvider<LinkSpaceToModelBloc>(
                                  create: (_) => LinkSpaceToModelBloc(),
                                  child: BlocListener<LinkSpaceToModelBloc, LinkSpaceToModelState>(
                                    listenWhen: (previous, current) {
                                      return previous != current;
                                    },
                                    listener: (context, state) {
                                      final _bloc = BlocProvider.of<LinkSpaceToModelBloc>(context);
                                      if (state is SpaceModelLoading) {
                                        showDialog(
                                          context: context,
                                          barrierDismissible: false,
                                          builder: (BuildContext context) {
                                            return Dialog(
                                              shape: RoundedRectangleBorder(
                                                  borderRadius: BorderRadius.circular(20)),
                                              elevation: 10,
                                              backgroundColor: Colors.white,
                                              child: Padding(
                                                padding: const EdgeInsets.symmetric(
                                                    vertical: 30, horizontal: 50),
                                                child: Column(
                                                  mainAxisSize: MainAxisSize.min,
                                                  children: [
                                                    CustomLoadingIndicator(),
                                                  ],
                                                ),
                                              ),
                                            );
                                          },
                                        );
                                      } else if (state is AlreadyHaveLinkedState) {
                                        Navigator.of(dialogContext).pop();
                                        showOverwriteDialog(context, _bloc, model);
                                      } else if (state is SpaceValidationSuccess) {
                                        _bloc.add(LinkSpaceModelEvent(
                                            isOverWrite: false, selectedSpaceMode: model.uuid));

                                        Future.delayed(const Duration(seconds: 1), () {
                                          Navigator.of(dialogContext).pop();
                                          Navigator.of(dialogContext).pop();
                                          Navigator.of(dialogContext).pop();
                                        });

                                        showDialog(
                                          context: context,
                                          builder: (BuildContext dialogContext) {
                                            return const LinkingSuccessful();
                                          },
                                        ).then((v) {
                                          Future.delayed(const Duration(seconds: 2), () {
                                            Navigator.of(dialogContext).pop();
                                          });
                                        });
                                      } else if (state is SpaceModelLinkSuccess) {
                                        Navigator.of(dialogContext).pop();
                                        Navigator.of(dialogContext).pop();
                                        showDialog(
                                          context: context,
                                          barrierDismissible: false,
                                          builder: (BuildContext successDialogContext) {
                                            Future.delayed(const Duration(seconds: 2), () {
                                              Navigator.of(successDialogContext).pop();
                                            });

                                            return const LinkingSuccessful();
                                          },
                                        );
                                      }
                                    },
                                    child: LinkSpaceModelSpacesDialog(
                                      spaceModel: model,
                                    ),
                                  ),
                                );
                              },
                            );
                          },
                          child: SvgPicture.asset(
                            Assets.spaceLinkIcon,
                            fit: BoxFit.contain,
                          ),
                        ),
                        InkWell(
                          onTap: () {
                            _showDeleteDialog(context);
                          },
                          child: SvgPicture.asset(
                            Assets.deleteSpaceLinkIcon,
                            fit: BoxFit.contain,
                          ),
                        ),
                      ],
                    ),
                ],
              ),
              if (!showOnlyName) ...[
                const SizedBox(height: 10),
                Expanded(
                  child: Row(
                    children: [
                      // Left Container
                      Expanded(
                        flex: 1, // Distribute space proportionally
                        child: Container(
                          padding: const EdgeInsets.all(8.0),
                          child: LayoutBuilder(
                            builder: (context, constraints) {
                              return Align(
                                alignment: Alignment.topLeft,
                                child: DynamicRoomWidget(
                                  subspaceModels: model.subspaceModels,
                                  maxWidth: constraints.maxWidth,
                                  maxHeight: constraints.maxHeight,
                                ),
                              );
                            },
                          ),
                        ),
                      ),
                      if (productTagCount.isNotEmpty && model.subspaceModels != null)
                        Container(
                          width: 1.0,
                          color: ColorsManager.softGray,
                          margin: const EdgeInsets.symmetric(vertical: 6.0),
                        ),
                      Expanded(
                        flex: 1, // Distribute space proportionally
                        child: Container(
                          padding: const EdgeInsets.all(8.0),
                          child: LayoutBuilder(
                            builder: (context, constraints) {
                              return Align(
                                  alignment: Alignment.topLeft,
                                  child: DynamicProductWidget(
                                      productTagCount: productTagCount,
                                      maxWidth: constraints.maxWidth,
                                      maxHeight: constraints.maxHeight));
                            },
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ]
            ],
          ),
        );
      },
    );
  }

  void _showDeleteDialog(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext dialogContext) {
        return DeleteSpaceModelDialog(
          onConfirmDelete: () {
            if (pageContext != null) {
              pageContext!.read<SpaceModelBloc>().add(
                    DeleteSpaceModel(spaceModelUuid: model.uuid ?? ''),
                  );

              pageContext!.read<SpaceManagementBloc>().add(
                    DeleteSpaceModelFromCache(model.uuid ?? ''),
                  );
            }
          },
        );
      },
    );
  }
}
