import { useState, useEffect, useRef } from 'react'
/*import { gql } from 'graphql-request'*/
import { useRouter } from 'next/router'
import Image from 'next/image'
import cx from 'classnames'
import { useInView, useIsomorphicLayoutEffect } from 'framer-motion'

/*import fetchQueryAPI from '@/lib/api/fetchQuery'*/
import { useLoadingContext } from '@/lib/LoadingContext'

import loadingSVG from '@/public/icons/loading.svg'
import BlurImage from '@/components/shared/BlurImage'
import Container from '@/components/shared/Container'
import CallToAction from '@/components/sections/CallToAction'
import Newsletter from '@/components/forms/Newsletter'
import SearchResultBlock from '@/components/blocks/SearchResultBlock'

type Props = {
  page: {
    title: string
    featuredImage?: {
      node: {
        imageUrl: string
        alt: string
        placeholder: string
      }
    } | null
  }
}

type MapQuery = {
  query: ApiData
  searchPageQuery: string
}

type ApiData =
  | [
      {
        _source: {
          postType: string
          post_type: string
          id: string
          title: string
          urlPath: string
          content: string
          excerpt: string
          slug: string
          caseStudyProjectContent: {
            hero_section: {
              main_description: string
            }
          }
        }
      }
    ]
  | undefined

function MapResults({ query, searchPageQuery }: MapQuery) {
  const pageList = query?.map(test => {
    if (test?._source?.postType === 'page') {
      return (
        <SearchResultBlock
          key={test?._source?.id}
          title={test?._source?.title}
          url={test?._source?.urlPath}
          content={removeTagsFromContent(test?._source?.excerpt)}
        />
      )
    } else if (test?._source?.postType === 'post') {
      return (
        <SearchResultBlock
          key={test?._source?.id}
          title={test?._source?.title}
          url={test?._source?.urlPath}
          content={
            test?._source?.excerpt
              ? removeTagsFromContent(test?._source?.excerpt)
              : removeTagsFromContent(test?._source?.content)
          }
        />
      )
    } else if (test?._source?.post_type === 'case_study') {
      return (
        <SearchResultBlock
          key={test?._source?.id}
          title={test?._source?.title}
          url={`case-study/${test?._source?.slug}`}
          content={
            test?._source?.caseStudyProjectContent?.hero_section?.main_description
              ? removeTagsFromContent(test?._source?.caseStudyProjectContent?.hero_section?.main_description)
              : removeTagsFromContent(test?._source?.excerpt)
          }
        />
      )
    } else if (test?._source?.post_type === 'project') {
      return (
        <SearchResultBlock
          key={test?._source?.id}
          title={test?._source?.title}
          url={`${test?._source?.post_type}/${test?._source?.slug}`}
          content={test?._source?.caseStudyProjectContent?.hero_section?.main_description}
        />
      )
    } else {
      return null
    }
  })
  if (pageList?.length === 0 && searchPageQuery !== '') {
    return (
      <div>
        <div className="text-h5 pt-8 pb-2">No Results Found</div>
        <div className="text-h6 font-light">
          The page you requested could not be found. Try refining your search, or use the navigation above to help you
          find what you&apos;re looking for.
        </div>
      </div>
    )
  }
  return <>{pageList}</>
}

function removeTagsFromContent(str: string) {
  if (str === null || str === '' || str === undefined) return ''
  else str = str?.toString()
  const cleanedStr = str?.replace(/(<([^>]+)>)/gi, '')

  return cleanedStr.slice(0, 300)
}

