import { joinClassNames } from '@vizality/util/dom';
import { getModule } from '@vizality/webpack';
import { useToggle } from '@vizality/hooks';
import React, { memo } from 'react';

import { Tooltip } from '..';
import { Sidebar } from '.';

/**
 * Content sidebar that can be used as a side navigation or to hold content.
 * @component
 * @returns {React.MemoExoticComponent<function(): React.ReactElement>}
 */
export default memo(({ header, collapsed, onToggle, side = 'right', children, className }) => {
  const [ _collapsed, toggleCollapsed ] = useToggle(collapsed);
  const { auto, fade } = getModule('thin', 'scrollerBase');
  const { header: headerClass } = getModule('header', 'separator', 'side', 'top');
  return (
    <div
      className={joinClassNames('vz-dashboard-content-sidebar', className)}
      vz-collapsed={Boolean(_collapsed) && ''}
      vz-expanded={Boolean(!_collapsed) && ''}
    >
      <Tooltip text={_collapsed ? 'Expand' : 'Collapse'}>
        <div
          className='vz-dashboard-content-sidebar-expander'
          onClick={() => {
            toggleCollapsed();
            onToggle?.();
          }}
        />
      </Tooltip>
      <div className='vz-dashboard-content-sidebar-inner'>
        <div className='vz-dashboard-content-sidebar-header-wrapper'>
          <div className={joinClassNames('vz-dashboard-content-sidebar-header', headerClass)}>
            {header}
          </div>
          <Tooltip text={_collapsed ? 'Expand' : 'Collapse'}>
            <div
              className='vz-dashboard-content-sidebar-collapser'
              onClick={() => {
                toggleCollapsed();
                onToggle?.();
              }}
            />
          </Tooltip>
        </div>
        <div className={joinClassNames('vz-dashboard-content-sidebar-items', auto, fade)}>
          {children}
        </div>
      </div>
    </div>
  );
});

/**
 * Content sidebar navigation item.
 * @component
 * @returns {React.MemoExoticComponent<function(): React.ReactElement>}
 */
export const NavItem = memo(({ icon, route, selected, onClick, children, className, ...other }) => {
  return (
    <Sidebar.Item
      {...other}
      icon={icon}
      route={route}
      className={joinClassNames('vz-dashboard-content-sidebar-item-wrapper', className)}
      selected={selected}
      onClick={onClick}
    >
      {children}
    </Sidebar.Item>
  );
});
