import "../../styles/styles.scss"
import { Configure, InstantSearch } from "react-instantsearch-dom"
import { useCollection } from "../../hooks/use-collection"
import { useFavicon } from "../../hooks/use-favicon"
import { useGallery } from "../../hooks/use-gallery"
import * as classNames from "classnames"
import * as styles from "./styles.module.scss"
import algoliasearch from "algoliasearch/lite"
import CustomSearch from "../CustomSearch"
import Footer from "../Footer"
import Navbar from "../Navbar"
import React, { useState } from "react"

export const GalleryContext = React.createContext(null)
export const CollectionContext = React.createContext(null)
export const FaviconContext = React.createContext(null)

const Layout = ({ children }) => {
  const galleryAll = useGallery()
  const collection = useCollection()
  const favicon = useFavicon()
  const [query, setQuery] = useState(``)

  const searchClient = algoliasearch(
    process.env.GATSBY_ALGOLIA_APP_ID,
    process.env.GATSBY_ALGOLIA_SEARCH_KEY
  )

  return (
    <GalleryContext.Provider value={galleryAll}>
      <CollectionContext.Provider value={collection}>
        <FaviconContext.Provider value={favicon}>
          <div className={styles.wrapper}>
            <InstantSearch
              indexName={process.env.GATSBY_ALGOLIA_INDEX_NAME}
              searchClient={searchClient}
              onSearchStateChange={({ query }) => setQuery(query)}
              stalledSearchDelay={500}
              root={{
                Root: "div",
                props: {
                  className: styles.searchWrapper,
                },
              }}
            >
              <Configure
                hitsPerPage={20}
                typoTolerance="min"
                attributesToHighlight={["titoloPretty"]}
                attributesToSnippet={["descrizioneAlgolia:20"]}
                snippetEllipsisText="..."
                queryLanguages={["it"]}
                ignorePlurals={true}
              />
              <Navbar query={query} setQuery={setQuery} />
              <div
                className={classNames({
                  [styles.search]: true,
                  [styles.active]: query,
                })}
              >
                <CustomSearch query={query} galleryAll={galleryAll} />
              </div>
              <div
                className={classNames({
                  [styles.main]: true,
                  [styles.active]: !query,
                })}
              >
                {children}
              </div>
            </InstantSearch>
            <Footer />
          </div>
        </FaviconContext.Provider>
      </CollectionContext.Provider>
    </GalleryContext.Provider>
  )
}

export default Layout
