import { Alert, Button, Col, Row, Space } from "antd";
import i18n from "i18next";
import React from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectUpdateAvailable } from "../../redux/application/application.selectors";
import { AlertOutlined } from "@ant-design/icons";
import { useTranslation } from "react-i18next";
import { setUpdateAvailable } from "../../redux/application/application.actions";
import { store } from "../../redux/store";
import * as serviceWorkerRegistration from "../../serviceWorkerRegistration";

let globalRegistration;

const mapStateToProps = createStructuredSelector({
  updateAvailable: selectUpdateAvailable,
});
const mapDispatchToProps = (dispatch) => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(UpdateAlert);

export function UpdateAlert({ updateAvailable }) {
  const { t } = useTranslation();
  if (!updateAvailable) return null;
  return (
    <Alert
      message={t("general.messages.newversiontitle")}
      showIcon
      icon={<AlertOutlined />}
      description={
        <Row gutter={[16, 16]}>
          <Col sm={24} md={16} lg={18}>
            {t("general.messages.newversionmessage")}
          </Col>
          <Col sm={24} md={8} lg={6}>
            <Space wrap>
              <Button
                onClick={async () => {
                  window.open("https://imex-online.noticeable.news/", "_blank");
                }}
              >
                {i18n.t("general.actions.viewreleasenotes")}
              </Button>
              <Button
                type="primary"
                onClick={async () => {
                  if (globalRegistration && globalRegistration.waiting) {
                    await globalRegistration.unregister();
                    // Makes Workbox call skipWaiting()
                    globalRegistration.waiting.postMessage({
                      type: "SKIP_WAITING",
                    });
                    // Once the service worker is unregistered, we can reload the page to let
                    // the browser download a fresh copy of our app (invalidating the cache)
                    window.location.reload();
                  }
                }}
              >
                {i18n.t("general.actions.refresh")}
              </Button>
            </Space>
          </Col>
        </Row>
      }
      closable={false}
      type="warning"
    />
  );
}

const onServiceWorkerUpdate = (registration) => {
  console.log("onServiceWorkerUpdate", registration);
  globalRegistration = registration;
  store.dispatch(setUpdateAvailable(true));
};

serviceWorkerRegistration.register({ onUpdate: onServiceWorkerUpdate });
