import { UserInfo } from 'models/user.types';
import { useState, useEffect, useCallback } from 'react';

const useAlertBar = ({ originExp, type }: Pick<UserInfo, 'originExp' | 'type'>): [boolean, string, Function] => {
  const [showAlert, setShowAlert] = useState(false);
  const [maxHeight, setMaxHeight] = useState('calc(100vh - 64px)');

  useEffect(() => {
    if (
      type != 'lifelong' &&
      originExp !== undefined &&
      +new Date(originExp) < Date.now() + 30 * 24 * 3600 * 1000 &&
      !document.cookie.includes('hide_alert_bar')
    ) {
      setShowAlert(true);
    }
  }, [originExp, setShowAlert]);

  useEffect(() => {
    setMaxHeight(showAlert ? 'calc(100vh - 44px - 64px)' : 'calc(100vh - 64px)');
  }, [showAlert]);

  const closeAlertBar = useCallback(() => {
    const maxAge = 24 * 3600;
    document.cookie = `hide_alert_bar=true; max-age=${maxAge};`;
    setShowAlert(false);
  }, [setShowAlert]);

  return [showAlert, maxHeight, closeAlertBar];
};

export default useAlertBar;
