import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_web/common/edit_chip.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/add_device_type/views/add_device_type_widget.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_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/subspace_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/dialogs/icon_selection_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/assign_tag/views/assign_tag_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace/views/create_subspace_model_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/helper/space_helper.dart';
import 'package:syncrow_web/pages/spaces_management/helper/tag_helper.dart';
import 'package:syncrow_web/pages/spaces_management/link_space_model/view/link_space_model_dialog.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/button_content_widget.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/subspace_name_label_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/constants/space_icon_const.dart';

class CreateSpaceDialog extends StatefulWidget {
  final Function(
      String,
      String,
      List<SelectedProduct> selectedProducts,
      SpaceTemplateModel? spaceModel,
      List<SubspaceModel>? subspaces,
      List<Tag>? tags) onCreateSpace;
  final List<ProductModel>? products;
  final String? name;
  final String? icon;
  final bool isEdit;
  final List<SelectedProduct> selectedProducts;
  final SpaceModel? parentSpace;
  final SpaceModel? editSpace;
  final List<SpaceTemplateModel>? spaceModels;
  final List<SubspaceModel>? subspaces;
  final List<Tag>? tags;
  final List<String>? allTags;
  final SpaceTemplateModel? currentSpaceModel;
  final List<Tag> projectTags;

  const CreateSpaceDialog(
      {super.key,
      this.parentSpace,
      required this.onCreateSpace,
      this.products,
      this.name,
      this.icon,
      this.isEdit = false,
      this.editSpace,
      this.allTags,
      this.selectedProducts = const [],
      this.spaceModels,
      this.subspaces,
      this.tags,
      this.currentSpaceModel,
      required this.projectTags});

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

class CreateSpaceDialogState extends State<CreateSpaceDialog> {
  String selectedIcon = Assets.location;
  SpaceTemplateModel? selectedSpaceModel;
  String enteredName = '';
  List<SelectedProduct> selectedProducts = [];
  late TextEditingController nameController;
  bool isOkButtonEnabled = false;
  bool isNameFieldInvalid = false;
  bool isNameFieldExist = false;
  List<SubspaceModel>? subspaces;
  List<Tag>? tags;

  @override
  void initState() {
    super.initState();
    selectedIcon = widget.icon ?? Assets.location;
    nameController = TextEditingController(text: widget.name ?? '');
    selectedProducts = widget.selectedProducts.isNotEmpty ? widget.selectedProducts : [];
    isOkButtonEnabled = enteredName.isNotEmpty || nameController.text.isNotEmpty;
    if (widget.currentSpaceModel != null) {
      subspaces = [];
      tags = [];
    } else {
      tags = widget.tags ?? [];
      subspaces = widget.subspaces ?? [];
    }
    selectedSpaceModel = widget.currentSpaceModel;
  }

