import React, { useState } from 'react';
import { useNavigation, NavigationProp } from '@react-navigation/native';
import { Image, TouchableHighlight, View } from 'react-native';
import { useSelector } from 'react-redux';
import { Meme } from '../../../database';
import { ROUTE, RootStackParamList } from '../../../types';
import { useDimensions } from '../../../contexts';
import { RootState } from '../../../state';

const MemesGridItem = ({ meme }: { meme: Meme }) => {
  const { navigate } = useNavigation<NavigationProp<RootStackParamList>>();
  const { dimensions } = useDimensions();
  const gridColumns = useSelector(
    (state: RootState) => state.settings.gridColumns,
  );

  const [imageWidth, setImageWidth] = useState<number>();
  const [imageHeight, setImageHeight] = useState<number>();

  Image.getSize(meme.uri, () => {
    const paddedWidth = (dimensions.width * 0.92 - 5) / gridColumns;
    setImageWidth(paddedWidth);
    setImageHeight(paddedWidth);
  });

  return (
    <>
      {imageWidth && imageHeight && (
        <View>
          <TouchableHighlight
            onPress={() =>
              navigate(ROUTE.EDIT_MEME, { id: meme.id.toHexString() })
            }>
            <Image
              source={{ uri: meme.uri }}
              style={[{ width: imageWidth, height: imageHeight }]}
            />
          </TouchableHighlight>
        </View>
      )}
    </>
  );
};

export default MemesGridItem;
