const _ = require("lodash");
import Grid from "../Grid";
import React, { useContext } from "react";
import Text, { Element, Size } from "../Text";
import SimilarItemsSchema from "../SimilarItemsSchema";
import { CollectionContext } from "../Layout";
import * as styles from "./styles.module.scss";

interface IProps {
  tags: [string];
  titolo: string;
}

const SimilarItems = ({ titolo, tags }: IProps) => {
  const categoryLocale = "categoryIt";
  let collection = useContext(CollectionContext);
  collection = collection.edges.filter(item => item.node.titolo !== titolo);
  let similar = collection;

  tags.forEach(tag => {
    if (similar.length > 6) {
      similar = similar.filter(item => item.node[categoryLocale].includes(tag));
    }
  });

  if (similar.length < 5 && tags.length > 1) {
    similar = [
      ...similar,
      ...collection.filter(item => item.node[categoryLocale].includes(tags[1]))
    ];
  }

  if (similar.length === 0) {
    similar = _(collection)
      .shuffle()
      .take(5)
      .value();
  } else {
    similar = _(similar)
      .take(5)
      .value();
  }

  return (
    <div className={styles.similar}>
      <header className={styles.header}>
        <Text element={Element.H4} size={Size.H3}>
          Oggetti simili
        </Text>
      </header>
      <Grid collection={similar} />
      <SimilarItemsSchema collection={similar} />
    </div>
  );
};

export default SimilarItems;
