import {
  PropsWithChildren,
  ReactNode,
  useEffect,
  useRef,
  useState
} from 'react'

import styles from './StickySideColumns.module.scss'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { IconDefinition } from '@fortawesome/free-solid-svg-icons'
import { Button } from '@mui/material'

interface StickySideColumnsProps {
  left: ReactNode
  right: ReactNode
  leftIcon: IconDefinition
  centerIcon: IconDefinition
  rightIcon: IconDefinition
}

const DEFAULT_TAB = 'nav-content'
export const StickySideColumns = ({
  left,
  right,
  leftIcon,
  centerIcon,
  rightIcon,
  children
}: PropsWithChildren<StickySideColumnsProps>) => {
  const [tab, setTab] = useState(DEFAULT_TAB)
  const ref = useRef<HTMLDivElement>(null)
  const tabsRefs = useRef<{ [id: string]: HTMLDivElement | null }>({})
  const handleNavClick = (id: string) => {
    if (ref.current && tabsRefs.current) {
      const x = tabsRefs.current[id]?.offsetLeft
      ref.current.scrollTo({
        left: x,
        behavior: 'smooth'
      })
    }
  }
  const isActive = (id: string) => id === tab

  useEffect(() => {
    setTab(DEFAULT_TAB)
    handleNavClick(DEFAULT_TAB)
  }, [])

  useEffect(() => {
    const tabs = tabsRefs.current
    // Set up the observer
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            setTab(entry.target.id)
          }
        })
      },
      {
        root: ref.current,
        threshold: 0.5,
        rootMargin: '-20px'
      }
    )

    if (tabs) {
      Object.values(tabs).forEach((tab) => {
        if (tab) observer.observe(tab)
      })
    }

    return () => {
      if (tabs) {
        Object.values(tabs).forEach((tab) => {
          if (tab) observer.unobserve(tab)
        })
      }
    }
  }, [])

  return (
    <>
      <div className={styles.container} ref={ref}>
        <div
          id="nav-left"
          className={styles.sidesWrap}
          ref={(tab) => (tabsRefs.current['nav-left'] = tab)}
        >
          <div className={styles.sides}>{left}</div>
        </div>
        <div
          id="nav-content"
          className={styles.scrollAdjust}
          ref={(tab) => (tabsRefs.current['nav-content'] = tab)}
        >
          <div id="content-preview" className={styles.content}>
            {children}
          </div>
        </div>
        <div
          id="nav-right"
          className={styles.sidesWrap}
          ref={(tab) => (tabsRefs.current['nav-right'] = tab)}
        >
          <div className={styles.sides}>{right}</div>
        </div>
      </div>
      <ul className={styles.navTabs}>
        <li>
          <Button
            fullWidth
            variant="text"
            onClick={() => handleNavClick('nav-left')}
            className={`${isActive('nav-left') && styles.active}`}
            aria-label="nav left"
          >
            <FontAwesomeIcon icon={leftIcon} />
          </Button>
        </li>
        <li>
          <Button
            fullWidth
            variant="text"
            onClick={() => handleNavClick('nav-content')}
            className={`${isActive('nav-content') && styles.active}`}
            aria-label="nav middle"
          >
            <FontAwesomeIcon icon={centerIcon} />
          </Button>
        </li>
        <li>
          <Button
            fullWidth
            variant="text"
            onClick={() => handleNavClick('nav-right')}
            className={`${isActive('nav-right') && styles.active}`}
            aria-label="nav right"
          >
            <FontAwesomeIcon icon={rightIcon} />
          </Button>
        </li>
      </ul>
    </>
  )
}