  @override
  Widget build(BuildContext context) {
    bool isSpaceModelDisabled =
        (tags != null && tags!.isNotEmpty || subspaces != null && subspaces!.isNotEmpty);
    bool isTagsAndSubspaceModelDisabled = (selectedSpaceModel != null);

    final screenWidth = MediaQuery.of(context).size.width;
    return AlertDialog(
      title: widget.isEdit ? const Text('Edit Space') : const Text('Create New Space'),
      backgroundColor: ColorsManager.whiteColors,
      content: SizedBox(
        width: screenWidth * 0.5,
        child: SingleChildScrollView(
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                flex: 1,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  //  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    const SizedBox(height: 50),
                    Stack(
                      alignment: Alignment.center,
                      children: [
                        Container(
                          width: screenWidth * 0.1,
                          height: screenWidth * 0.1,
                          decoration: const BoxDecoration(
                            color: ColorsManager.boxColor,
                            shape: BoxShape.circle,
                          ),
                        ),
                        SvgPicture.asset(
                          selectedIcon,
                          width: screenWidth * 0.04,
                          height: screenWidth * 0.04,
                        ),
                        Positioned(
                          top: 20,
                          right: 20,
                          child: InkWell(
                            onTap: _showIconSelectionDialog,
                            child: Container(
                              width: 24,
                              height: 24,
                              decoration: const BoxDecoration(
                                color: Colors.white,
                                shape: BoxShape.circle,
                              ),
                              child: SvgPicture.asset(
                                Assets.iconEdit,
                                width: 16,
                                height: 16,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 20),
              Expanded(
                flex: 2,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(
                      width: screenWidth * 0.25,
                      child: TextField(
                        controller: nameController,
                        onChanged: (value) {
                          enteredName = value.trim();
                          setState(() {
                            isNameFieldExist = false;
                            isOkButtonEnabled = false;
                            isNameFieldInvalid = value.isEmpty;

                            if (!isNameFieldInvalid) {
                              if (SpaceHelper.isNameConflict(
                                  value, widget.parentSpace, widget.editSpace)) {
                                isNameFieldExist = true;
                                isOkButtonEnabled = false;
                              } else {
                                isNameFieldExist = false;
                                isOkButtonEnabled = true;
                              }
                            }
                          });
                        },
                        style: Theme.of(context).textTheme.bodyMedium,
                        decoration: InputDecoration(
                          hintText: 'Please enter the name',
                          hintStyle: Theme.of(context)
                              .textTheme
                              .bodyMedium!
                              .copyWith(color: ColorsManager.lightGrayColor),
                          filled: true,
                          fillColor: ColorsManager.boxColor,
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide(
                              color: isNameFieldInvalid || isNameFieldExist
                                  ? ColorsManager.red
                                  : ColorsManager.boxColor,
                              width: 1.5,
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: const BorderSide(
                              color: ColorsManager.boxColor,
                              width: 1.5,
                            ),
                          ),
                        ),
                      ),
                    ),
                    if (isNameFieldInvalid)
                      Padding(
                        padding: const EdgeInsets.only(top: 8.0),
                        child: Text(
                          '*Space name should not be empty.',
                          style: Theme.of(context)
                              .textTheme
                              .bodySmall
                              ?.copyWith(color: ColorsManager.red),
                        ),
                      ),
                    if (isNameFieldExist)
                      Padding(
                        padding: const EdgeInsets.only(top: 8.0),
                        child: Text(
                          '*Name already exist',
                          style: Theme.of(context)
                              .textTheme
                              .bodySmall
                              ?.copyWith(color: ColorsManager.red),
                        ),
                      ),
                    const SizedBox(height: 10),
                    selectedSpaceModel == null
                        ? TextButton(
                            style: TextButton.styleFrom(
                              padding: EdgeInsets.zero,
                            ),
                            onPressed: () {
                              isSpaceModelDisabled ? null : _showLinkSpaceModelDialog(context);
                            },
                            child: ButtonContentWidget(
                              svgAssets: Assets.link,
                              label: 'Link a space model',
                              disabled: isSpaceModelDisabled,
                            ),
                          )
                        : Container(
                            width: screenWidth * 0.25,
                            padding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 16.0),
                            decoration: BoxDecoration(
                              color: ColorsManager.boxColor,
                              borderRadius: BorderRadius.circular(10),
                            ),
                            child: Wrap(
                              spacing: 8.0,
                              runSpacing: 8.0,
                              children: [
                                Chip(
                                    label: Text(
                                      selectedSpaceModel?.modelName ?? '',
                                      style: Theme.of(context)
                                          .textTheme
                                          .bodyMedium!
                                          .copyWith(color: ColorsManager.spaceColor),
                                    ),
                                    backgroundColor: ColorsManager.whiteColors,
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(8),
                                      side: const BorderSide(
                                        color: ColorsManager.transparentColor,
                                        width: 0,
                                      ),
                                    ),
                                    deleteIcon: Container(
                                      width: 24,
                                      height: 24,
                                      decoration: BoxDecoration(
                                        shape: BoxShape.circle,
                                        border: Border.all(
                                          color: ColorsManager.lightGrayColor,
                                          width: 1.5,
                                        ),
                                      ),
                                      child: const Icon(
                                        Icons.close,
                                        size: 16,
                                        color: ColorsManager.lightGrayColor,
                                      ),
                                    ),
                                    onDeleted: () => setState(() {
                                          this.selectedSpaceModel = null;
                                          subspaces = widget.subspaces ?? [];
                                          tags = widget.tags ?? [];
                                        })),
                              ],
                            ),
                          ),
                    const SizedBox(height: 25),
                    Row(
                      children: [
                        const Expanded(
                          child: Divider(
                            color: ColorsManager.neutralGray,
                            thickness: 1.0,
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 6.0),
                          child: Text(
                            'OR',
                            style: Theme.of(context)
                                .textTheme
                                .bodyMedium
                                ?.copyWith(fontWeight: FontWeight.bold),
                          ),
                        ),
                        const Expanded(
                          child: Divider(
                            color: ColorsManager.neutralGray,
                            thickness: 1.0,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 25),
                    subspaces == null || subspaces!.isEmpty
                        ? TextButton(
                            style: TextButton.styleFrom(
                              padding: EdgeInsets.zero,
                              overlayColor: ColorsManager.transparentColor,
                            ),
                            onPressed: () async {
                              isTagsAndSubspaceModelDisabled
                                  ? null
                                  : _showSubSpaceDialog(
                                      context, enteredName, [], false, widget.products, subspaces);
                            },
                            child: ButtonContentWidget(
                              icon: Icons.add,
                              label: 'Create Sub Space',
                              disabled: isTagsAndSubspaceModelDisabled,
                            ),
                          )
                        : SizedBox(
                            width: screenWidth * 0.25,
                            child: Container(
                              padding: const EdgeInsets.all(8.0),
                              decoration: BoxDecoration(
                                color: ColorsManager.textFieldGreyColor,
                                borderRadius: BorderRadius.circular(15),
                                border: Border.all(
                                  color: ColorsManager.textFieldGreyColor,
                                  width: 3.0, // Border width
                                ),
                              ),
                              child: Wrap(
                                spacing: 8.0,
                                runSpacing: 8.0,
                                children: [
                                  if (subspaces != null)
                                    ...subspaces!.map((subspace) {
                                      return Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          SubspaceNameDisplayWidget(
                                            text: subspace.subspaceName,
                                            validateName: (updatedName) {
                                              bool nameExists = subspaces!.any((s) {
                                                bool isSameId = s.internalId == subspace.internalId;
                                                bool isSameName =
                                                    s.subspaceName.trim().toLowerCase() ==
                                                        updatedName.trim().toLowerCase();

                                                return !isSameId && isSameName;
                                              });

                                              return !nameExists;
                                            },
                                            onNameChanged: (updatedName) {
                                              setState(() {
                                                subspace.subspaceName = updatedName;
                                              });
                                            },
                                          ),
                                        ],
                                      );
                                    }),
                                  EditChip(
                                    onTap: () async {
                                      _showSubSpaceDialog(context, enteredName, [], true,
                                          widget.products, subspaces);
                                    },
                                  )
                                ],
                              ),
                            ),
                          ),
                    const SizedBox(height: 10),
                    (tags?.isNotEmpty == true ||
                            subspaces?.any((subspace) => subspace.tags?.isNotEmpty == true) == true)
                        ? SizedBox(
                            width: screenWidth * 0.25,
                            child: Container(
                              padding: const EdgeInsets.all(8.0),
                              decoration: BoxDecoration(
                                color: ColorsManager.textFieldGreyColor,
                                borderRadius: BorderRadius.circular(15),
                                border: Border.all(
                                  color: ColorsManager.textFieldGreyColor,
                                  width: 3.0, // Border width
                                ),
                              ),
                              child: Wrap(
                                spacing: 8.0,
                                runSpacing: 8.0,
                                children: [
                                  // Combine tags from spaceModel and subspaces
                                  ...TagHelper.groupTags([
                                    ...?tags,
                                    ...?subspaces?.expand((subspace) => subspace.tags ?? [])
                                  ]).entries.map(
                                        (entry) => Chip(
                                          avatar: SizedBox(
                                            width: 24,
                                            height: 24,
                                            child: SvgPicture.asset(
                                              entry.key.icon ?? 'assets/icons/gateway.svg',
                                              fit: BoxFit.contain,
                                            ),
                                          ),
                                          label: Text(
                                            'x${entry.value}', // Show count
                                            style: Theme.of(context)
                                                .textTheme
                                                .bodySmall
                                                ?.copyWith(color: ColorsManager.spaceColor),
                                          ),
                                          backgroundColor: ColorsManager.whiteColors,
                                          shape: RoundedRectangleBorder(
                                            borderRadius: BorderRadius.circular(16),
                                            side: const BorderSide(
                                              color: ColorsManager.spaceColor,
                                            ),
                                          ),
                                        ),
                                      ),

                                  EditChip(onTap: () async {
                                    await showDialog(
                                      context: context,
                                      builder: (context) => AssignTagDialog(
                                        products: widget.products,
                                        subspaces: subspaces,
                                        allTags: widget.allTags,
                                        addedProducts:
                                            TagHelper.createInitialSelectedProductsForTags(
                                                tags ?? [], subspaces),
                                        title: 'Edit Device',
                                        initialTags: TagHelper.generateInitialForTags(
                                            spaceTags: tags, subspaces: subspaces),
                                        spaceName: widget.name ?? '',
                                        projectTags: widget.projectTags,
                                        onSave: (updatedTags, updatedSubspaces) {
                                          setState(() {
                                            tags = updatedTags;
                                            subspaces = updatedSubspaces;
                                          });
                                        },
                                      ),
                                    );
                                  })
                                ],
                              ),
                            ),
                          )
                        : TextButton(
                            onPressed: () {
                              isTagsAndSubspaceModelDisabled
                                  ? null
                                  : _showTagCreateDialog(
                                      context,
                                      enteredName,
                                      widget.isEdit,
                                      widget.products,
                                    );
                            },
                            style: TextButton.styleFrom(
                              padding: EdgeInsets.zero,
                            ),
                            child: ButtonContentWidget(
                              icon: Icons.add,
                              label: 'Add Devices',
                              disabled: isTagsAndSubspaceModelDisabled,
                            ))
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
      actions: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              child: CancelButton(
                label: 'Cancel',
                onPressed: () => Navigator.of(context).pop(),
              ),
            ),
            const SizedBox(width: 10),
            Expanded(
              child: DefaultButton(
                onPressed: () {
                  if (nameController.text.isEmpty) {
                    setState(() {
                      isNameFieldInvalid = true;
                    });
                    return;
                  } else if (isNameFieldExist) {
                    return;
                  } else {
                    String newName = enteredName.isNotEmpty ? enteredName : (widget.name ?? '');
                    if (newName.isNotEmpty) {
                      widget.onCreateSpace(newName, selectedIcon, selectedProducts,
                          selectedSpaceModel, subspaces, tags);
                      Navigator.of(context).pop();
                    }
                  }
                },
                borderRadius: 10,
                backgroundColor:
                    isOkButtonEnabled ? ColorsManager.secondaryColor : ColorsManager.grayColor,
                foregroundColor: ColorsManager.whiteColors,
                child: const Text('OK'),
              ),
            ),
          ],
        ),
      ],
    );
  }

  void _showIconSelectionDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return IconSelectionDialog(
          spaceIconList: spaceIconList,
          onIconSelected: (String selectedIcon) {
            setState(() {
              this.selectedIcon = selectedIcon;
            });
          },
        );
      },
    );
  }

