'use strict';
import { logger } from '../../common';
import type { AnimatedStyle, StyleProps } from '../../commonTypes';
import type { PropUpdates } from '../../createAnimatedComponent/commonTypes';
import { createReactDOMStyle } from './webUtils';

export { createJSReanimatedModule } from './JSReanimated';

interface JSReanimatedComponent {
  previousStyle: StyleProps;
  setNativeProps?: (style: StyleProps) => void;
  style?: StyleProps;
  props: Record<string, string | number>;
  _touchableNode: {
    setAttribute: (key: string, props: unknown) => void;
  };
}

export interface ReanimatedHTMLElement extends HTMLElement {
  previousStyle: StyleProps;
  setNativeProps?: (style: StyleProps) => void;
  props: Record<string, string | number>;
  _touchableNode: {
    setAttribute: (key: string, props: unknown) => void;
  };
  isDummy?: boolean;
  dummyClone?: ReanimatedHTMLElement;
  removedAfterAnimation?: boolean;
}

// TODO: Move these functions outside of index file.
export const _updatePropsJS = (
  updates: PropUpdates,
  viewRef: (JSReanimatedComponent | ReanimatedHTMLElement) & {
    getAnimatableRef?: () => JSReanimatedComponent | ReanimatedHTMLElement;
  },
  isAnimatedProps?: boolean
): void => {
  if (viewRef) {
    const component = viewRef.getAnimatableRef
      ? viewRef.getAnimatableRef()
      : viewRef;
    const [rawStyles] = Object.keys(updates).reduce(
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      (acc: [StyleProps, AnimatedStyle<any>], key) => {
        const value = updates[key];
        const index = typeof value === 'function' ? 1 : 0;
        acc[index][key] = value;
        return acc;
      },
      [{}, {}]
    );

    // Check for a DOM node first: React Native Web 0.22 gives its DOM nodes
    // a setNativeProps function that does nothing.
    if (
      createReactDOMStyle !== undefined &&
      'nodeType' in component &&
      component.style !== undefined
    ) {
      // For Animated.Text we need to update textContent directly
      if ('children' in rawStyles) {
        component.textContent = rawStyles.children;
        delete rawStyles.children;
      }

      updatePropsDOM(component, rawStyles, isAnimatedProps);
    } else if (typeof component.setNativeProps === 'function') {
      // Some components (e.g. from react-native-svg) don't have styles
      // and always provide setNativeProps function instead.
      setNativeProps(component, rawStyles, isAnimatedProps);
    } else if (component.props && Object.keys(component.props).length > 0) {
      Object.keys(component.props).forEach((key) => {
        if (!(key in rawStyles)) {
          return;
        }
        const dashedKey = key.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase());
        component._touchableNode.setAttribute(dashedKey, rawStyles[key]);
      });
    } else {
      const componentName =
        'className' in component ? component?.className : '';
      logger.warn(
        `It's not possible to manipulate the component ${componentName}`
      );
    }
  }
};

const setNativeProps = (
  component: JSReanimatedComponent | ReanimatedHTMLElement,
  newProps: StyleProps,
  isAnimatedProps?: boolean
): void => {
  if (isAnimatedProps) {
    // Only update UI props directly on the component,
    // other props can be updated as standard style props.
    component.setNativeProps?.(newProps);
  }

  const previousStyle = component.previousStyle ? component.previousStyle : {};
  const currentStyle = { ...previousStyle, ...newProps };
  component.previousStyle = currentStyle;

  component.setNativeProps?.({ style: currentStyle });
};

const updatePropsDOM = (
  component: JSReanimatedComponent | HTMLElement,
  style: StyleProps,
  isAnimatedProps?: boolean
): void => {
  const previousStyle = (component as JSReanimatedComponent).previousStyle
    ? (component as JSReanimatedComponent).previousStyle
    : {};
  const currentStyle = { ...previousStyle, ...style };
  (component as JSReanimatedComponent).previousStyle = currentStyle;

  if (createReactDOMStyle == null) {
    return;
  }

  if (isAnimatedProps) {
    // Props are attributes, not styles: keep their names, and use the raw
    // value when StyleSheet renames or drops the key (`start`, `tintColor`).
    const resolved = createReactDOMStyle(currentStyle);

    for (const key in currentStyle) {
      const attributeValue: string | number | null | undefined =
        key in resolved ? resolved[key] : currentStyle[key];

      if (attributeValue == null) {
        continue;
      }

      // We need to explicitly set the 'text' property on input component because React Native's
      // internal _valueTracker (https://github.com/facebook/react/blob/main/packages/react-dom-bindings/src/client/inputValueTracking.js)
      // prevents updates when only modifying attributes.
      if ((component as HTMLElement).nodeName === 'INPUT' && key === 'text') {
        (component as HTMLInputElement).value = String(attributeValue);
      } else {
        (component as HTMLElement).setAttribute(key, String(attributeValue));
      }
    }

    return;
  }

  // StyleSheet builds `boxShadow` from the animated shadow* keys only, which
  // would replace a static shadow with a partial one. Leave them out.
  const {
    shadowColor: _shadowColor,
    shadowOpacity: _shadowOpacity,
    shadowOffset: _shadowOffset,
    shadowRadius: _shadowRadius,
    ...styleWithoutShadow
  } = currentStyle;

  const domStyle = createReactDOMStyle(
    styleWithoutShadow,
    getWritingDirection(component)
  );

  for (const key in domStyle) {
    (component.style as StyleProps)[key] = domStyle[key];
  }
};

const DIR_SELECTOR = '[dir]:not(html):not(body)';

// Same rule as react-native-web: the nearest `dir`, ignoring <html> and <body>.
// An element's own `auto` (set by a root Text) defers to its ancestors.
const getWritingDirection = (
  component: JSReanimatedComponent | HTMLElement
): 'ltr' | 'rtl' => {
  if ('closest' in component) {
    const start =
      component.getAttribute('dir') === 'auto'
        ? component.parentElement
        : component;

    if (start?.closest(DIR_SELECTOR)?.getAttribute('dir') === 'rtl') {
      return 'rtl';
    }
  }

  return 'ltr';
};
