import { Colors, Radius, Spacing, Styles } from '../../Consts';
import { InputRef, InputSearch } from '../../Input';
import {
  Animated,
  Dimensions,
  StyleSheet,
  TouchableOpacity,
  View,
} from 'react-native';
import React, { useContext, useEffect, useRef } from 'react';
import { SearchHeaderProps } from '../types';
import { ApplicationContext, MiniAppContext } from '../../Context';
import { Text } from '../../Text';

const SearchHeader = React.forwardRef<InputRef, SearchHeaderProps>(
  (
    {
      animatedValue,
      buttonText = 'Huỷ',
      onPressButtonText,
      renderButtons,
      ...props
    },
    ref,
  ) => {
    const { theme, navigator } = useContext(ApplicationContext);
    const context = useContext<any>(MiniAppContext);
    const BACK_WIDTH = 28;
    const { width: screenWidth } = Dimensions.get('window');

    const animated = useRef(new Animated.Value(0));
    const leftPosition = props?.leftPosition ?? BACK_WIDTH + 20;
    const headerRightWidth = props?.headerRightWidth ?? 73;

    useEffect(() => {
      const listener = animatedValue?.addListener(({ value }) => {
        animated.current.setValue(value);
      });
      return () => {
        if (listener) {
          animatedValue?.removeListener(listener);
        }
      };
    }, [animatedValue]);

    const backgroundColor = animated.current?.interpolate({
      inputRange: [0, 100],
      outputRange: [
        theme.colors.background.surface,
        theme.colors.background.default,
      ],
      extrapolate: 'clamp',
    });

    const goBack = () => {
      const canGoBack = navigator?.ref?.current?.canGoBack?.();
      const currentRoute = navigator?.ref?.current?.getCurrentRoute?.();
      context?.autoTracking?.({
        ...context,
        componentName: 'SearchHeader',
        componentId: 'search_back',
        screenName: currentRoute?.params?.screen?.name ?? currentRoute?.name,
      });

      if (canGoBack) {
        navigator?.ref?.current?.goBack?.();
      } else if (navigator?.maxApi) {
        navigator?.maxApi?.dismiss?.(navigator?.dismissData);
      } else {
        (globalThis as any)?.miniAppApi?.dispatch?.('dismiss', context);
      }
      onPressButtonText?.();
    };

    const goBackSafe = () => {
      goBack();
      return true;
    };

    const showBaseLineDebug = context?.features?.showBaseLineDebug ?? false;

    return (
      <View
        style={[styles.container, showBaseLineDebug && styles.debugBaseLine]}
      >
        <View
          style={[
            Styles.flex,
            renderButtons && {
              maxWidth: screenWidth - leftPosition - 12 - headerRightWidth,
            },
          ]}
        >
          <Animated.View style={{ backgroundColor, borderRadius: Radius.XL }}>
            <InputSearch
              ref={ref}
              {...props}
              backgroundColor={'transparent'}
              showButtonText={false}
            />
          </Animated.View>
        </View>
        {renderButtons && typeof renderButtons === 'function' ? (
          renderButtons()
        ) : (
          <TouchableOpacity onPress={goBackSafe} style={styles.searchAction}>
            <Text typography={'action_default_bold'}>{buttonText}</Text>
          </TouchableOpacity>
        )}
      </View>
    );
  },
);

const styles = StyleSheet.create({
  container: {
    borderRadius: Radius.XL,
    flexDirection: 'row',
    alignItems: 'center',
  },
  searchAction: {
    marginLeft: Spacing.M,
  },
  debugBaseLine: { borderWidth: 1, borderColor: Colors.green_06 },
});

export { SearchHeader };
