import React, { FC, ReactType, ReactNode, useState, useEffect } from 'react';
import LogoRawSVG from '../../assets/icons/logo-raw.svg';
import DefaultLink, { LinkProps } from '../../blocks/Link';
import css from './index.module.css';
import classnames from 'classnames';
import { MilaGridColumn } from '../../index';
import GridContainer from '../../grid/GridContainer';
import { useSpring, animated } from 'react-spring';
import usePrevious from '../../hooks/usePrevious';
import { throttle } from 'lodash';
export interface HeaderProps {
  variant?: string;
  claim?: string;
  Navigation: ReactType;
  Link?: ReactType;
  LinkProps?: LinkProps;
  children?: ReactNode;
}

const getScrollPosition = (): { x: number; y: number } => {
  const target = document.body;
  const position = target.getBoundingClientRect();

  return { x: position.left, y: position.top };
};
const Header: FC<HeaderProps> = ({
  claim,
  Link = DefaultLink,
  LinkProps,
  Navigation,
  variant,
}) => {
  const [sticky, setSticky] = useState(false);
  const [minScroll, setMinScroll] = useState(false);
  const prevScroll = usePrevious(minScroll);
  const [clientHeight, setClientHeight] = useState(0);

  const [currPos, setCurrPos] = useState(null);
  const prevPos = usePrevious(currPos);

  const [isMobileNavOpen, setIsMobileNavOpen] = useState(false);
  const contentProps = useSpring({
    transform: sticky || !minScroll ? 'translateY(0%)' : 'translateY(-110%)',
    position: minScroll ? 'fixed' : 'absolute',
    config: { duration: !prevScroll ? 0 : 300 },
  });

  const handleScroll = (e): void => {
    const currentHeight = e.target.body.clientHeight;
    setClientHeight(currentHeight);
    if (!prevPos || clientHeight === currentHeight) {
      const pos = getScrollPosition();
      setCurrPos(pos);
      // @ts-ignore
      const isShow = pos.y > (prevPos ? prevPos.y : 0) && Math.abs(pos.y) > 400;
      setMinScroll(Math.abs(pos.y) > 400);
      if (isShow !== sticky) {
        setSticky(isShow);
      }
    }
    setClientHeight(currentHeight);
  };

  useEffect(() => {
    const throttledCount = throttle(handleScroll, 300);
    window.addEventListener('scroll', throttledCount);
    return (): void => window.removeEventListener('scroll', throttledCount);
  });
  return (
    <animated.div
      style={contentProps}
      className={classnames(css.header__fullWidth, {
        [css.header__sticky]: sticky || minScroll,
        [css.header__package]: variant === 'Package',
      })}
    >
      <GridContainer>
        <div
          className={classnames('mila-void', css.header, {
            [css.headerOpen]: isMobileNavOpen,
          })}
        >
          <MilaGridColumn columns={['sm-8', 'xl-2', 'xxl-3']}>
            <div className={css.header__logoWrapper}>
              <Link
                {...LinkProps}
                aria-label="Back to home"
                className={css.header__logoLink}
              >
                {claim ? (
                  <>
                    <LogoRawSVG className={css.header__logo} />
                    <div
                      className={css.header__logoClaim}
                      dangerouslySetInnerHTML={{ __html: claim }}
                    />
                  </>
                ) : (
                  <LogoRawSVG className={css.header__logo} />
                )}
              </Link>
            </div>
          </MilaGridColumn>
          {Navigation && (
            <Navigation
              isStickyHeader={minScroll}
              setMobileNavOpen={(open): void => {
                document.body.style.overflow = open ? 'hidden' : '';
                setIsMobileNavOpen(open);
              }}
            />
          )}
        </div>
      </GridContainer>
    </animated.div>
  );
};

export default Header;
