import * as React from "react";

type Props = {
  children?: React.ReactNode;
  online?: boolean;
  previousOnline?: boolean;
  dismiss: () => void;
};

const DURATION_TO_HIDE_AFTER_BACK_TO_ONLINE = 4500; // ms

const ONLINE_TITLE = "You are back online";
const ONLINE_SUBTITLE = "Feel free to continue where you left off";

const OFFLINE_TITLE = "No internet connection";
const OFFLINE_SUBTITLE = "Please check your connection";

const styles: Record<any, React.CSSProperties> = {
  body: {
    position: "absolute",
    top: 0,
    width: 1920,
    height: 200,
    background:
      "linear-gradient(180deg, rgba(17,17,17,0.9) 0%, rgba(17,17,17,1) 49%, rgba(0,0,0,0.85) 100%)",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    flexDirection: "column",
    color: "#fff",
    paddingTop: 15,
  },
  title: {
    fontSize: 28,
    margin: 0,
    padding: 0,
  },
  subtitle: {
    fontSize: 20,
    margin: 0,
    padding: 0,
  },
};

let timer: NodeJS.Timeout;

export const NotificationView = (props: Props) => {
  const { children, dismiss, previousOnline = true, online } = props;

  const [shown, setShown] = React.useState<boolean>(false);

  const onClose = () => {
    setShown(false);
    dismiss();
  };

  React.useEffect(() => {
    if (previousOnline && online) {
      return;
    }

    if (!previousOnline && !online) {
      return;
    }

    if (previousOnline && !online) {
      // went to offline
      clearTimeout(timer);
      setShown(true);
    }

    if (!previousOnline && online) {
      // back to online
      setShown(true);

      timer = setTimeout(() => {
        setShown(false);
      }, DURATION_TO_HIDE_AFTER_BACK_TO_ONLINE);
    }
  }, [online, previousOnline]);

  const title = online ? ONLINE_TITLE : OFFLINE_TITLE;
  const subtitle = online ? ONLINE_SUBTITLE : OFFLINE_SUBTITLE;

  return (
    <div onClick={onClose}>
      {children}
      {shown && (
        <div style={styles.body}>
          <div style={styles.title}>
            <h2>{title}</h2>
          </div>

          <h4 style={styles.subtitle}>{subtitle}</h4>
        </div>
      )}
    </div>
  );
};
