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

import type { TabItem as TabItemProps } from '@/components/shared/Tabs'
import ParseFlexibleContent from '@/components/parsers/ParseFlexibleContent'
import CallToAction from '@/components/sections/CallToAction'
import ProductionSpecs from '@/components/sections/ProductionSpecs'
import AnimateUnderline from '@/components/shared/AnimateUnderline'
import BlurImage from '@/components/shared/BlurImage'
import Container from '@/components/shared/Container'
import ResourceContent from '@/components/shared/ResourceContent'
import Tabs from '@/components/shared/Tabs'
import Callout from '@/components/blocks/Callout'
import InlineCta from '@/components/blocks/InlineCta'

type Props = {
  page: {
    title: string
    content: string
    featuredImage?: {
      node: {
        imageUrl: string
        alt: string
        placeholder: string
      }
    } | null
    materialsPageContent: {
      fieldGroupName: string
      heroSection: {
        heroTitle: string
        heroText: string
      }
      materialsTitle: string
      materialsDescription: string
      materialsSections: Sections[]
    }
    customResourcesSection: {
      resourcesSection: {
        sectionTitle: string
        sectionDescription: string
        resources: any
      }
    }
    customCtaSection: any
  }
  menu: {
    name: string
    menuItems: {
      nodes: TabItemProps[]
    }
  }
}

type Sections = {
  title: string
  description: string
  enableDescriptionButton: boolean
  buttonLink: {
    title: string
    url: string
  }
  specificationsTitle: string
  productionSpecsSection: {
    specTitle: string
    specDescription: string
  }
  bodySection: {
    fieldGroupName: string
  }
  downloadPdfSection: {
    downloadPdfText: string
    downloadPdfLink: any
  }
}

export default function MaterialsAndFinishes({ page, menu }: Props) {
  const {
    // title,
    // content,
    featuredImage,
    materialsPageContent,
    customResourcesSection: {
      resourcesSection: { sectionTitle, sectionDescription, resources },
    },
    customCtaSection,
  } = page
  const {
    // fieldGroupName: coverMaterialsGroupName,
    heroSection,
    materialsTitle,
    materialsDescription,
    materialsSections,
  } = materialsPageContent
  const {
    // name: menuName,
    menuItems: { nodes: materialMenuItems },
  } = menu

  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])

  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 className="pb-8 sm:pb-16">
        <div className="flex items-end min-h-[calc(100vh_-_320px)]">
          <h1 className="text-h1 text-white">{heroSection.heroTitle}</h1>
        </div>
      </Container>

      <section id="intro" ref={contentRef} className="relative overflow-hidden transition-colors">
        <div className="relative max-w-[1320px] sm:mx-[35px] md:mx-[45px] lg:mx-auto bg-white">
          <Container>
            <div className="grid gap-y-12 sm:gap-y-20 lg:gap-y-24 py-12 sm:py-20 lg:py-24 bg-white">
              <div ref={introRef}>
                <h2 className="text-page-intro">{heroSection.heroText}</h2>
              </div>
              <Tabs
                items={materialMenuItems.map(item => ({ ...item, path: `${item.path}#intro` }))}
                accentColor="teal"
              />
              <div>
                <AnimateUnderline as="h2" className="text-xl relative inline-block">
                  {materialsTitle}
                </AnimateUnderline>
                <div className="pt-4 text-section-intro" dangerouslySetInnerHTML={{ __html: materialsDescription }} />
              </div>
              {/* Repeater Materials Sections */}
              {materialsSections.map((section: any) => (
                <>
                  <div>
                    <div className="pb-12">
                      <Callout
                        heading={section.title}
                        content={section.description}
                        button={section.enableDescriptionButton ? section.buttonLink : undefined}
                      />
                    </div>
                    <ParseFlexibleContent
                      sections={section.bodySection}
                      sectionOverrides={{
                        FullWidthPhotoLayout: {
                          aspect: '16/9',
                        },
                      }}
                    />
                  </div>
                  {section.productionSpecsSection[0].specTitle && (
                    <ProductionSpecs specs={section.productionSpecsSection} heading={section.specificationsTitle} />
                  )}
                  {section.downloadPdfSection.downloadPdfText && (
                    <InlineCta
                      heading={section.downloadPdfSection.downloadPdfText}
                      button={section.downloadPdfSection.downloadPdfLink}
                      accentColor="white"
                    />
                  )}
                </>
              ))}
            </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>

      {/* Call to action */}
      {customCtaSection?.enableCta && (
        <CallToAction heading={customCtaSection?.ctaText} link={customCtaSection?.ctaLink} linkColor="white" />
      )}

      <div className="bg-white py-[100px]">
        <Container>
          <ResourceContent sectionTitle={sectionTitle} sectionDescription={sectionDescription} resources={resources} />
        </Container>
      </div>
    </>
  )
}
