import React, { useEffect, useState } from 'react'
import { mdiChevronDown, mdiChevronUp } from '@mdi/js'
import Link from 'next/link'
import { useRouter } from 'next/router'
import BaseIcon from './BaseIcon'
import { getButtonColor } from '../colors'
import AsideMenuList from './AsideMenuList'
import { MenuAsideItem } from '../interfaces'
import { useAppSelector } from '../stores/hooks'

type Props = {
  item: MenuAsideItem
  isDropdownList?: boolean
}

const getActiveView = (path: string) => new URL(path, location.href).pathname.split('/')[1]

const itemMatchesActiveView = (menuItem: MenuAsideItem, activeView: string): boolean => {
  if (menuItem.href && getActiveView(menuItem.href) === activeView) {
    return true
  }

  if (!menuItem.menu?.length) {
    return false
  }

  return menuItem.menu.some((nestedItem) => itemMatchesActiveView(nestedItem, activeView))
}

const AsideMenuItem = ({ item, isDropdownList = false }: Props) => {
  const [isLinkActive, setIsLinkActive] = useState(false)
  const [isDropdownActive, setIsDropdownActive] = useState(false)

  const asideMenuItemStyle = useAppSelector((state) => state.style.asideMenuItemStyle)
  const asideMenuDropdownStyle = useAppSelector((state) => state.style.asideMenuDropdownStyle)
  const asideMenuItemActiveStyle = useAppSelector((state) => state.style.asideMenuItemActiveStyle)
  const borders = useAppSelector((state) => state.style.borders)
  const activeLinkColor = useAppSelector((state) => state.style.activeLinkColor)
  const activeClassAddon = !item.color && isLinkActive ? asideMenuItemActiveStyle : ''
  const isGroupTrigger = Boolean(item.menu && !item.href && !isDropdownList)

  const { asPath, isReady } = useRouter()

  useEffect(() => {
    if (!isReady) {
      return
    }

    const activeView = getActiveView(asPath)

    if (item.href) {
      setIsLinkActive(getActiveView(item.href) === activeView)
    }

    if (item.menu?.length) {
      setIsDropdownActive(item.menu.some((nestedItem) => itemMatchesActiveView(nestedItem, activeView)))
    }
  }, [item.href, item.menu, isReady, asPath])

  const asideMenuItemInnerContents = (
    <>
      {item.icon && (
        <span className='flex h-9 w-9 flex-none items-center justify-center rounded-xl'>
          <BaseIcon path={item.icon} className={`${activeClassAddon}`} size='18' />
        </span>
      )}
      <span
        className={`min-w-0 grow whitespace-normal break-words leading-5 line-clamp-2 ${item.menu ? '' : 'pr-3'} ${isGroupTrigger ? 'text-[0.93rem] tracking-[0.01em]' : ''} ${activeClassAddon}`}
      >
        {item.label}
      </span>
      {item.menu && (
        <BaseIcon
          path={isDropdownActive ? mdiChevronUp : mdiChevronDown}
          className={`flex-none ${activeClassAddon}`}
          size='18'
        />
      )}
    </>
  )

  const componentClass = [
    'group flex w-full items-start gap-3 rounded-xl px-3 text-left transition-all duration-150',
    isDropdownList ? 'py-2 text-sm' : 'py-2.5',
    item.color ? getButtonColor(item.color, false, true) : `${asideMenuItemStyle}`,
    isGroupTrigger ? 'font-semibold' : '',
    isLinkActive ? `${activeLinkColor} shadow-sm` : '',
  ].join(' ')

  return (
    <li className={isDropdownList ? 'px-2 py-1' : 'px-2 py-1.5'}>
      {item.withDevider && <hr className={`${borders} mb-3`} />}
      {item.href ? (
        <Link href={item.href} target={item.target} className={componentClass}>
          {asideMenuItemInnerContents}
        </Link>
      ) : (
        <button type='button' className={componentClass} onClick={() => setIsDropdownActive(!isDropdownActive)}>
          {asideMenuItemInnerContents}
        </button>
      )}
      {item.menu && (
        <AsideMenuList
          menu={item.menu}
          className={`${asideMenuDropdownStyle} ${
            isDropdownActive
              ? 'mt-2 ml-3 block rounded-xl p-2'
              : 'hidden'
          }`}
          isDropdownList
        />
      )}
    </li>
  )
}

export default AsideMenuItem
