import {useEffect, useRef} from "react"
import {WheelPickerProps} from "../../props"
import styles from "./styles.module.sass"

export const CustomWheel = ({selected, type, items, onChange, animation = "flat"}: WheelPickerProps) => {
  const height = 50
  const parentHeight = 200
  const scrollViewId = `picker-state-${type}`
  const scrollTimer = useRef<NodeJS.Timeout | null>(null)
  const scrollView = document.getElementById(scrollViewId)
  const itemHeight = animation === "wheel" ? 40 : height || 40
  const totalItems = items.length
  const dynamicSpace = `${(parentHeight || 0) / 2 - itemHeight / 2}px`
  const containerHeight = `${parentHeight}px`
  const sectionHeight = `${itemHeight}px`

  useEffect(() => {
    let y = selected * height - 1
    y = y === -1 ? 0 : y
    const scrollView = document.getElementById(scrollViewId)
    scrollView?.scroll({
      top: y,
      behavior: "smooth",
    })
  }, [])

  const onScroll = () => {
    //if there is already a timeout in process cancel it
    if (scrollTimer.current) clearTimeout(scrollTimer.current)

    const scrollTop = scrollView?.scrollTop || 0 // scroll value

    // itemInSelectorArea height of area available to scroll / height of individual item
    const itemInSelectorArea = parseInt(`${(scrollTop + itemHeight / 2) / itemHeight}`, 10) // add (height/2) to adjust error
    const selectAreaElement = document.getElementById(`${scrollViewId}-scroll-item--${itemInSelectorArea}`)
    onChange(type, itemInSelectorArea)

    if (itemInSelectorArea < totalItems) {
      selectAreaElement?.classList.add("selected-time")

      for (let i = 0; i < totalItems; i++) {
        if (i !== itemInSelectorArea) {
          const listElement = document.getElementById(`${scrollViewId}-scroll-item--${i}`)
          listElement?.classList.remove("selected-time")
        }
      }
    }

    const applyStyle = () => {
      let topShadeItem = itemInSelectorArea
      let topFade = 1
      let bottomFade = 0.66666
      const bottomShade = itemInSelectorArea + 1

      const topShadeElement = document.getElementById(`${scrollViewId}-scroll-item--${topShadeItem}`)
      const selectAreaElement = document.getElementById(`${scrollViewId}-scroll-item--${itemInSelectorArea}`)

      while (topShadeItem >= 0) {
        if (topShadeElement) {
          topShadeElement.style.transition = `all 0.3s`
          topShadeElement.style.opacity = `${topFade}`
        }
        topFade -= 0.333333
        topShadeItem--
      }

      if (selectAreaElement) selectAreaElement.style.opacity = `1`

      for (let i = bottomShade; i < totalItems; i++) {
        const listElement = document.getElementById(`${scrollViewId}-scroll-item--${i}`)
        if (listElement) {
          listElement.style.transition = `all 0.3s`
          listElement.style.opacity = `${bottomFade}`
        }
        bottomFade -= 0.33333
      }
    }

    scrollTimer.current = setTimeout(() => {
      onChange(type, itemInSelectorArea)
      let y = itemInSelectorArea * itemHeight - 1
      y = y === -1 ? 0 : y
      scrollView?.scroll({
        top: y,
        behavior: "smooth",
      })
    }, 150)

    applyStyle()

    onChange(type, itemInSelectorArea)
  }

  const renderItem = (item: string, index: number) => {
    const elementId = `${scrollViewId}-scroll-item--${index}`
    const isFirstItem = index === selected

    const onClickItem = () => scrollView?.scroll({top: isFirstItem ? 0 : index * itemHeight - 1, behavior: "smooth"})

    return (
      <section className={styles.scroll_item_container} data-item-height={sectionHeight}>
        <h4
          key={item}
          id={elementId}
          data-item-height={sectionHeight}
          className={`${styles.scroll_item} flex-col-center ${isFirstItem ? styles.selected_time : ""}`}
          onClick={onClickItem}>
          {item}
        </h4>
      </section>
    )
  }

  return (
    <section data-container-height={containerHeight} className={styles.custom_wheel_container}>
      <section
        className={styles.scroll_selector_area}
        data-dynamic-space={dynamicSpace}
        data-item-height={sectionHeight}
        id={`${scrollViewId}--scroll-selector-area`}></section>
      <section className={styles.scroll_select_list} id={scrollViewId} onScroll={onScroll}>
        <ul className={styles.wheel_list_container} data-dynamic-space={dynamicSpace}>
          {items.map(renderItem)}
        </ul>
      </section>
    </section>
  )
}
