import React, { useEffect, useRef, useState } from 'react'
import styled, { createGlobalStyle } from 'styled-components'

export type SliderProps = {
  list?: string[];
  css?:string;
  scrollRefs?:React.MutableRefObject<HTMLLIElement>[]
};

let scrolling = false

export const Slider = ({ list,scrollRefs }:SliderProps):JSX.Element => {
  const navRefs = useRef<any>()
  
  const [active, setActive] = useState(0)
  const [showMenu,setShowMenu] = useState(false) 

  navRefs.current = list?.map(() => React.createRef() as React.MutableRefObject<HTMLLIElement>)

  const scrollTo = (index:number) => {
    if(scrollRefs) {
      scrolling = true
      scrollRefs[index].current.scrollIntoView({ behavior: 'smooth' })
      setActive(index)
      setTimeout(() => {
        scrolling = false
        navRefs.current[index].current.scrollIntoView({
          behavior: 'smooth',
          block: 'start',
          inline: 'center'
        })
      }, 1000)
    }
  }

  const scrollHandler = (e:Event) => {
    if(scrollRefs) {
      if (e.target !== document) return

      if (scrolling === true) return
  
      scrollRefs.forEach((el, i) => {
        const rect = el.current.getBoundingClientRect()
        const elemTop = rect.top
        const elemBottom = rect.bottom
        const isVisible =
          elemTop < window.innerHeight / 2 && elemBottom > window.innerHeight / 2
  
        if (isVisible) {
          navRefs.current[i].current.scrollIntoView({
            behavior: 'smooth',
            block: 'center',
            inline: 'center'
          })
          setActive(i)
        }
      })
    }
  }

  useEffect(() => {
    window.addEventListener('scroll', scrollHandler, true)
    return () => {
      window.removeEventListener('scroll', scrollHandler, true)
    }
  }, [])

  return (
    <>
      <GlobalStyle />
      <NavContainer>
        <NavList>
          {list?.map((item, i) => (
            <li key={i} ref={navRefs.current[i]}>
              <NavAnchor href={`#s-${i}`}
                style={ active === i ? { color:'white',backgroundColor:'turquoise', borderRadius:'20px' }: {}}
                onClick={() => {
                  scrollTo(i)
                }}
              >
                {item}
              </NavAnchor>
            </li>
          ))}
        </NavList> 
     
        <MenuButton onClick={() => setShowMenu(!showMenu)}>...</MenuButton>
     
        {showMenu && <MenuContainer >
          <ul style={{ padding:0 }}>
            {list?.map((item, i) => (
              <MenuContentContainer key={i}>
                <p style={ active === i ? { }: { visibility:'hidden' }}>✔️</p>
                <MenuContentItem onClick={() => scrollTo(i)}>
                  {item}
                </MenuContentItem>
              </MenuContentContainer>
            ))}
          </ul>
        </MenuContainer>}
      </NavContainer>
    </>
  )
}

const NavContainer = styled.div`
  display: flex;
  flex-direction: row;
  justify-content: center;
  position: fixed;
  background-color: white;
  top: 0;
  box-shadow: rgb(0 0 0 / 4%) 1.95px 1.95px 2.6px;
  width: 300px;
  align-items: center;
  border-bottom: 1px solid gainsboro;
`

const NavList = styled.ul`
  background-color: white;
  padding: 10px;
  margin: 0px;
  overflow: overlay;
  padding-left: 0;
  margin-bottom: 0;
  list-style: none;
  display: flex!important;
  flex-wrap: nowrap!important;
  top: 0;
  right: 0;
  
  ::-webkit-scrollbar {
    display: none;
  }
`

const MenuButton = styled.button`
  border-radius: 50%;
  color: turquoise;
  border: 1px solid gainsboro;
  cursor:pointer;
  background-color:white;
  width:20px;
  height:20px;
  display:flex;
  justify-content:center;
  margin-left:14px;
`

const MenuContainer = styled.div`
  bottom: 0;
  position: absolute;
  right: 0;
  background: white;
  border: 1px solid gainsboro;
  top: 40px;
  width: 200px;
  height: fit-content;
  border-radius: 10px;
`

const MenuContentContainer = styled.div`
  border-bottom: 1px solid gainsboro;
  display:flex;
  align-items:center;
  height:40px;
  padding:0px 10px;

  :first-child {
    border-top: 1px solid gainsboro;
  }

  :last-child {
    border-bottom: 0;
  }
`

const MenuContentItem = styled.li`
  list-style:none;
  padding:10px;
  cursor:pointer;
  font-family: sans-serif;
    font-size: 1rem;
`

const NavAnchor = styled.a`
  display: block;
  padding: 0.2rem 1rem;
  color: turquoise;
  text-decoration: none;
  font-size: 0.8rem;
  transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out;
  white-space: nowrap!important;
`

const GlobalStyle = createGlobalStyle`
h1,
p {
  font-family: sans-serif;
}

html {
  scroll-behavior: smooth;
}

body {
  max-width: 400px !important;
  margin: 0 auto;
}`