#include <reanimated/Fabric/ShadowTreeCloner.h>

#include <reanimated/Tools/ReanimatedSystraceSection.h>

#include <ranges>
#include <utility>

// amzn_mod - Kepler-specific logging for `convertToFollyDynamic`
#ifdef KEPLER
#include <Kepler/turbomodule/TMLog.h>
#include <fmt/format.h>
#endif // KEPLER

namespace reanimated {

Props::Shared mergeProps(
    const ShadowNode &shadowNode,
    const PropsMap &propsMap,
    const ShadowNodeFamily &family) {
  ReanimatedSystraceSection s("ShadowTreeCloner::mergeProps");

  const auto it = propsMap.find(&family);

  if (it == propsMap.end()) {
    return ShadowNodeFragment::propsPlaceholder();
  }

  PropsParserContext propsParserContext{
      shadowNode.getSurfaceId(), *shadowNode.getContextContainer()};
  const auto &propsVector = it->second;
  auto newProps = shadowNode.getProps();

// amzn_mod - props from state update were overriden by props from `propsMap`
// `cloneProps` populates `changedPropsMap_` with props passed to `propsMap`
// This ensures that props from `shadowNode` are also included in new `changedPropsMap_`
#if defined(KEPLER)
  folly::dynamic mergedProps = folly::dynamic::object;
  for (auto& changedPropsMapIt : shadowNode.getProps()->changedPropsMap_) {
    mergedProps[changedPropsMapIt.first] = convertToFollyDynamic(shadowNode.getComponentName(), changedPropsMapIt.first, changedPropsMapIt.second); 
  }

  react_native_assert(it != propsMap.end() && "Iterator over propsMap is invalid");
  for (const auto &props : propsVector) {
    mergedProps.update((folly::dynamic) RawProps(props));
  }

  newProps = shadowNode.getComponentDescriptor().cloneProps(
    propsParserContext, newProps, RawProps(mergedProps));
  return newProps;
#elif defined(ANDROID)
// amzn_mod - props from state update were overriden by props from `propsMap`
  if (propsVector.size() > 1) {
    folly::dynamic newPropsDynamic = folly::dynamic::object;
    for (const auto &props : propsVector) {
      newPropsDynamic = folly::dynamic::merge(
          props.operator folly::dynamic(), newPropsDynamic);
    }
    return shadowNode.getComponentDescriptor().cloneProps(
        propsParserContext, newProps, RawProps(newPropsDynamic));
  }
#endif

  for (const auto &props : propsVector) {
    newProps = shadowNode.getComponentDescriptor().cloneProps(
        propsParserContext, newProps, RawProps(props));
  }

  return newProps;
}

std::shared_ptr<ShadowNode> cloneShadowTreeWithNewPropsRecursive(
    const ShadowNode &shadowNode,
    const ChildrenMap &childrenMap,
    const PropsMap &propsMap) {
  const auto family = &shadowNode.getFamily();
  const auto affectedChildrenIt = childrenMap.find(family);
  auto children = shadowNode.getChildren();

  if (affectedChildrenIt != childrenMap.end()) {
    for (const auto index : affectedChildrenIt->second) {
      children[index] = cloneShadowTreeWithNewPropsRecursive(
          *children[index], childrenMap, propsMap);
    }
  }

  return shadowNode.clone(
      {mergeProps(shadowNode, propsMap, *family),
       std::make_shared<std::vector<std::shared_ptr<const ShadowNode>>>(
           children),
       shadowNode.getState(),
       false});
}

RootShadowNode::Unshared cloneShadowTreeWithNewProps(
    const RootShadowNode &oldRootNode,
    const PropsMap &propsMap) {
  ReanimatedSystraceSection s("ShadowTreeCloner::cloneShadowTreeWithNewProps");

  ChildrenMap childrenMap;

  {
    ReanimatedSystraceSection s("ShadowTreeCloner::prepareChildrenMap");

    for (auto &[family, _] : propsMap) {
      const auto ancestors = family->getAncestors(oldRootNode);
// amzn_mod - std::ranges::reverse_view is not supported on clang versions < 16
#ifdef KEPLER
    for (auto parentNodeIt = ancestors.rbegin(); parentNodeIt != ancestors.rend(); ++parentNodeIt) {
      const auto parentFamily = &parentNodeIt->first.get().getFamily();
      const int index = *(&parentNodeIt->second);
#else
      for (const auto &[parentNode, index] :
           std::ranges::reverse_view(ancestors)) {
        const auto parentFamily = &parentNode.get().getFamily();
#endif // KEPLER
// amzn_mod - std::ranges::reverse_view is not supported on clang versions < 16
        auto &affectedChildren = childrenMap[parentFamily];
        if (affectedChildren.contains(index)) {
          continue;
        }

        affectedChildren.insert(index);
      }
    }
  }

  // This cast is safe, because this function returns a clone
  // of the oldRootNode, which is an instance of RootShadowNode
  return std::static_pointer_cast<RootShadowNode>(
      cloneShadowTreeWithNewPropsRecursive(oldRootNode, childrenMap, propsMap));
}

// amzn_mod - needed because some of the values might cause `bad_any_cast`
#ifdef KEPLER
folly::dynamic convertToFollyDynamic(
    const std::string &componentName,
    const std::string &propName,
    const std::any &value) {
  try {
    return std::any_cast<folly::dynamic>(value);
  } catch (const std::bad_any_cast &) {
    std::string value_type = value.type().name();
    TMWARN(fmt::format(
        "Custom setter for core prop '{}' detected in '{}' (received "
        "type: {})",
        propName,
        componentName,
        value_type));
    /**
     * This is a case of custom setters for Core props, which is not allowed.
     * TODO: Remove this workaround once PROJVEGA-250051 blocks core prop custom
     *setters
     **/
    if (propName == "opacity" || propName == "borderBottomStartRadius" || propName == "borderTopStartRadius" ||
        propName == "borderTopLeftRadius" || propName == "borderTopRightRadius" || propName == "borderBottomLeftRadius" ||
        propName == "borderBottomRightRadius" || propName == "borderTopEndRadius" || propName == "borderBottomEndRadius") {
      return folly::dynamic(std::any_cast<facebook::react::Float>(value));
    }
    if (value_type == typeid(facebook::react::SharedColor).name()) {
      return folly::dynamic(*std::any_cast<facebook::react::SharedColor>(value));
    }
    TMERROR(fmt::format(
        "Failed to convert core prop '{}' to folly::dynamic (type: {})",
        propName,
        value.type().name()));
    throw;
  }
}
#endif // KEPLER

} // namespace reanimated
