import React from 'react';
import { Image, TouchableHighlight } from 'react-native';
import { useSelector } from 'react-redux';
import { useSafeAreaFrame } from 'react-native-safe-area-context';
import { useImageDimensions } from '@react-native-community/hooks';
import { Meme } from '../../../database';
import { RootState } from '../../../state';

const MemesGridItem = ({
  meme,
  index,
  focusMeme,
}: {
  meme: Meme;
  index: number;
  focusMeme: (index: number) => void;
}) => {
  const { width } = useSafeAreaFrame();
  const gridColumns = useSelector(
    (state: RootState) => state.settings.gridColumns,
  );

  const { dimensions, loading, error } = useImageDimensions({ uri: meme.uri });

  if (loading || error || !dimensions) return <></>;

  return (
    <TouchableHighlight onPress={() => focusMeme(index)}>
      <Image
        source={{ uri: meme.uri }}
        style={[
          {
            width: (width * 0.92 - 5) / gridColumns,
            height: (width * 0.92 - 5) / gridColumns,
          },
        ]}
      />
    </TouchableHighlight>
  );
};

export default MemesGridItem;
