import { Link } from "gatsby";
import { useSiteMetadata } from "../../hooks/use-site-metadata";
import * as classNames from "classnames";
import * as styles from "./styles.module.scss";
import CustomSearchBox from "../CustomSearchBox";
import React, { useRef, useEffect, useState } from "react";
import Text, { Element, Size } from "../Text";

interface IProps {
  query?: string;
  setQuery: (string) => null;
}

declare global {
  interface Window {
    IntersectionObserver: any;
  }
}

const Navbar = ({ query, setQuery }: IProps) => {
  const { siteMetadata } = useSiteMetadata();
  const observerRef = useRef(null);
  const [hasScrolled, setScrolled] = useState(false);

  const options = {
    root: null,
    rootMargin: "0px",
    threshold: 0
  };

  const checkIfScrolled = entries => {
    setScrolled(!entries[0].isIntersecting);
  };

  useEffect(() => {
    if (!window.IntersectionObserver) {
      return;
    }
    var observer = new IntersectionObserver(checkIfScrolled, options);
    observer.observe(observerRef.current);
    return () => {
      observer.unobserve(observerRef.current);
    };
  });

  return (
    <React.Fragment>
      <nav
        role="navigation"
        className={classNames({
          [styles.nav]: true
        })}
      >
        <div className={styles.inner}>
          <div className={styles.logoWrapper} onClick={() => setQuery("")}>
            <Link
              className={classNames({
                [styles.logo]: true,
                [styles.hasScrolled]: hasScrolled
              })}
              to="/"
            >
              {siteMetadata.title}
              {console.log(siteMetadata)}
            </Link>
          </div>
          <CustomSearchBox
            hasScrolled={hasScrolled}
            query={query}
            setQuery={setQuery}
          />
          <ul className={styles.primary}>
            <li className={styles.primaryItem}>
              <Link
                to="/contatti"
                className={styles.link}
                activeClassName={styles.active}
              >
                <Text element={Element.Span} size={Size.P4}>
                  Contatti
                </Text>
              </Link>
            </li>
          </ul>
        </div>
      </nav>
      <div ref={observerRef} />
    </React.Fragment>
  );
};

export default Navbar;
