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

const memeMasonryItemStyles = StyleSheet.create({
  view: {
    margin: 2.5,
    borderRadius: 5,
  },
  image: {
    borderRadius: 5,
  },
});

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

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

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

  return (
    <TouchableHighlight
      onPress={() => focusMeme(index)}
      style={memeMasonryItemStyles.view}>
      {error || !dimensions ? (
        <MemeFail
          style={[
            memeMasonryItemStyles.image,
            {
              width: (width * 0.92) / masonryColumns - 5,
              height: (width * 0.92) / masonryColumns - 5,
            },
          ]}
          iconSize={getFontAwesome5IconSize(masonryColumns)}
        />
      ) : (
        <Image
          source={{ uri: meme.uri }}
          style={[
            memeMasonryItemStyles.image,
            {
              width: (width * 0.92) / masonryColumns - 5,
              height:
                ((width * 0.92) / masonryColumns - 5) / dimensions.aspectRatio,
            },
          ]}
        />
      )}
    </TouchableHighlight>
  );
};

export default MemesMasonryItem;
