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

import { GfForm } from '@/lib/api/general-inquiry-form'

import type { TabItem as TabItemProps } from '@/components/shared/Tabs'
import type { repState } from '@/components/sections/FindARep'
import BlurImage from '@/components/shared/BlurImage'
import Container from '@/components/shared/Container'
import Tabs from '@/components/shared/Tabs'
import CallToAction from '@/components/sections/CallToAction'
import FindARep from '@/components/sections/FindARep'
import ContactForm from '@/components/forms/ContactForm'

// type salesRep = {
//   title: string
//   featuredImage?: {
//     node: {
//       imageUrl: string
//       alt: string
//       placeholder: string
//     }
//   } | null
//   salesRepContent: {
//     email: string
//     jobTitle: string
//     phoneNumber: string
//   }
//   productLines: any
// }

type Props = {
  page: {
    title: string
    content?: string
    featuredImage?: {
      node: {
        imageUrl: string
        alt: string
        placeholder: string
      }
    } | null
    contactPageContent: {
      heroTitle: string
      associatedFormId: number
      sideBarContent: {
        address: string
        address2: string
        contactEmail: string
        faxNumber: string
        officeNumber: string
        sidebarText: string
        tollFreeNumber: string
        fieldGroupName: string
      }
    }
    customCtaSection: any
  }
  menu: {
    name: string
    menuItems: {
      nodes: TabItemProps[]
    }
  }
  repStates?: {
    nodes: repState[]
  }
  form?: GfForm
}

export default function ContactPage({ page, menu, repStates, form }: 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,
    content,
    featuredImage,
    contactPageContent: { heroTitle, associatedFormId, sideBarContent },
    customCtaSection,
  } = page
  const {
    address,
    address2,
    contactEmail,
    faxNumber,
    officeNumber,
    sidebarText,
    tollFreeNumber,
    // fieldGroupName
  } = sideBarContent

  const {
    menuItems: { nodes },
  } = menu

  const contactMenuItems = nodes

  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="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]">{heroTitle}</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="lg:col-span-8 col-span-12 relative pt-header 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">
              <Tabs
                items={contactMenuItems.map(item => ({ ...item, path: `${item.path}#intro` }))}
                accentColor="red"
                className="lg:mb-[100px] md:mb-[80px] sm:mb-[70px] mb-[50px]"
              />

              <div
                className="page-content-intro [&_h1]:text-h2 [&_h1]:mb-5 [&_h1]:mb-10 [&_p]:text-section-intro"
                dangerouslySetInnerHTML={{ __html: content || '' }}
              />

              {/* Could be a switch statement cased off of slug */}
              {!!associatedFormId ? (
                <ContactForm formId={associatedFormId} form={form as GfForm} contentRef={contentRef} />
              ) : (
                <FindARep
                  repStates={
                    repStates as {
                      nodes: repState[]
                    }
                  }
                />
              )}
              <div className="lg:pb-20"></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'
                )}
              />
            </article>

            <aside className="lg:col-start-10 lg:col-span-3 col-span-12 relative lg:pt-header pt-[140px] 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 gap-x-6">
                <div className="lg:col-span-12 md:col-span-4 sm:col-span-5 col-span-12">
                  <div className="border-l sm:pl-[30px] pl-[20px] lg:mb-[155px] sm:mb-0 mb-[60px]">
                    <h6 className="inline-block text-h6 border-b-[4px] mb-[35px]">Contact</h6>
                    <div className="text-body mb-[5px]">
                      <span className="text-accent-red">Office:&nbsp;</span>{' '}
                      <a href={`tel:${officeNumber}`}>{officeNumber}</a>
                    </div>
                    <div className="text-body mb-[5px]">
                      <span className="text-accent-red">Toll Free:&nbsp;</span>{' '}
                      <a href={`tel:${tollFreeNumber}`}>{tollFreeNumber}</a>
                    </div>
                    <div className="text-body mb-[5px]">
                      <span className="text-accent-red">Fax:&nbsp;</span> <a href={`tel:${faxNumber}`}>{faxNumber}</a>
                    </div>
                    <div className="text-body mb-[5px]">
                      <a className="border-b pb-[3px] hover:border-0" href={`mailTo:${contactEmail}`}>
                        {contactEmail}
                      </a>
                    </div>
                    <br></br>
                    <div className="text-body mb-[5px]">{address}</div>
                    <div className="text-body mb-[5px]">{address2}</div>
                  </div>
                </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
                      "
                      dangerouslySetInnerHTML={{ __html: sidebarText }}
                    />
                  </div>
                </div>
              </div>

              <div className="md:pb-20"></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 */}
      {customCtaSection?.enableCta && (
        <CallToAction heading={customCtaSection?.ctaText} link={customCtaSection?.ctaLink} linkColor="white" />
      )}
    </>
  )
}