function Search({ page }: Props) {
  const router = useRouter()
  const routerQuery = router?.query?.q as string
  const { isLoading, loadingStart, loadingDone } = useLoadingContext()
  const searchQueryURL = process.browser ? routerQuery : ''
  const [searchPageQuery, setSearchPageQuery] = useState<string>(searchQueryURL ? searchQueryURL : '')
  const [apiQuery, setApiQuery] = useState(searchPageQuery)
  const [query, setQuery] = useState<ApiData>()
  const [timer, setTimer] = useState(0)

  useEffect(() => {
    const cleanedQuery = apiQuery?.replace(/[^a-zA-Z0-9 ]/g, '')
    if (cleanedQuery !== '') {
/*      const fetchData = async () => {
        loadingStart!()
        const data = await fetchQueryAPI(
          gql`{
            search(query: "${cleanedQuery}", limit: 10) {
              result
            }
          }`
        )
        const { hits } = data.search.result.hits
        loadingDone!()
        setQuery(hits)
      }
      fetchData()*/
    }
  }, [setQuery, apiQuery])

  const { featuredImage } = page

  const updateQuery = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSearchPageQuery(() => event.target.value)
    clearTimeout(timer)
  }

  useEffect(() => {
    setSearchPageQuery(routerQuery)
  }, [router.query.q])

  useEffect(() => {
    const newTimer = window.setTimeout(() => {
      setApiQuery(() => searchPageQuery)
    }, 500)
    setTimer(newTimer)
  }, [searchPageQuery])

  //if the search form on the search result page needs a submit button that works
  const submitHandler = (event: React.SyntheticEvent) => {
    event.preventDefault()
    event.stopPropagation()
  }

  const [introHeight, setIntroHeight] = useState(0)
  const [isContentExpanded, setIsContentExpanded] = useState(false)
  const contentRef = useRef<HTMLDivElement>(null)
  const introRef = useRef<HTMLDivElement>(null)
  const isContentInView = useInView(contentRef, {
    margin: '0px 0px -33% 0px',
  })

  useEffect(() => {
    const isPastContent = contentRef?.current && window.pageYOffset > contentRef?.current?.getBoundingClientRect().top
    setIsContentExpanded(Boolean(isContentInView || isPastContent))
  }, [isContentInView])

  useIsomorphicLayoutEffect(() => {
    setIntroHeight(introRef.current?.clientHeight || 0)
  }, [])

  return (
    <>
      <div className="fixed inset-0 h-vh -z-1 bg-gray-light">
        {featuredImage && (
          <BlurImage
            src={featuredImage.node.imageUrl}
            alt={featuredImage.node.alt}
            placeholderSrc={featuredImage.node.placeholder}
            fill
            className="object-cover"
            sizes="100vw"
            priority
          />
        )}
      </div>

      <Container>
        <div className="px-1 flex items-end min-h-[calc(100vh_-_320px)]">
          <h1 className="text-h1 text-white lg:mb-[100px] md:mb-[80px] sm:mb-[50px] mb-[30px]">Search</h1>
        </div>
      </Container>

      <section
        id="intro"
        ref={contentRef}
        className="relative overflow-hidden transition-colors"
        style={{ marginTop: `-${introHeight}px` }}
      >
        <Container>
          <div className="grid grid-cols-12 gap-x-6">
            <article className="md:col-span-8 sm:col-span-12 col-span-12 relative px-1 lg:pt-[60px] md:pt-[50px] sm:pt-[30px] pt-[20px] bg-white before:content-[''] md:before:w-[50px] sm:before:w-[30px] md:before:left-[-50px] sm:before:left-[-30px] before:block before:absolute before:bg-white before:inset-y-0 after:content-[''] md:after:w-[50px] sm:after:w-[30px] md:after:right-[-50px] sm:after:right-[-30px] after:block after:absolute after:bg-white after:inset-y-0">
              <div className="flex sm:flex-row flex-col mb-[50px]">
                <div className="text-h3">{apiQuery ? 'Results for' : 'Search for'}</div>
              </div>
              <form action="" onSubmit={event => event.preventDefault()} className="relative">
                <input
                  onSubmit={submitHandler}
                  value={searchPageQuery}
                  onChange={updateQuery}
                  autoFocus
                  type="text"
                  style={{ boxShadow: 'none' }}
                  className="text-h4 font-semibold w-full border-t-0 border-l-0 border-r-0 border-b-2 bg-transparent focus:border-b-black"
                />
                <button
                  className={`absolute md:-inset-y-[22px] -inset-y-[15px] right-0 navbar-btn search-btn  w-[30px] h-[30px] md:w-[46px] md:h-[46px] md:my-[31px] my-[40px] flex items-center justify-center group`}
                >
                  <div className="sr-only">Search</div>
                  <span
                    className="
                      inline-block
                      group-hover:bg-black
                      group-hover:border-white
                      group-hover:after:bg-white
                      bg-transparent
                      rounded-[30px]
                      relative
                      w-[20px]
                      h-[20px]
                      border-[3px]
                      border-black
                      after:bg-black
                      after:h-[3px]
                      after:w-6/12
                      after:absolute
                      after:bottom-[-20%]
                      after:right-[-30%]
                      after:rotate-[45deg]
                      after:origin-bottom
                      icon-magnifying-glass
                      "
                  ></span>
                </button>
              </form>
              <div className="pb-8 divide-y-4">
                {isLoading ? (
                  <div className="text-h5 pt-8 pb-2 flex justify-center">
                    <Image src={loadingSVG} alt="Loading SVG" />
                  </div>
                ) : (
                  <MapResults query={query} searchPageQuery={searchPageQuery} />
                )}
              </div>
              <div className="page-content-intro [&_h1]:text-h2 [&_h1]:mb-5 [&_h1]:mb-10 [&_p]:text-section-intro" />

              <div
                className={cx(
                  'absolute inset-y-0 left-1/2 w-vw -translate-x-1/2 bg-white transition-all duration-300 -z-1 ease-in-out-cubic',
                  isContentExpanded ? 'sm:w-vw' : 'sm:w-full'
                )}
              />
            </article>
            <aside className="md:col-start-10 md:col-span-3 col-span-12 relative bg-white before:content-[''] md:before:w-[50px] sm:before:w-[30px] md:before:left-[-50px] sm:before:left-[-30px] before:block before:absolute before:bg-white before:inset-y-0 after:content-[''] md:after:w-[50px] sm:after:w-[30px] md:after:right-[-50px] sm:after:right-[-30px] after:block after:absolute after:bg-white after:inset-y-0">
              <div className="grid grid-cols-12 bg-black">
                <div className="col-span-12">
                  <div className="px-[24px] pt-[30px] pb-[30px]">
                    <div className="inline-block text-h5 font-medium text-accent-yellow ">
                      Subscribe today to stay on top of industry news, trends, and events.
                    </div>
                  </div>
                </div>
                <div className="col-span-12 px-[30px] pb-[30px]">
                  <Newsletter />
                </div>
                <div className="lg:col-span-12 md:col-span-8 sm:col-span-7 col-span-12">
                  <div className="border-l sm:pl-[30px] pl-[20px] lg:ml-0 sm:ml-[40px]">
                    <div
                      className="
                        lg:block
                        sm:flex
                        sm:flex-wrap
                        block
                        sm:[&>p:first-child]:flex-auto
                        sm:[&>p:first-child]:w-full
                        sm:[&>p:first-child]:text-[22px]
                        sm:[&>p:first-child]:leading-[26px]
                        sm:[&_p:nth-child(2)]:pr-[30px]
                        sm:[&_p]:mb-[40px]
                        md:[&_p]:flex-1
                      "
                    />
                  </div>
                </div>
              </div>

              <div
                className={cx(
                  'absolute inset-y-0 left-1/2 w-vw -translate-x-1/2 bg-white transition-all duration-300 -z-1 ease-in-out-cubic',
                  isContentExpanded ? 'sm:w-vw' : 'sm:w-full'
                )}
              />
            </aside>
          </div>
        </Container>
      </section>
      {/* Custom CTA Section */}
      <CallToAction
        heading="Have a project you want to get started on?"
        link={{ url: '/contact', title: "Let's Talk" }}
        linkColor="blue"
        accentColor="white"
      />
    </>
  )
}

export default Search
