import * as React from 'react';
import { useContext, useEffect, useMemo, useState } from 'react';
import * as ReactDOM from 'react-dom';
import { usePersistedMap } from '@assets/js-shop/components/hooks/usePersistedMap';
import { GET_IN_STORE_SELLER_DETAIL } from '@assets/js-shop/query';
import { DataContext } from '@assets/js-shop/context';
import { findNewSellerElements } from '@assets/js-shop/sellers/SellersUtil';
import { SellerAvailabilityDetail } from '@assets/js-shop/sellers/SellerAvailabilityDetail';
import { ShopUtils } from '@assets/js-shop/ShopUtils';

const sellerAvailabilityDetailSelector = '[data-js-shop-seller-availability=\'detail\']';

export const SELLERS_DETAIL_CACHE_KEY = 'sellers-detail';

const CACHE_ITEMS_TTL = 3*60; // s

export interface IProductSellerDetail {
   element: HTMLElement;
   productId: number;
   html?: string;
}

export function SellerAvailabilityDetailData() {
   const context = useContext(DataContext);
   const [items, setItems] = useState<IProductSellerDetail[]>([]);

   const itemsMap = usePersistedMap<number>(SELLERS_DETAIL_CACHE_KEY);

   useEffect(() => {
      findNewElementsAndFetch();
   }, []);


   const findNewElementsAndFetch = () => {
      const { cachedItems, itemsToFetch } = findNewSellerElements(sellerAvailabilityDetailSelector, itemsMap);

      const tmpItems: IProductSellerDetail[] = cachedItems.map((val) => {
         return { ...val, html: itemsMap.get(val.productId) };
      });
         console.log(tmpItems);

      if (itemsToFetch.size > 0) {
         setItems(tmpItems);
         const variables = { filter: { id: Array.from(itemsToFetch.keys()) }};
         context.client.query({ query: GET_IN_STORE_SELLER_DETAIL, variables }).then((result) => {
            result.data.products.items.forEach((item) => {
               tmpItems.push({ ...itemsToFetch.get(item.id), html: item.sellerAvailabilityDetail });
               itemsMap.set(item.id, item.sellerAvailabilityDetail, CACHE_ITEMS_TTL);
            });
            itemsMap.persist();
            setItems([...tmpItems]);
         }).catch((e) => ShopUtils.handleFetchError(e, {query: 'GET_IN_STORE_SELLER_DETAIL', variables}));
      } else {
         setItems(tmpItems);
      }
   };

   const content = useMemo(() => {
      return <>
         {items.filter((value) => value.element).map((value) => {
            ShopUtils.clearElement(value.element);
            return ReactDOM.createPortal(<SellerAvailabilityDetail html={value.html}/>, value.element);
         })}
      </>;
   }, [items]);


   return <>
      {context.seller && content}
   </>;
}
