import { AlertOutlined } from "@ant-design/icons";
import { Alert, Button, Col, Row, Space } from "antd";
import i18n from "i18next";
import React from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectUpdateAvailable } from "../../redux/application/application.selectors";
import { useRegisterSW } from "virtual:pwa-register/react";
import InstanceRenderManager from "../../utils/instanceRenderMgr";

const mapStateToProps = createStructuredSelector({
  updateAvailable: selectUpdateAvailable
});
const mapDispatchToProps = (dispatch) => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(UpdateAlert);
const intervalMS = 10 * 60 * 1000;
export function UpdateAlert({ updateAvailable }) {
  const { t } = useTranslation();

  const {
    offlineReady: [
      offlineReady //setOfflineReady
    ],
    needRefresh: [
      needRefresh //setNeedRefresh
    ],
    updateServiceWorker
  } = useRegisterSW({
    onRegistered(r) {
      // eslint-disable-next-line prefer-template
      console.log("SW Registered: " + r);
      r &&
        setInterval(() => {
          r.update();
        }, intervalMS);
    },
    onRegisterError(error) {
      console.log("SW registration error", error);
    }
  });

  if (import.meta.env.DEV) console.log(`SW Status => Refresh? ${needRefresh} - offlineReady? ${offlineReady}`);

  if (!needRefresh) return null;
  return (
    <Alert
      message={t("general.messages.newversiontitle", {
        app: InstanceRenderManager({
          imex: "$t(titles.imexonline)",
          rome: "$t(titles.romeonline)",
          promanager: "$t(titles.promanager)"
        })
      })}
      showIcon
      icon={<AlertOutlined />}
      description={
        <Row gutter={[16, 16]}>
          <Col sm={24} md={16} lg={18}>
            {t("general.messages.newversionmessage", {
              app: InstanceRenderManager({
                imex: "$t(titles.imexonline)",
                rome: "$t(titles.romeonline)",
                promanager: "$t(titles.promanager)"
              })
            })}
          </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 () => {
                  updateServiceWorker(true);
                }}
              >
                {i18n.t("general.actions.refresh")}
              </Button>
            </Space>
          </Col>
        </Row>
      }
      closable={false}
      type="warning"
    />
  );
}
