import React from 'react';
import { Menu } from 'antd';
import { useNavigate } from 'react-router-dom';

export default (props) => {
  const { items, onChange, location } = props;

  const navigate = useNavigate();
  const [selectedKeys, setSelectedKeys] = React.useState([]);

  const renderItems = React.useMemo(() => items.map(x => ({ ...x, children: undefined })), [items]);

  const rootPath = React.useMemo(() => `/${location.pathname.split('/')[1]}`, [location.pathname]);

  const onClick = (item) => {
    onChange(item.key);
    navigate(item.key);
  };

  React.useEffect(() => {
    setSelectedKeys([rootPath]);
    onChange(rootPath);
  }, [rootPath]);

  return (
    <Menu className='split-menu' mode="horizontal" items={renderItems} selectedKeys={selectedKeys} onClick={onClick} />
  )
}
