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

import ParseFlexibleContent from '@/components/parsers/ParseFlexibleContent'
import AnimateUnderline from '@/components/shared/AnimateUnderline'
import BlurImage from '@/components/shared/BlurImage'
import Container from '@/components/shared/Container'
import Divider from '@/components/shared/Divider'
import Icon from '@/components/shared/Icon'
import SocialShare from '@/components/shared/SocialShare'
import CallToAction from '@/components/sections/CallToAction'
import NextPage from '@/components/sections/NextPage'
import ProductionSpecs from '@/components/sections/ProductionSpecs'
import Callout from '@/components/blocks/Callout'

type Props = {
  postType: 'case_study' | 'project'
  page: {
    title: string
    featuredImage?: {
      node: {
        imageUrl: string
        alt: string
        placeholder: string
      }
    } | null
    caseStudyProjectContent: {
      heroSection: {
        customerName: string
        accentColor: string
        mainDescription: string
        goalText?: string
        challengeText?: string
      }
      bodySection: any
      productionSpecsSection: any
      requestASampleButton: boolean
      customCtaSection: any
    }
  }
  nextPage?: any
}

export default function Single({ postType, page, nextPage }: Props) {
  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,
    caseStudyProjectContent: { heroSection, bodySection, productionSpecsSection, customCtaSection },
  } = page

  const { customerName, accentColor, mainDescription, goalText, challengeText } = heroSection

  const label = (() => {
    switch (postType) {
      case 'case_study':
        return 'Case Study'
      case 'project':
        return 'Project'
    }
  })()

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

  return (
    <>
      <div className="fixed inset-0 h-vh -z-1 bg-gray-light">
        {featuredImage && (
          <div className="absolute inset-0">
            <BlurImage
              src={featuredImage.node.imageUrl}
              alt={featuredImage.node.alt}
              placeholderSrc={featuredImage.node.placeholder}
              fill
              className="object-cover"
              sizes="100vw"
              priority
              quality={95}
            />
          </div>
        )}
      </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">
                  {label}
                </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">
              <div>
                <h1 className="text-h1">{customerName}</h1>
                <p className="pt-4 text-page-intro">{mainDescription}</p>
              </div>
              {/* Social share  */}
              <SocialShare
                title={customerName}
                excerpt={mainDescription}
                image={featuredImage?.node?.imageUrl}
                accentColor={accentColor}
              />
              {/* Goal/challenge */}
              {(goalText || challengeText) && (
                <div className="grid xs:grid-cols-1 md:grid-cols-2 gap-12 sm:gap-20 lg:gap-16">
                  {goalText && (
                    <div>
                      <Callout heading="Goal" content={goalText} />
                    </div>
                  )}
                  {challengeText && (
                    <div>
                      <Callout heading="Challenge" content={challengeText} />
                    </div>
                  )}
                </div>
              )}
              {/* Flexible content */}
              <ParseFlexibleContent sections={bodySection} accentColor={accentColor} postType={postType} />
              {/* Production specs */}
              <ProductionSpecs specs={productionSpecsSection} heading="Production Specs" />
            </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>
      </section>

      {/* CTA */}
      <div className="bg-white">
        <Container>
          <Divider />
        </Container>
        <CallToAction heading={customCtaSection?.ctaText} link={customCtaSection?.ctaLink} linkColor={accentColor} />
      </div>

      {nextPage && <NextPage page={nextPage} />}
    </>
  )
}
