import React, {ReactNode, useState} from 'react'
import './index.less'
import Icon from '../icon/index'
import {initLevel, marginLeft, isLinkClassName, isSelectClassName} from './utils'

export type MenuEnum = {
  title: string | ReactNode
  id?: number
  icon?: string
  child?: MenuEnum[]
  isChose?: boolean
  level?: number
}

type Props = {
  closable?: boolean
  data: MenuEnum[]
  onClick?(item: MenuEnum): void
  onClose?(): void
}

type MenuItemProps = {
  menuItem: MenuEnum
  children: ReactNode
  onClick?(item: MenuEnum): void
}

const MenuItem: React.FC<MenuItemProps> = (props: MenuItemProps) => {
  const {menuItem, children} = props
  const [isFold, setFold] = useState(false)
  const renderIcon = () => {
    if (menuItem?.child?.length && menuItem?.level !== 1) {
      const iconName = menuItem.isChose ? 'chose-fold' : 'fold'
      return (
        <Icon
          className={`${isFold ? '' : 'icon-fold'}`}
          name={iconName}
          onClick={() => setFold(!isFold)}
        />
      )
    }
  }
  const renderChildren = () => {
    if (isFold) return <div />
    return children
  }
  return (
    <>
      <div
        className={`menu-title-box ${isSelectClassName(menuItem)}`}
        onClick={() => menuItem?.level !== 1 && props?.onClick?.(menuItem)}>
        <div className="menu-item-box">
          {menuItem.icon && <Icon className="menu-item-icon" name={menuItem.icon} />}
          <p className={`${isLinkClassName(menuItem)}`}>{menuItem.title}</p>
        </div>
        {renderIcon()}
      </div>
      {renderChildren()}
    </>
  )
}

const Menu: React.FC<Props> = (props: Props) => {
  const {closable, data} = props
  const [visible, setVisible] = useState(false)
  const recursionData = (menuData: MenuEnum[], level: number): MenuEnum[] => {
    return menuData?.map(item => ({
      ...item,
      child: item?.child ? recursionData(item?.child, level + 1) : [],
      level,
    }))
  }
  const renderMenuItem = (menuList: MenuEnum[]) => {
    return menuList.map((item, index) => {
      return (
        <div key={item.id || index} style={{marginLeft: `${marginLeft * (item.level! - 1)}px`}}>
          <MenuItem menuItem={item} onClick={props?.onClick}>
            <div>{renderMenuItem(item?.child!)}</div>
          </MenuItem>
        </div>
      )
    })
  }
  const onClickClose = () => {
    setVisible(!visible)
    if (visible) props?.onClose?.()
  }
  const newData = recursionData(data, initLevel)
  return (
    <div className={`component-menu ${visible ? 'visible' : ''}`}>
      {renderMenuItem(newData)}
      <div className="close-menu">
        {closable && <Icon name="close_menu" onClick={onClickClose} />}
      </div>
    </div>
  )
}

export default Menu
