import { GalleryContext } from "../Layout";
import { usePrettify } from "../../hooks/use-prettify";
import { usePriceValidUntil } from "../../hooks/use-price-valid-until";
import Helmet from "react-helmet";
import React, { useContext } from "react";

interface IProps {
  collection: any;
}

const SimilarItemsSchema = ({ collection }: IProps) => {
  const galleryAll = useContext(GalleryContext);
  let thumb = {
    src: "",
    width: "",
    height: ""
  };
  const catalog = collection.map(item => {
    const image = galleryAll.find(
      element =>
        element.relativeDirectory === item.node.parent.relativeDirectory
    );
    if (image) {
      thumb = image.fluid;
    }
    return {
      "@type": "Offer",
      itemOffered: {
        "@type": "Product",
        name: usePrettify(item.node.titolo),
        description: item.descrizioneAlgolia,
        url: `/${item.node.titolo}`,
        image: thumb.src
      },
      url: `/${item.node.titolo}`,
      priceCurrency: "EUR",
      price: item.node.price,
      itemCondition: "https://schema.org/UsedCondition",
      availability: "https://schema.org/LimitedAvailability",
      priceValidUntil: usePriceValidUntil()
    };
  });

  const list = collection.map((item, key) => {
    const image = galleryAll.find(
      element =>
        element.relativeDirectory === item.node.parent.relativeDirectory
    );
    if (image) {
      thumb = image.fluid;
    }
    return {
      "@type": "ListItem",
      position: key,
      item: {
        "@type": "Product",
        name: usePrettify(item.node.titolo),
        description: item.descrizioneAlgolia,
        image: thumb.src,
        url: `/${item.node.titolo}`,
        offers: {
          "@type": "Offer",
          price: item.node.price,
          priceCurrency: "EUR",
          itemCondition: "https://schema.org/UsedCondition",
          availability: "https://schema.org/LimitedAvailability",
          priceValidUntil: usePriceValidUntil()
        }
      }
    };
  });

  const schemaOrgJSONLD = [
    {
      "@context": "https://schema.org/",
      "@type": "ItemList",
      numberOfItems: collection.length,
      name: "Oggetti simili",
      itemListElement: list,
      hasOfferCatalog: {
        "@type": "OfferCatalog",
        name: "Oggetti simili",
        itemListElement: catalog
      }
    }
  ];

  return (
    <Helmet>
      <script type="application/ld+json">
        {JSON.stringify(schemaOrgJSONLD)}
      </script>
    </Helmet>
  );
};

export default SimilarItemsSchema;
