import React, { useEffect, useState } from 'react';
import { useSpring } from 'react-spring';
import { useTheme } from 'styled-components';
import { getImageSource } from '../../helpers/getImageSource';
import { usePrevious } from '../../hooks';
import { ItemMiniCardProps } from '../../interfaces';
import FavoriteButton from '../FavoriteButton';
import FavoriteToast from '../FavoriteToast';
import Typography from '../Typography';
import {
  BoxWrapper,
  InnerItemContainer,
  Image,
  ItemInformationCard,
  ItemNameContainer,
} from './styles';

const ItemMiniCard: React.FC<ItemMiniCardProps> = ({
  itemSrc,
  onClick,
  itemName,
  itemUsername,
  isFavorite,
  onFavoriteClick,
  showFavorite = true,
  favoriteCount = 0,
}) => {
  const [hover, setHover] = useState<boolean>();
  const { colors } = useTheme();
  const prevIsFavorite = usePrevious(isFavorite);
  const [showFavoriteToast, setShowFavoriteToast] = useState(false);

  useEffect(() => {
    if (isFavorite && prevIsFavorite === false) {
      // show favorite toast for 3 seconds
      setShowFavoriteToast(true);
      setTimeout(() => {
        setShowFavoriteToast(false);
      }, 3000);
    }
  }, [isFavorite]);

  const expand = useSpring({
    opacity: hover ? 1 : 0,
  });

  return (
    <BoxWrapper
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={onClick}
    >
      <InnerItemContainer>
        <Image src={getImageSource(itemSrc, 240)} />
      </InnerItemContainer>

      {hover && showFavorite && (
        <FavoriteButton
          active={isFavorite || false}
          onClick={(e) => {
            e.preventDefault();
            e.stopPropagation();
            onFavoriteClick?.();
          }}
          size="small"
          top={4}
          right={4}
          favoriteCount={favoriteCount}
        />
      )}

      <FavoriteToast
        visable={showFavoriteToast}
        message="Added to Favorites"
        size="small"
      />

      {hover && itemUsername && (
        <ItemInformationCard style={expand}>
          <ItemNameContainer>
            <Typography
              variant="utility3"
              fontSize={13}
              lineHeight={16}
              color={colors.neutral[900]}
            >
              {itemName}
            </Typography>
          </ItemNameContainer>
          <Typography
            fontSize={10}
            lineHeight={12.5}
            color={colors.neutral[500]}
          >
            @{itemUsername}
          </Typography>
        </ItemInformationCard>
      )}
    </BoxWrapper>
  );
};

export default ItemMiniCard;
