import { Button } from '@/components/ui/button'
import { RichTextType } from '@/lib/types/admin/richText'
import { cn } from '@/lib/utils/cn'
import React, { useEffect, useRef, useState } from 'react'

interface Props {
  data: {
    title: string
    id: string
    value: RichTextType
  }[]
}

export const Sidebar: React.FC<Props> = ({ data }) => {
  const [activeSection, setActiveSection] = useState(0)
  const clickedRef = useRef<boolean>(false)

  useEffect(() => {
    function handleScroll() {
      if (clickedRef.current) {
        return
      }
      data.map((el, i) => {
        const element = document.getElementById(`privacy${i}`)
        if (element) {
          const top = element.getBoundingClientRect().top - 96
          const bottom = element.getBoundingClientRect().bottom - 96

          if (top < 0 && bottom > 0) {
            setActiveSection(i)
          }
        }
      })
    }

    window.addEventListener('scroll', handleScroll)
  }, [])

  function scrollToElement(i: number) {
    const element = document.getElementById(`privacy${i}`)
    if (element) {
      window.scrollTo({
        top: element?.getBoundingClientRect().top + window.scrollY - 95,
        behavior: 'smooth',
      })
    }
  }

  return (
    <>
      <div className="max-xl:hidden relative gap-y-3 h-full max-w-[530px] w-full">

        <div className="flex flex-col gap-y-1 sticky bg-base-white/8 rounded-[8px] p-4 h-fit top-[85px] relative">
        <div className="max-xl:hidden absolute bottom-[39px] right-[-200px] w-[261px] h-[112px] rounded-[396px] bg-[#D39E7F] blur-[165px]"></div>

          {data.map((el, i) => {
            return (
              <Button
                variant="ancor-link"
                className="w-full"
                key={i}
                onClick={() => {
                  clickedRef.current = true
                  scrollToElement(i)
                  setActiveSection(i)

                  setTimeout(() => {
                    clickedRef.current = false
                  }, 1000)
                }}
                selected={activeSection === i}
              >
                {el.title}
              </Button>
            )
          })}
        </div>
      </div>
    </>
  )
}
