import { AlertOutlined } from "@ant-design/icons";
import { Alert, Button, Col, Row, Space } from "antd";
import i18n from "i18next";
import React, { useEffect } 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 function UpdateAlert({ updateAvailable }) {
  const { t } = useTranslation();
  const {
    offlineReady: [offlineReady],
    needRefresh: [needRefresh],
    updateServiceWorker
  } = useRegisterSW({
    onRegistered(r) {
      console.log("SW Registered:", r);
      if (r) {
        setInterval(
          () => {
            r.update();
          },
          30 * 60 * 1000
        );
      }
    },
    onRegisterError(error) {
      console.error("SW registration error", error);
    }
  });

  useEffect(() => {
    if (import.meta.env.DEV) {
      console.log(`SW Status => Refresh? ${needRefresh} - offlineReady? ${offlineReady}`);
    }
  }, [needRefresh, 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={() => window.open("https://imex-online.noticeable.news/", "_blank")}>
                {i18n.t("general.actions.viewreleasenotes")}
              </Button>
              <Button type="primary" onClick={() => updateServiceWorker(true)}>
                {i18n.t("general.actions.refresh")}
              </Button>
            </Space>
          </Col>
        </Row>
      }
      closable={false}
      type="warning"
    />
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(UpdateAlert);
