import React, { useState } from 'react';
import { useNavigation, NavigationProp } from '@react-navigation/native';
import { Meme } from '../../database';
import { ROUTE, RootStackParamList } from '../../types';
import { Card } from 'react-native-paper';
import { Image, StyleSheet } from 'react-native';
import { useDimensions } from '../../contexts';

const memeCardStyles = StyleSheet.create({
  card: {
    margin: 5,
  },
});

const MemeCard = ({ meme }: { meme: Meme }) => {
  const { navigate } = useNavigation<NavigationProp<RootStackParamList>>();
  const { dimensions } = useDimensions();

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

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

  return (
    <>
      {imageWidth && imageHeight && (
        <Card
          onPress={() =>
            navigate(ROUTE.EDIT_MEME, { id: meme.id.toHexString() })
          }
          style={memeCardStyles.card}>
          <Card.Cover
            source={{ uri: meme.uri }}
            style={{ width: imageWidth, height: imageHeight }}
          />
          <Card.Title
            title={meme.title}
            titleVariant="titleSmall"
            titleNumberOfLines={3}
          />
        </Card>
      )}
    </>
  );
};

export default MemeCard;
