import * as React from "react";

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

const NOTIF_DURATION = 4500;

export const ONLINE_MSG = "You are back online";

export const OFFLINE_MSG = "No internet connection";

const EXTRA_OFFLINE_MSG = "Please check your connection";
const EXTRA_ONLINE_MSG = "Feel free to continue where you left off";

const styles: Record<any, React.CSSProperties> = {
  body: {
    position: "absolute",
    bottom: 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",
    paddingBottom: 15,
  },
  title: {
    fontSize: 28,
    margin: 0,
    padding: 0,
  },
  subtitle: {
    fontSize: 20,
    margin: 0,
    padding: 0,
  },
};

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

  const [open, setOpen] = React.useState<boolean | null>(null);

  const timeout = React.useRef<NodeJS.Timeout>();
  const wentOnline = !previousOnline && props.online;

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

  const closeNotification = () => {
    clearTimeout(timeout.current as NodeJS.Timeout);

    timeout.current = setTimeout(() => {
      setOpen(false);
    }, NOTIF_DURATION);
  };

  const openNotification = () => {
    if (!open && !hidden) {
      setOpen(true);
    }
  };

  const handleNotificationChange = () => {
    if (open !== null) {
      openNotification();
    }

    closeNotification();
  };

  React.useEffect(() => {
    handleNotificationChange();
  }, [hidden, online]);

  const showOnlineMsg = wentOnline || online;
  const MSG = showOnlineMsg ? ONLINE_MSG : OFFLINE_MSG;
  const EXTRA_MSG = showOnlineMsg ? EXTRA_ONLINE_MSG : EXTRA_OFFLINE_MSG;

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

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