/**
 * Copyright (c) 2025 Huawei Technologies Co., Ltd.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import {Animated} from 'react-native';
import {TestCase} from '../../components';
import {AnimatedValueTestCore as AnimatedValueTestCore} from './AnimatedValueTestCore';
import {SimpleText} from 'react-native-harmony-sample-package';
import {useEffect, useRef} from 'react';
import {TestSuite} from '@rnoh/testerino';

const AnimatedSimpleText = Animated.createAnimatedComponent(SimpleText);

export const AnimatedValueTest = () => {
  return (
    <TestSuite name="Animated.Value">
      <AnimatedValueTestCore />
      <TestCase.Automated
        tags={['sequential']}
        itShould="interpolate numbers detected in a string"
        initialState={0}
        arrange={({setState, done}) => {
          return (
            <StringInterpolationExample
              onTextChange={text => {
                const value = parseFloat(text.replace('foo', ''));
                setState(value);
              }}
              onAnimationComplete={done}
            />
          );
        }}
        act={() => {}}
        assert={({expect, state}) => {
          // done() fires just before the final text update, so the value sits slightly under 100 when the assertion runs
          expect(state).to.be.closeTo(100, 1);
        }}
      />
    </TestSuite>
  );
};

const StringInterpolationExample = ({
  onTextChange,
  onAnimationComplete,
}: {
  onTextChange: (text: string) => void;
  onAnimationComplete: () => void;
}) => {
  const animValueRef = useRef(new Animated.Value(0));
  const interpolatedAnimValueRef = useRef(
    animValueRef.current.interpolate({
      inputRange: [0, 1],
      outputRange: ['0foo', '100foo'],
    }),
  );
  const onAnimationCompleteRef = useRef(onAnimationComplete);

  useEffect(() => {
    onAnimationCompleteRef.current = onAnimationComplete;
  }, [onAnimationComplete]);

  useEffect(() => {
    Animated.timing(animValueRef.current, {
      toValue: 1,
      duration: 1000,
      useNativeDriver: true,
    }).start(() => {
      onAnimationCompleteRef.current();
    });
  }, []);

  return (
    <Animated.View
      style={{
        justifyContent: 'center',
        alignItems: 'center',
        height: 64,
      }}>
      <AnimatedSimpleText
        style={{height: 64, width: '64%'}}
        text={interpolatedAnimValueRef.current}
        onTextChange={onTextChange}
      />
    </Animated.View>
  );
};