import '../../common/constants.dart';
import '../../common/tools.dart';
import '../../services/service_config.dart';

class ProductAttribute {
  String? id;
  String? name;
  String? label;
  String? slug;
  List? options = [];
  List optionSlugs = [];
  bool? isVisible;
  bool? isVariation;

  String? get cleanSlug => slug?.replaceAll('pa_', '');
  bool? isDefault;
  bool? isActive = false;

  /// For Variation Swatches plugin
  bool? isImageType;
  bool? isColorType;

  /// For BigCommerce.
  String? type;

  String? get keyAttr => ServerConfig().isWooType
      ? (['null', '0'].contains(id.toString())
            ? label?.toLowerCase()
            : '[${id!}]')
      : name;

  /// For product variation swatches (image)
  Map<String, String?>? get imageUrls {
    Map<String, String?>? imageUrls;
    if (isImageType == true && options != null) {
      imageUrls = {};
      for (var option in options!) {
        if (option['name'] != null && option['image_url'] != null) {
          imageUrls[option['name']] = option['image_url'];
        }
      }
    }
    return imageUrls;
  }

  Map<String, String?>? get colorValues {
    Map<String, String?>? colorValues;
    if (isColorType == true && options != null) {
      colorValues = {};
      for (var option in options!) {
        if (option['name'] != null && option['primary_color'] != null) {
          colorValues[option['name']] = option['primary_color'];
        }
      }
    }
    return colorValues;
  }

  ProductAttribute({
    this.id,
    this.name,
    this.label,
    this.slug,
    this.options,
    this.optionSlugs = const [],
    this.isVisible,
    this.isVariation,
    this.isDefault,
    this.isActive,
    this.type,
    this.isImageType,
    this.isColorType,
  });

  ProductAttribute.fromJson(Map parsedJson) {
    id = parsedJson['id'].toString();
    label = parsedJson['label'] ?? parsedJson['name']?.replaceAll('pa_', '');
    name = parsedJson['name']?.replaceAll('pa_', '');

    slug = parsedJson['slug']?.toString().toLowerCase() ?? parsedJson['name'];
    isVariation = parsedJson['variation'] ?? false;
    isVisible = parsedJson['visible'] ?? false;
    isDefault = parsedJson['default'] ?? false;
    isImageType = parsedJson['is_image_type'] ?? false;
    isColorType = parsedJson['is_color_type'] ?? false;
    if (parsedJson['options'] != null) {
      for (var item in parsedJson['options']) {
        options!.add(item);
      }
    }
    if (parsedJson['slugs'] != null) {
      for (var item in parsedJson['slugs']) {
        optionSlugs.add(item);
      }
    }
  }

  ProductAttribute.fromMagentoJson(Map parsedJson) {
    id = "${parsedJson["attribute_id"]}";
    name = parsedJson['attribute_code'];
    label = name;
    options = parsedJson['options'];
  }

