import { useEffect, useRef, useState } from 'react'
import type { GetStaticProps, InferGetStaticPropsType } from 'next'
import cx from 'classnames'
import { useInView, useIsomorphicLayoutEffect } from 'framer-motion'

import { getGlobalFields } from '@/lib/api/globals'
import { getSustainablityPage } from '@/lib/api/sustainablity'

import AnimateUnderline from '@/components/shared/AnimateUnderline'
import BlurImage from '@/components/shared/BlurImage'
import Container from '@/components/shared/Container'
import Icon from '@/components/shared/Icon'
import AsymmetricalPhoto from '@/components/sections/AsymmetricalPhoto'
import CallToAction from '@/components/sections/CallToAction'
import FullWidthPhoto from '@/components/sections/FullWidthPhoto'
import Callout from '@/components/blocks/Callout'
import Award from '@/components/blocks/Award'

export default function Sustainability({ page }: InferGetStaticPropsType<typeof getStaticProps>) {
  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])

  const {
    title,
    featuredImage,
    sustainabilityPageContent: {
      heroSection,
      threeRsSection,
      theRsAcrossPackagingSection,
      theFourthRSection,
      awardsSection,
      awardsFullImageSection,
      energyConservationSection,
    },
    customCtaSection,
  } = page

  const { heroTitle, mainDescription, subHeroTitle, subHeroDescription } = heroSection

  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>

      <div className="h-vh-header" />

      <section
        id="intro"
        ref={contentRef}
        className="relative overflow-hidden transition-colors"
        style={{ marginTop: `-${introHeight}px` }}
      >
        <div className="relative max-w-[1320px] sm:mx-[35px] md:mx-[45px] lg:mx-auto bg-white">
          <Container>
            <div ref={introRef}>
              <div className="flex justify-between items-center pt-6 pb-7">
                <AnimateUnderline as="h2" className="text-xl relative">
                  {title}
                </AnimateUnderline>
                <a href="#intro" aria-hidden="true">
                  <Icon name="arrow-down" className="w-8 text-black" />
                </a>
              </div>
            </div>
            <div className="grid gap-y-12 sm:gap-y-20 lg:gap-y-24 pt-6 pb-12 sm:pb-20 lg:pb-24 bg-white">
              <h1 className="text-h1">{heroTitle}</h1>
              <p className="text-page-intro">{mainDescription}</p>
              <div>
                <AnimateUnderline className="inline-block">{subHeroTitle}</AnimateUnderline>
                <div className="pt-4 text-section-intro">{subHeroDescription}</div>
              </div>
              {/* Three R's */}
              {threeRsSection.bodySection.map((section: any, index: number) => (
                <Callout key={index} heading={section.title} content={section.bodyCopy} />
              ))}
              {/* R's Across */}
              <div>
                <AnimateUnderline className="inline-block">{theRsAcrossPackagingSection.sectionTitle}</AnimateUnderline>
                {theRsAcrossPackagingSection.enableFullImage && (
                  <figure className="pt-8">
                    <FullWidthPhoto {...theRsAcrossPackagingSection} aspect="16/9" />
                    <figcaption className="pt-2 text-caption">{theRsAcrossPackagingSection.imageCaption}</figcaption>
                  </figure>
                )}
              </div>
              {/* The Fouth R's */}
              <div>
                <AnimateUnderline className="inline-block pb-8">{theFourthRSection.sectionTitle}</AnimateUnderline>
                <Callout heading={theFourthRSection.title} content={theFourthRSection.description} />
              </div>
              <AsymmetricalPhoto
                removePadding={theFourthRSection.removePadding}
                largeImagePlacement={theFourthRSection.photoSection.largeImagePlacement}
                photoGrid={theFourthRSection.photoSection.photoGrid}
              />
              {/* Award */}
              <div className="grid gap-y-12 sm:gap-y-20">
                {awardsSection.awards.map((award: any, index: number) => (
                  <Award
                    key={index}
                    image={award.awardImage}
                    title={award.awardTitle}
                    blurb={award.awardBlurb}
                    description={award.awardDescription}
                    link={award.awardLink}
                  />
                ))}
              </div>
              {awardsFullImageSection.enableFullImage && <FullWidthPhoto {...awardsFullImageSection} aspect="16/9" />}
              {/* Energy Conversation */}
              <div>
                <AnimateUnderline className="inline-block pb-8">
                  {energyConservationSection.sectionTitle}
                </AnimateUnderline>
                <Callout heading={energyConservationSection.title} content={energyConservationSection.description} />
              </div>
            </div>
          </Container>
          <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'
            )}
          />
        </div>

        {/* CTA */}
        <div className="bg-white">
          {customCtaSection?.enableCta && (
            <CallToAction heading={customCtaSection?.ctaText} link={customCtaSection?.ctaLink} />
          )}
        </div>
      </section>
    </>
  )
}

export const getStaticProps: GetStaticProps = async ({ preview = false }) => {
  const { globals } = await getGlobalFields(preview)
  const { page } = await getSustainablityPage()

  return {
    props: {
      globals,
      page,
    },
    revalidate: 10, // In seconds
  }
}
