import 'package:flutter/material.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/create_space_widgets/devices_part_widget.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/create_space_widgets/icon_choose_part_widget.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/create_space_widgets/space_model_linking_widget.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/create_space_widgets/space_name_textfield_widget.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/create_space_widgets/sub_space_part_widget.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/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: IconChoosePartWidget(
                  selectedIcon: selectedIcon,
                  showIconSelection: _showIconSelectionDialog,
                  screenWidth: screenWidth,
                ),
              ),
              const SizedBox(width: 20),
              Expanded(
                flex: 2,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SpaceNameTextfieldWidget(
                      isNameFieldExist: isNameFieldExist,
                      isNameFieldInvalid: isNameFieldInvalid,
                      nameController: nameController,
                      screenWidth: screenWidth,
                      onChange: (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;
                            }
                          }
                        });
                      },
                    ),
                    const SizedBox(height: 10),
                    // SpaceModelLinkingWidget(
                    //   isSpaceModelDisabled: true,
                    //   //  isSpaceModelDisabled,
                    //   onPressed: () {
                    //     isSpaceModelDisabled
                    //         ? null
                    //         : _showLinkSpaceModelDialog(context);
                    //   },
                    //   onDeleted: () => setState(() {
                    //     selectedSpaceModel = null;
                    //     subspaces = widget.subspaces ?? [];
                    //     tags = widget.tags ?? [];
                    //   }),
                    //   screenWidth: screenWidth,
                    //   selectedSpaceModel: selectedSpaceModel,
                    // ),
                    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),
                    SubSpacePartWidget(
                      subspaces: subspaces,
                      onPressed: () {
                        isTagsAndSubspaceModelDisabled
                            ? null
                            : _showSubSpaceDialog(
                                context,
                                enteredName,
                                [],
                                false,
                                widget.products,
                                subspaces,
                              );
                      },
                      isTagsAndSubspaceModelDisabled:
                          isTagsAndSubspaceModelDisabled,
                      screenWidth: screenWidth,
                      editChipOnTap: () async {
                        _showSubSpaceDialog(
                          context,
                          enteredName,
                          [],
                          true,
                          widget.products,
                          subspaces,
                        );
                      },
                    ),
                    const SizedBox(height: 10),
                    DevicesPartWidget(
                      tags: tags,
                      subspaces: subspaces,
                      screenWidth: screenWidth,
                      isTagsAndSubspaceModelDisabled:
                          isTagsAndSubspaceModelDisabled,
                      onEditChip: () 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;
                              });
                            },
                          ),
                        );
                      },
                      onTextButtonPressed: () {
                        isTagsAndSubspaceModelDisabled
                            ? null
                            : _showTagCreateDialog(
                                context,
                                enteredName,
                                widget.isEdit,
                                widget.products,
                              );
                      },
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
      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'),
              ),
            ),
          ],
        ),
      ],
    );
  }

//dialooogggs
  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-spaces' : 'Create Sub-spaces',
            products: products,
            existingSubSpaces: existingSubSpaces,
            onSave: (slectedSubspaces, updatedSubSpaces) {
              final List<Tag> tagsToAppendToSpace = [];

              if (slectedSubspaces != null && slectedSubspaces.isNotEmpty) {
                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) {
                      s.tags!.forEach(
                        (tag) => tag.location = null,
                      );
                      tagsToAppendToSpace.addAll(s.tags!);
                    }
                  }
                }
              } else {
                if (existingSubSpaces != null) {
                  final deletedSubspaces = existingSubSpaces;

                  for (var s in deletedSubspaces) {
                    if (s.tags != null) {
                      s.tags!.forEach(
                        (tag) => tag.location = 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;
                            }
                          }
                        }
                      }
                    }
                  });
                },
              );
            },
          );
  }
}
