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

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

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,
  );
  
  // Custom "active" style based on the image: blue text and light blue background
  const activeClassAddon = isLinkActive ? 'text-blue-600 font-medium' : ''
  const activeBgClass = isLinkActive ? 'bg-blue-50/70 border-r-4 border-blue-600' : ''

  const { asPath, isReady } = useRouter()

  useEffect(() => {
    if (item.href && isReady) {
      const linkPathName = new URL(item.href, location.href).pathname + '/';
      const activePathname = new URL(asPath, location.href).pathname

      const activeView = activePathname.split('/')[1];
      const linkPathNameView = linkPathName.split('/')[1];

      setIsLinkActive(linkPathNameView === activeView);
      
      // If a child is active, the parent should be open
      if (linkPathNameView === activeView && item.menu) {
          setIsDropdownActive(true);
      }
    }
  }, [item.href, isReady, asPath, item.menu])

  const asideMenuItemInnerContents = (
    <>
      {item.icon && (
        <BaseIcon path={item.icon} className={`flex-none mx-3 ${isLinkActive ? 'text-blue-600' : ''}`} size="18" />
      )}
      <span
        className={`grow text-ellipsis line-clamp-1 ${
          item.menu ? '' : 'pr-12'
        } ${activeClassAddon}`}
      >
        {item.label}
      </span>
      {item.menu && (
        <BaseIcon
          path={isDropdownActive ? mdiChevronDown : mdiChevronRight}
          className={`flex-none ${isLinkActive ? 'text-blue-600' : 'text-gray-400'}`}
          w="w-12"
          size="16"
        />
      )}
    </>
  )

  const componentClass = [
    'flex cursor-pointer py-2 ',
    isDropdownList ? 'px-6 text-sm' : '',
    activeBgClass,
    !isLinkActive ? (item.color
        ? getButtonColor(item.color, false, true)
        : `${asideMenuItemStyle}`) : '',
  ].join(' ');

  return (
    <li className={''}>
      {item.withDevider && <hr className={`${borders} mb-3`} />}
      {item.href && (
        <Link href={item.href} target={item.target} className={componentClass}>
          {asideMenuItemInnerContents}
        </Link>
      )}
      {!item.href && (
        <div className={componentClass} onClick={() => setIsDropdownActive(!isDropdownActive)}>
          {asideMenuItemInnerContents}
        </div>
      )}
      {item.menu && (
        <AsideMenuList
          menu={item.menu}
          className={`${asideMenuDropdownStyle} ${
            isDropdownActive ? 'block' : 'hidden'
          }`}
          isDropdownList
        />
      )}
    </li>
  )
}

export default AsideMenuItem