import AsyncStorage from '@react-native-community/async-storage';
import React, {useCallback, useEffect, useState} from 'react';
import {Alert, LayoutChangeEvent, StyleSheet, View} from 'react-native';
import Animated from 'react-native-reanimated';
import {AuthContext, ProfileContext} from '../../routes/';
import {MomentType} from 'src/types';
import {defaultMoments, MOMENTS_ENDPOINT} from '../../constants';
import {SCREEN_HEIGHT} from '../../utils';
import TaggsBar from '../taggs/TaggsBar';
import {Moment} from '../moments';
import ProfileBody from './ProfileBody';
import ProfileCutout from './ProfileCutout';
import ProfileHeader from './ProfileHeader';

interface ContentProps {
  y: Animated.Value<number>;
  isProfileView: boolean;
}

const Content: React.FC<ContentProps> = ({y, isProfileView}) => {
  const [profileBodyHeight, setProfileBodyHeight] = useState(0);
  const {newMomentsAvailable, updateMoments, user} = isProfileView
    ? React.useContext(ProfileContext)
    : React.useContext(AuthContext);
  const [imagesList, setImagesList] = useState<MomentType[]>([]);
  const [imagesMap, setImagesMap] = useState<Map<string, MomentType[]>>(
    new Map(),
  );
  const onLayout = (e: LayoutChangeEvent) => {
    const {height} = e.nativeEvent.layout;
    setProfileBodyHeight(height);
  };

  const {userId, username} = user;

  const createImagesMap = useCallback(() => {
    var map = new Map();
    imagesList.forEach(function (imageObject) {
      var moment_category = imageObject.moment_category;
      if (map.has(moment_category)) {
        map.get(moment_category).push(imageObject);
      } else {
        map.set(moment_category, [imageObject]);
      }
    });

    setImagesMap(map);
  }, [imagesList]);

  useEffect(() => {
    if (!userId) {
      return;
    }

    const retrieveMoments = async () => {
      try {
        const token = await AsyncStorage.getItem('token');
        const response = await fetch(MOMENTS_ENDPOINT + '?user_id=' + userId, {
          method: 'GET',
          headers: {
            Authorization: 'Token ' + token,
          },
        });
        const status = response.status;
        if (status === 200) {
          const data = await response.json();
          setImagesList(data);
          updateMoments(!newMomentsAvailable);
        } else {
          console.log('Could not load moments!');
        }
      } catch (err) {
        console.log(err);
      }
    };

    if (newMomentsAvailable) {
      retrieveMoments();
      createImagesMap();
    }
  }, [userId, createImagesMap, updateMoments, newMomentsAvailable]);

  return (
    <Animated.ScrollView
      style={styles.container}
      onScroll={(e) => y.setValue(e.nativeEvent.contentOffset.y)}
      showsVerticalScrollIndicator={false}
      scrollEventThrottle={1}
      stickyHeaderIndices={[2, 4]}>
      <ProfileCutout>
        <ProfileHeader {...{isProfileView}} />
      </ProfileCutout>
      <ProfileBody {...{onLayout, isProfileView}} />
      <TaggsBar {...{y, profileBodyHeight, isProfileView}} />
      <View style={styles.momentsContainer}>
        {defaultMoments.map((title, index) => (
          <Moment
            key={index}
            title={title}
            images={imagesMap.get(title)}
            isProfileView={isProfileView}
          />
        ))}
      </View>
    </Animated.ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  momentsContainer: {
    backgroundColor: '#f2f2f2',
    paddingBottom: SCREEN_HEIGHT / 10,
  },
});

export default Content;
