import React, { useEffect, useState } from 'react'

import styles from '../css/TabMenu.module.scss'

interface ITabMenuProps {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  list: { key: string | number; name: string; label?: string }[] | any
  actKey?: string | number
  keyChange?: { key: string | number; name: string } // 用于转换Key
  className?: string
  onChange: (key: string | number) => void
}

/**
 * 菜单组件
 */
const TabMenu: React.FC<ITabMenuProps> = props => {
  const { list, actKey, keyChange, className, onChange } = props
  // const [actKey, setActKey] = useState<string | number | undefined>(defalutKey)
  const [newList, setNewList] = useState<{ key: string | number; name: string; label?: string }[]>(list)

  useEffect(() => {
    let _list: { key: string | number; name: string; label?: string }[] = list
    if (keyChange) {
      _list = list?.map((item: { [x: string]: string | number }) => {
        return {
          key: item[keyChange.key],
          name: item[keyChange.name] as string
        }
      })
    }
    setNewList(_list)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [keyChange, list])

  const handleChangeTabMenu = (key: string | number) => {
    onChange(key)
  }

  return (
    <div className={`${styles['tabmenu-wrapper']} ${className ? className : ''}`}>
      {newList?.map((item: { key: string | number; name: string }, index) => (
        <div
          className={`menu-item ${actKey === item.key ? 'act-menu' : ''}`}
          key={item.key || index}
          onClick={handleChangeTabMenu.bind(this, item.key)}
        >
          {item.name}
        </div>
      ))}
    </div>
  )
}

export default TabMenu
