import React, { Fragment, useState, useEffect, useMemo, useCallback } from "react";
import useToggle from "../../hooks/useToggle";
import { TextSmall } from "../../components/typography";
import Flex from "../../components/templates/flex";
import Layer from "../../components/templates/layer";
import Container from "./container";
import Header from "./header";
import Item from "./item";
import useFetchNews from "./useFetchNews";
var emptyArray = [];
var News = function News(_ref) {
  var _ref$app = _ref.app,
    app = _ref$app === void 0 ? "cloud" : _ref$app,
    onCloseClick = _ref.onCloseClick,
    children = _ref.children;
  var lastSeen = localStorage.getItem("news_last_seen");
  var _useState = useState(emptyArray),
    news = _useState[0],
    setNews = _useState[1];
  var _useState2 = useState(),
    error = _useState2[0],
    setError = _useState2[1];
  var _useToggle = useToggle(),
    isOpen = _useToggle[0],
    toggle = _useToggle[1];
  var fetchNews = useFetchNews();
  useEffect(function () {
    fetchNews(app, function (_ref2) {
      var results = _ref2.results;
      return setNews(results);
    }, function () {
      return setError(true);
    });
  }, []);
  var upToDate = useMemo(function () {
    if (!news.length) return true;
    var firstItem = news[0];
    var publishedAt = firstItem.last_publication_date;
    return new Date(lastSeen) >= new Date(publishedAt);
  }, [lastSeen, news]);
  var onClose = useCallback(function () {
    toggle();
    localStorage.setItem("news_last_seen", new Date());
    if (onCloseClick) onCloseClick();
  }, [onCloseClick]);
  return /*#__PURE__*/React.createElement(Fragment, null, children({
    toggle: toggle,
    isOpen: isOpen,
    upToDate: upToDate
  }), isOpen && /*#__PURE__*/React.createElement(Layer, {
    backdrop: true,
    onClickOutside: onClose,
    onEsc: onClose
  }, /*#__PURE__*/React.createElement(Flex, {
    background: "dropdown",
    round: true,
    padding: [6],
    width: "640px",
    height: {
      max: "640px"
    },
    gap: 4,
    column: true
  }, /*#__PURE__*/React.createElement(Header, {
    onClose: onClose
  }), /*#__PURE__*/React.createElement(Container, {
    column: true,
    gap: 6
  }, error && /*#__PURE__*/React.createElement(TextSmall, {
    textAlign: "center"
  }, "Something went wrong \uD83D\uDE14"), !error && !news.length && /*#__PURE__*/React.createElement(TextSmall, {
    textAlign: "center"
  }, "There are no latest news"), !error && news.length > 0 && news.map(function (item) {
    return /*#__PURE__*/React.createElement(Item, {
      key: item.id,
      item: item
    });
  })))));
};
export default News;