import React from 'react';
import { Menu } from 'antd';
import { useNavigate } from 'react-router-dom';
import useRoute from '@/utils/hooks/useRoute';

const menuStyle = { height: '100%', borderRight: 0 };

export default (props) => {
  const { theme, items, location } = props;
  const navigate = useNavigate();
  const { meta } = useRoute() || {};

  const selectedKeys = React.useMemo(() => {
    const parts = location.pathname.split('/').filter(Boolean);
    const keys = parts.reduce((acc, it) => {
      const parent = acc.pop();
      const path = !parent ? `/${it}` : `${parent}/${it}`

      return acc.concat([parent, path].filter(Boolean));
    }, []);

    return keys;
  }, [location.pathname]);

  // const selectedKeys = [location.pathname];

  const onClick = ({key}) => {
    const path = key
    if (path.indexOf('http') > -1) {
      document.createElement('a');
      a.href = path;
      a.target = '_blank';
      a.click();
    } else {
      if (meta?.target === '_blank') {
        document.createElement('a');
        a.href = `${window.location.pathname}#${path}`
        a.target = '_blank';
        a.click();
      } else {
        navigate(path);
      }
    }
  }

  return (
    <Menu
      mode="inline"
      style={menuStyle}
      theme={theme}
      items={items}
      selectedKeys={selectedKeys}
      onClick={onClick}
    />
  )
}