  void _showLinkSpaceModelDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return LinkSpaceModelDialog(
          spaceModels: widget.spaceModels ?? [],
          onSave: (selectedModel) {
            if (selectedModel != null) {
              setState(() {
                selectedSpaceModel = selectedModel;
                subspaces = null;
                tags = null;
              });
            }
          },
        );
      },
    );
  }

  void _showSubSpaceDialog(BuildContext context, String name, final List<Tag>? spaceTags,
      bool isEdit, List<ProductModel>? products, final List<SubspaceModel>? existingSubSpaces) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return CreateSubSpaceDialog(
            spaceName: name,
            dialogTitle: isEdit ? 'Edit Sub-space' : 'Create Sub-space',
            products: products,
            existingSubSpaces: existingSubSpaces,
            onSave: (slectedSubspaces) {
              final List<Tag> tagsToAppendToSpace = [];

              if (slectedSubspaces != null) {
                final updatedIds = slectedSubspaces.map((s) => s.internalId).toSet();
                if (existingSubSpaces != null) {
                  final deletedSubspaces =
                      existingSubSpaces.where((s) => !updatedIds.contains(s.internalId)).toList();
                  for (var s in deletedSubspaces) {
                    if (s.tags != null) {
                      tagsToAppendToSpace.addAll(s.tags!);
                    }
                  }
                }
              }
              if (slectedSubspaces != null) {
                setState(() {
                  subspaces = slectedSubspaces;
                  tags?.addAll(tagsToAppendToSpace);
                  selectedSpaceModel = null;
                });
              }
            });
      },
    );
  }

  void _showTagCreateDialog(
      BuildContext context, String name, bool isEdit, List<ProductModel>? products) {
    isEdit
        ? showDialog(
            context: context,
            builder: (BuildContext context) {
              return AssignTagDialog(
                title: 'Edit Device',
                addedProducts: TagHelper.createInitialSelectedProductsForTags(tags, subspaces),
                spaceName: name,
                products: products,
                subspaces: subspaces,
                allTags: widget.allTags,
                projectTags: widget.projectTags,
                onSave: (selectedSpaceTags, selectedSubspaces) {
                  setState(() {
                    tags = selectedSpaceTags;
                    selectedSpaceModel = null;

                    if (selectedSubspaces != null) {
                      if (subspaces != null) {
                        for (final subspace in subspaces!) {
                          for (final selectedSubspace in selectedSubspaces) {
                            if (subspace.subspaceName == selectedSubspace.subspaceName) {
                              subspace.tags = selectedSubspace.tags;
                            }
                          }
                        }
                      }
                    }
                  });
                },
              );
            },
          )
        : showDialog(
            context: context,
            builder: (BuildContext context) {
              return AddDeviceTypeWidget(
                spaceName: name,
                products: products,
                subspaces: subspaces,
                spaceTags: tags,
                isCreate: true,
                allTags: widget.allTags,
                projectTags: widget.projectTags,
                initialSelectedProducts:
                    TagHelper.createInitialSelectedProductsForTags(tags, subspaces),
                onSave: (selectedSpaceTags, selectedSubspaces) {
                  setState(() {
                    tags = selectedSpaceTags;
                    selectedSpaceModel = null;

                    if (selectedSubspaces != null) {
                      if (subspaces != null) {
                        for (final subspace in subspaces!) {
                          for (final selectedSubspace in selectedSubspaces) {
                            if (subspace.subspaceName == selectedSubspace.subspaceName) {
                              subspace.tags = selectedSubspace.tags;
                            }
                          }
                        }
                      }
                    }
                  });
                },
              );
            },
          );
  }
}
