import {
  clamp,
  Extrapolation,
  interpolate,
  useAnimatedReaction,
  useAnimatedScrollHandler,
  useAnimatedStyle,
  useDerivedValue,
  useSharedValue,
} from 'react-native-reanimated';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {CONVERSATION_ITEM_HEIGHT} from '@modules/chats/constants';
import {useConversationsSize} from '@modules/chats/store';
import {windowDimensions} from '@shared/constants';

import {INPUT_SEARCH_HEIGHT} from '../styles';
import {HEADER_HEIGHT} from '../components/ChatHomeHeader/styles';

const INPUT_SEARCH_HEIGHT_DOUBLE = INPUT_SEARCH_HEIGHT * 2;

interface UseSearchBarAnimationParams {
  showSearchResults: boolean;
}

export const useSearchBarAnimation = ({
  showSearchResults,
}: UseSearchBarAnimationParams) => {
  const {top} = useSafeAreaInsets();
  const conversationsSize = useConversationsSize();

  const searchBarTranslateY = useSharedValue(0);

  const availableContentHeight = windowDimensions.height - top - HEADER_HEIGHT;
  const listContentHeight = CONVERSATION_ITEM_HEIGHT * conversationsSize;

  const isScrollAnimationEnabledShared = useDerivedValue(
    () => listContentHeight > availableContentHeight,
    [listContentHeight, availableContentHeight],
  );

  const isSearchActive = useDerivedValue(
    () => showSearchResults,
    [showSearchResults],
  );

  // useAnimatedReaction para el side effect de resetear searchBarTranslateY
  useAnimatedReaction(
    () => isSearchActive.value,
    (current, previous) => {
      if (current && !previous) {
        searchBarTranslateY.value = 0;
      }
    },
    [],
  );

  const handleScroll = useAnimatedScrollHandler(event => {
    if (isSearchActive.value || !isScrollAnimationEnabledShared.value) {
      searchBarTranslateY.value = 0;
      return;
    }

    searchBarTranslateY.value = clamp(
      event.contentOffset.y,
      0,
      INPUT_SEARCH_HEIGHT_DOUBLE,
    );
  }, []);

  const searchBarAnimatedStyle = useAnimatedStyle(() => {
    if (!_WORKLET) {
      return {transform: [{translateY: 0}]};
    }
    const translateYValue = interpolate(
      searchBarTranslateY.value,
      [0, INPUT_SEARCH_HEIGHT_DOUBLE],
      [0, INPUT_SEARCH_HEIGHT],
      Extrapolation.CLAMP,
    );
    return {transform: [{translateY: -translateYValue}]};
  }, []);

  const searchBarWrapperStyle = useAnimatedStyle(() => {
    if (!_WORKLET) {
      return {height: INPUT_SEARCH_HEIGHT};
    }

    const height = interpolate(
      searchBarTranslateY.value,
      [0, INPUT_SEARCH_HEIGHT_DOUBLE],
      [INPUT_SEARCH_HEIGHT, 0],
      Extrapolation.CLAMP,
    );
    return {height};
  }, []);

  return {
    handleScroll,
    searchBarAnimatedStyle,
    searchBarWrapperStyle,
  };
};
