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

import { getGlobalFields } from '@/lib/api/globals'
import { getDesignToolsPage } from '@/lib/api/design-tools'

import ParseContent from '@/components/parsers/ParseContent'
import Accordion from '@/components/shared/Accordion'
import AnimateUnderline from '@/components/shared/AnimateUnderline'
import Container from '@/components/shared/Container'
import ResourceContent from '@/components/shared/ResourceContent'
import BlurImage from '@/components/shared/BlurImage'
import CallToAction from '@/components/sections/CallToAction'
import ProductionSpecs from '@/components/sections/ProductionSpecs'
import ColorCard from '@/components/blocks/ColorCard'
import InlineCta from '@/components/blocks/InlineCta'

// type Props = {
//   page: {
//     title: string
//     content: string
//     featuredImage?: {
//       node: {
//         imageUrl: string
//         alt: string
//         placeholder: string
//       }
//     } | null
//     designToolsPageContent: {
//       fieldGroupName: string
//       designToolSections: Sections[]
//     }
//   }
// }

// type Sections = {
//   fieldGroupName: string
//   title: string
//   imageGridSection: {
//     sectionTitle: string
//     descriptionText: string
//     logos: any
//   }
//   productionSpecsSection: {
//     specTitle: string
//     specDescription: string
//   }
// }

export default function DesignTools({ page }: InferGetStaticPropsType<typeof getStaticProps>) {
  const [isContentExpanded, setIsContentExpanded] = useState(false)
  const contentRef = 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,
    content,
    featuredImage,
    designToolsPageContent: { designToolSections },
    customResourcesSection: {
      resourcesSection: { sectionTitle, sectionDescription, resources },
    },
    customCtaSection,
  } = page

  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="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]">{title}</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 className="">
            <div className="lg:pt-[80px] md:pt-[50px] sm:pt-[30px] pt-[20px] pb-[100px] md:w-4/5 [&_h2]:mb-[30px]">
              <ParseContent content={content} />
            </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>

      <section className="bg-white pb-[150px]">
        <Accordion initial="" containerClasses="container">
          {designToolSections.map((section: any) => (
            <Accordion.Item key={section.title.replace(/[^A-Z0-9]+/gi, '_')}>
              <Accordion.Collapsed id={section.title.replace(/[^A-Z0-9]+/gi, '_')}>{section.title}</Accordion.Collapsed>
              <Accordion.Expanded>
                <div>
                  {/*Product Styles Section*/}
                  <section className="py-24 text-white bg-black">
                    <Container>
                      <AnimateUnderline className="inline-block">
                        {section.imageGridSection.sectionTitle}
                      </AnimateUnderline>
                      <p className="pt-8 text-section-intro">{section.imageGridSection.descriptionText}</p>
                      <div className="grid sm:grid-cols-3 gap-y-12 sm:gap-y-36 pt-16 sm:pt-24">
                        {section.imageGridSection.logos.map((item: any, index: any) => (
                          <div
                            key={index}
                            className="flex flex-col items-center border-t sm:border-t-0 sm:border-l border-gray-dark sm:[&:nth-child(3n)]:border-r"
                          >
                            <div className="relative aspect-4/3 w-full">
                              <Image
                                src={item.logoImage.imageUrl}
                                alt={item.logoImage.alt}
                                fill
                                className="object-contain"
                              />
                            </div>
                            <p className="text-h12">{item.logoName}</p>
                          </div>
                        ))}
                      </div>
                    </Container>
                  </section>
                  {/*Specifications*/}
                  {!!section.productionSpecsSection && (
                    <Container>
                      <div className="my-[100px]">
                        <ProductionSpecs specs={section.productionSpecsSection} heading="Specifications" />
                      </div>
                    </Container>
                  )}
                  {/* First ColorGrid Sections */}
                  {!!(section.colorGridSection.colorChartTitle && section.colorGridSection.colorChartTitle) && (
                    <Container>
                      <div className="my-[100px]">
                        <AnimateUnderline as="h2" className="inline-block text-h6 mb-[40px]">
                          {section.colorGridSection.colorChartTitle}
                        </AnimateUnderline>
                        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-16 sm:gap-x-12 sm:gap-y-24">
                          {section.colorGridSection.colorChart?.map((chart: any) => (
                            <div key={chart.fieldGroupName} className="flex">
                              <ColorCard image={chart.colorImage} title={chart.colorName} />
                            </div>
                          ))}
                        </div>
                      </div>
                    </Container>
                  )}
                  {/* Second ColorGrid Sections */}
                  {!!(section.secondColorGridSection.colorChartTitle && section.secondColorGridSection.colorChart) && (
                    <Container>
                      <div className="my-[100px]">
                        <AnimateUnderline as="h2" className="inline-block text-h6 mb-[40px]">
                          {section.secondColorGridSection.colorChartTitle}
                        </AnimateUnderline>
                        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-16 sm:gap-x-12 sm:gap-y-24">
                          {section.secondColorGridSection.colorChart?.map((chart: any) => (
                            <div key={chart.fieldGroupName} className="flex">
                              <ColorCard image={chart.colorImage} title={chart.colorName} />
                            </div>
                          ))}
                        </div>
                      </div>
                    </Container>
                  )}
                  {/* Inline CTA Section */}
                  <Container>
                    <div className="mb-[150px]">
                      <InlineCta
                        heading={section.downloadPdfBox.downloadLinkText}
                        button={section.downloadPdfBox.downloadLink}
                        accentColor="white"
                      />
                    </div>
                  </Container>
                  <Container>
                    <div className="border-b-4"></div>
                  </Container>
                </div>
              </Accordion.Expanded>
            </Accordion.Item>
          ))}
        </Accordion>
      </section>
      {customCtaSection?.enableCta && (
        <CallToAction heading={customCtaSection?.ctaText} link={customCtaSection?.ctaLink} linkColor="white" />
      )}
      <section className="bg-white py-[100px]">
        <Container>
          <ResourceContent sectionTitle={sectionTitle} sectionDescription={sectionDescription} resources={resources} />
        </Container>
      </section>
    </>
  )
}

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

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