  ProductAttribute.fromServerlessJson(Map parsedJson) {
    id = parsedJson['Name']?.toString().trim();
    name = parsedJson['Name']?.toString().trim().toLowerCase();
    label =
        parsedJson['Label']?.toString() ??
        parsedJson['Name']?.toString().trim();
    slug = parsedJson['Slug']?.toString() ?? name;
    isVariation = parsedJson['IsVariation'] ?? false;
    isVisible = parsedJson['IsVisible'] ?? true;
    isDefault = parsedJson['IsDefault'] ?? false;
    isActive = parsedJson['IsActive'] ?? false;
    isImageType = parsedJson['IsImageType'] ?? false;

    // Extract options from Values
    if (parsedJson['Values'] is List) {
      options = (parsedJson['Values'] as List)
          .map(
            (e) => {'slug': e?.toString().trim(), 'name': e?.toString().trim()},
          )
          .toList();
    } else {
      options = [];
    }

    // Extract option slugs if available
    if (parsedJson['OptionSlugs'] is List) {
      optionSlugs = List.from(parsedJson['OptionSlugs']);
    }
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'label': label,
      'options': options,
      'slugs': optionSlugs,
      'visible': isVisible,
      'variation': isVariation,
      'isActive': isActive,
      'default': isDefault,
      'slug': slug,
      'isImageType': isImageType,
      'isColorType': isColorType,
    };
  }

  ProductAttribute.fromLocalJson(Map json) {
    try {
      id = json['id']?.toString();
      name = json['name'];
      slug = json['slug'];
      options = json['options'];
      label = name;
      isImageType = json['isImageType'];
      isColorType = json['isColorType'];
    } catch (e) {
      printLog(e.toString());
    }
  }

  ProductAttribute.fromShopify(att) {
    try {
      id = att['id'];
      name = att['name'];
      label = name;
      List? values = att['values'];
      if (values != null) {
        options = values;
      }
    } catch (e) {
      printLog(e.toString());
    }
  }

  ProductAttribute.fromPresta(att) {
    try {
      id = att['id'].toString();
      name = att['name'];
      options = att['options'];
      label = name;
    } catch (e) {
      printLog(e.toString());
    }
  }

  ProductAttribute.fromNotion(
    Map<String, dynamic> parsedJson,
    String nameAttribute,
  ) {
    id = parsedJson['id'].toString();
    name = nameAttribute; // name for FluxStore Manager
    label = name;
    slug = nameAttribute;
    isVariation = false;
    isVisible = true;
    options = NotionDataTools.fromMultiSelect(parsedJson);
  }

  ProductAttribute.fromBigCommerceJson(Map json) {
    id = '${json['id']}';
    name = id;
    label = json['display_name'];
    type = json['type'];
    // sortOrder = json['sort_order'];
    final optionValues = json['option_values'];
    if (optionValues is List && optionValues.isNotEmpty) {
      options = [];
      for (var item in optionValues) {
        options?.add(Map.from(item));
        optionSlugs.add(item['id']);
      }
    }
  }

  ProductAttribute copyWith({
    String? id,
    String? name,
    String? label,
    String? slug,
    List? options,
    List? optionSlugs,
    bool? isVisible,
    bool? isVariation,
    bool? isDefault,
    bool? isActive,
    bool? isImageType,
    bool? isColorType,
  }) {
    return ProductAttribute(
      id: id ?? this.id,
      name: name ?? this.name,
      label: label ?? this.label,
      slug: slug ?? this.slug,
      options: options ?? this.options,
      optionSlugs: optionSlugs ?? this.optionSlugs,
      isVisible: isVisible ?? this.isVisible,
      isVariation: isVariation ?? this.isVariation,
      isDefault: isDefault ?? this.isDefault,
      isActive: isActive ?? this.isActive,
      isImageType: isImageType ?? this.isImageType,
      isColorType: isColorType ?? this.isColorType,
    );
  }

  /// Convert ProductAttribute to Firestore Map
  Map<String, dynamic> toFirestoreMap() {
    return {
      'Id': id,
      'Name': name,
      'Label': label,
      'Slug': slug,
      'Values': options?.map((option) {
        if (option is Map) {
          return option['name'];
        }
        return option;
      }).toList(),
      'IsVariation': isVariation,
      'IsVisible': isVisible,
      'IsDefault': isDefault,
      'IsActive': isActive,
      'IsImageType': isImageType,
    };
  }
}

class Attribute {
  String? id;
  String? name;
  String? option;

  /// For BigCommerce & Magento.
  String? optionLabel;

  Attribute({this.id, this.name, this.option, this.optionLabel});

  String? get keyAttr => ServerConfig().isWooType
      ? (['null', '0'].contains(id.toString())
            ? name?.toLowerCase()
            : '[${id!}]')
      : name;

  Attribute.fromJson(Map parsedJson) {
    id = parsedJson['id']?.toString();
    name = parsedJson['name']?.toString();
    option = parsedJson['option']?.toString();
  }

  Attribute.fromMagentoJson(Map parsedJson) {
    id = parsedJson['value']?.toString();
    name = parsedJson['attribute_code']?.toString();
    option = parsedJson['value']?.toString();
    optionLabel = parsedJson['option_label']?.toString();
  }

  Attribute.fromLocalJson(Map parsedJson) {
    id = parsedJson['id']?.toString();
    name = parsedJson['name']?.toString();
    option = parsedJson['option']?.toString();
    optionLabel = parsedJson['option_label']?.toString();
  }

  Attribute.fromShopifyJson(Map parsedJson) {
    id = parsedJson['id']?.toString();
    name = parsedJson['name']?.toString();
    option = parsedJson['value']?.toString();
  }

  Attribute.fromPrestaJson(Map parsedJson) {
    id = parsedJson['id']?.toString();
    name = parsedJson['group_name']?.toString();
    option = parsedJson['name']?.toString();
  }

  Attribute.fromBigCommerceJson(Map json) {
    id = json['id']?.toString();
    name = json['option_id']?.toString();
    option = json['label']?.toString();
    optionLabel = json['option_display_name']?.toString();
  }

  Attribute.fromServerlessJson(Map json) {
    name = json['Name']?.toString().trim().toLowerCase();
    option = json['Value']?.toString().trim();
    optionLabel = json['Value']?.toString().trim();
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'option': option,
      'option_label': optionLabel,
    };
  }

  @override
  String toString() {
    return '${name ?? ""}${option ?? ""}';
  }

  String toStringCompare() {
    return '${keyAttr ?? ''}${option ?? ""}';
  }
}
