import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:syncrow_web/common/edit_chip.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/assign_tag_models/views/assign_tag_models_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/helper/tag_helper.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/button_content_widget.dart';
import 'package:syncrow_web/pages/spaces_management/tag_model/views/add_device_type_model_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';

class TagChipDisplay extends StatelessWidget {
  const TagChipDisplay({
    required this.spaceModel,
    required this.products,
    required this.subspaces,
    required this.allTags,
    required this.spaceName,
    required this.projectTags,
    this.pageContext,
    this.otherSpaceModels,
    this.allSpaceModels,
    super.key,
  });

  final SpaceTemplateModel? spaceModel;
  final List<ProductModel>? products;
  final List<SubspaceTemplateModel>? subspaces;
  final List<String>? allTags;
  final String spaceName;
  final BuildContext? pageContext;
  final List<String>? otherSpaceModels;
  final List<SpaceTemplateModel>? allSpaceModels;
  final List<Tag> projectTags;

  Map<ProductModel, int> get _groupedTags {
    final spaceTags = spaceModel?.tags ?? <Tag>[];

    final subspaces = spaceModel?.subspaceModels ?? [];
    final subspaceTags = subspaces.expand((e) => e.tags ?? <Tag>[]).toList();

    return TagHelper.groupTags([...spaceTags, ...subspaceTags]);
  }

  @override
  Widget build(BuildContext context) {
    final hasTags = spaceModel?.tags?.isNotEmpty ?? false;
    final hasSubspaceTags =
        spaceModel?.subspaceModels?.any((e) => e.tags?.isNotEmpty ?? false) ?? false;

    if (hasTags || hasSubspaceTags) {
      return Container(
        width: context.screenWidth * 0.25,
        padding: const EdgeInsets.all(8),
        decoration: BoxDecoration(
          color: ColorsManager.textFieldGreyColor,
          borderRadius: BorderRadius.circular(15),
          border: Border.all(
            color: ColorsManager.textFieldGreyColor,
            width: 3,
          ),
        ),
        child: Wrap(
          spacing: 8,
          runSpacing: 8,
          children: [
            ..._groupedTags.entries.map((entry) => _buildChip(context, entry)),
            _buildEditChip(context),
          ],
        ),
      );
    }

    return _buildAddDevicesButton(context);
  }

  Widget _buildEditChip(BuildContext context) {
    return EditChip(
      onTap: () => showDialog<void>(
        context: context,
        builder: (context) => AssignTagModelsDialog(
          products: products,
          allSpaceModels: allSpaceModels,
          subspaces: subspaces,
          pageContext: pageContext,
          allTags: allTags,
          spaceModel: spaceModel,
          otherSpaceModels: otherSpaceModels,
          initialTags: TagHelper.generateInitialTags(
            subspaces: subspaces,
            spaceTagModels: spaceModel?.tags ?? [],
          ),
          title: 'Edit Device',
          addedProducts: TagHelper.createInitialSelectedProducts(
            spaceModel?.tags ?? [],
            subspaces,
          ),
          spaceName: spaceModel?.modelName ?? '',
          projectTags: projectTags,
        ),
      ),
    );
  }

  Widget _buildChip(
    BuildContext context,
    MapEntry<ProductModel, int> entry,
  ) {
    return Chip(
      backgroundColor: ColorsManager.whiteColors,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
        side: const BorderSide(
          color: ColorsManager.spaceColor,
        ),
      ),
      avatar: SvgPicture.asset(
        entry.key.icon ?? Assets.gateway,
        fit: BoxFit.contain,
        height: 24,
        width: 24,
      ),
      label: Text(
        '${entry.value}',
        style: context.textTheme.bodySmall!.copyWith(
          color: ColorsManager.spaceColor,
        ),
      ),
    );
  }

  Widget _buildAddDevicesButton(BuildContext context) {
    return TextButton(
      onPressed: () => showDialog<void>(
        context: context,
        builder: (context) => AddDeviceTypeModelWidget(
          products: products,
          subspaces: subspaces,
          allTags: allTags,
          spaceName: spaceName,
          pageContext: pageContext,
          isCreate: true,
          spaceModel: spaceModel,
          otherSpaceModels: otherSpaceModels,
          projectTags: projectTags,
        ),
      ),
      style: TextButton.styleFrom(
        padding: EdgeInsets.zero,
      ),
      child: const ButtonContentWidget(
        icon: Icons.add,
        label: 'Add Devices',
      ),
    );
  }
}
