import {BlurView} from '@react-native-community/blur';
import {RouteProp} from '@react-navigation/native';
import {StackNavigationProp} from '@react-navigation/stack';
import React, {useEffect, useRef, useState} from 'react';
import {FlatList, Keyboard, StyleSheet} from 'react-native';
import {useSelector} from 'react-redux';
import {IndividualMomentTitleBar, MomentPost} from '../../components';
import {AVATAR_DIM} from '../../constants';
import {MainStackParams} from '../../routes';
import {RootState} from '../../store/rootreducer';
import {MomentPostType} from '../../types';
import {
  isIPhoneX,
  normalize,
  SCREEN_HEIGHT,
  StatusBarHeight,
} from '../../utils';

/**
 * Individual moment view opened when user clicks on a moment tile
 */

type MomentContextType = {
  keyboardVisible: boolean;
  scrollTo: (index: number) => void;
};

export const MomentContext = React.createContext({} as MomentContextType);

type IndividualMomentRouteProp = RouteProp<MainStackParams, 'IndividualMoment'>;

type IndividualMomentNavigationProp = StackNavigationProp<
  MainStackParams,
  'IndividualMoment'
>;

interface IndividualMomentProps {
  route: IndividualMomentRouteProp;
  navigation: IndividualMomentNavigationProp;
}

const IndividualMoment: React.FC<IndividualMomentProps> = ({
  route,
  navigation,
}) => {
  const {
    userXId,
    screenType,
    moment: {moment_category, moment_id},
  } = route.params;
  const {moments} = useSelector((state: RootState) =>
    userXId ? state.userX[screenType][userXId] : state.moments,
  );
  const scrollRef = useRef<FlatList<MomentPostType>>(null);
  const momentData = moments.filter(
    (m) => m.moment_category === moment_category,
  );
  const initialIndex = momentData.findIndex((m) => m.moment_id === moment_id);
  const [keyboardVisible, setKeyboardVisible] = useState(false);

  useEffect(() => {
    const showKeyboard = () => setKeyboardVisible(true);
    const hideKeyboard = () => setKeyboardVisible(false);
    Keyboard.addListener('keyboardWillShow', showKeyboard);
    Keyboard.addListener('keyboardWillHide', hideKeyboard);
    return () => {
      Keyboard.removeListener('keyboardWillShow', showKeyboard);
      Keyboard.removeListener('keyboardWillHide', hideKeyboard);
    };
  }, []);

  const scrollTo = (index: number) => {
    // TODO: make this dynamic
    const offset = isIPhoneX() ? -(AVATAR_DIM + 100) : -(AVATAR_DIM + 160);
    scrollRef.current?.scrollToIndex({
      index: index,
      viewOffset: offset,
    });
  };

  return (
    <MomentContext.Provider
      value={{
        keyboardVisible,
        scrollTo,
      }}>
      <BlurView
        blurType="light"
        blurAmount={30}
        reducedTransparencyFallbackColor="white"
        style={styles.contentContainer}>
        <IndividualMomentTitleBar
          style={styles.header}
          close={() => navigation.goBack()}
          title={moment_category}
        />
        <FlatList
          ref={scrollRef}
          data={momentData}
          contentContainerStyle={styles.listContentContainer}
          renderItem={({item, index}) => (
            <MomentPost
              moment={item}
              userXId={userXId}
              screenType={screenType}
              index={index}
            />
          )}
          keyExtractor={(item, _) => item.moment_id}
          showsVerticalScrollIndicator={false}
          initialScrollIndex={initialIndex}
          onScrollToIndexFailed={() => {
            // TODO: code below does not work, index resets to 0
            // const wait = new Promise((resolve) => setTimeout(resolve, 500));
            // wait.then(() => {
            //   console.log('scrolling to ', initialIndex);
            //   scrollRef.current?.scrollToIndex({index: initialIndex});
            // });
          }}
        />
      </BlurView>
    </MomentContext.Provider>
  );
};
const styles = StyleSheet.create({
  contentContainer: {
    paddingTop: StatusBarHeight,
    flex: 1,
  },
  header: {
    height: normalize(70),
  },
  listContentContainer: {
    paddingBottom: SCREEN_HEIGHT * 0.2,
  },
});

export default IndividualMoment;
