import { Dropdown, Icon, Menu, Tooltip } from '@8base/boost';
import cx from 'classnames';
import React, { useCallback } from 'react';

import ActionButton from './ActionButton';
import css from './file-actions.module.css';

// -- TYPES

interface IAction {
  title: string;
  onClick: (dropdownOpts: { closeDropdown: () => void }) => void;
}

interface IFileActionsProps {
  moreActions?: IAction[];
  isSquared?: boolean;
  isOwner?: boolean;
  downloadUrl?: string | null;
}

// -- MAIN

function FileActions({
  moreActions,
  downloadUrl,
  isSquared,
  isOwner,
}: IFileActionsProps) {
  const cnAction = cx(
    isSquared
      ? css['squared-action']
      : isOwner
      ? css['owner-action']
      : css['foreign-action'],
  );

  // TODO: it's not good practice to stop propagation. May be we should refactor it
  const onClickAction = useCallback(e => {
    e.stopPropagation();
  }, []);

  return (
    <>
      {moreActions && moreActions.length > 0 && (
        <ActionButton onClick={onClickAction} className={cnAction} isSquared={isSquared}>
          <Dropdown defaultOpen={false}>
            <Dropdown.Head>
              <Tooltip
                className={css.tooltip}
                message="More actions"
                placement="top"
                cursor="pointer"
                eventsEnabled={false}
              >
                <Icon name="More" />
              </Tooltip>
            </Dropdown.Head>
            <Dropdown.Body
              pin="left"
              withPortal={true}
              preventOverflow={true}
              placement="left"
            >
              {(dropdownOpts: any) => (
                <Menu>
                  {moreActions.map(item => (
                    <Menu.Item
                      key={item.title}
                      // tslint:disable-next-line: jsx-no-lambda
                      onClick={() => item.onClick(dropdownOpts)}
                    >
                      {item.title}
                    </Menu.Item>
                  ))}
                </Menu>
              )}
            </Dropdown.Body>
          </Dropdown>
        </ActionButton>
      )}

      {downloadUrl && (
        <ActionButton
          tagName="a"
          onClick={onClickAction}
          className={cnAction}
          isSquared={isSquared}
          href={downloadUrl}
          target="_blank"
          rel="noopener noreferrer"
        >
          <Tooltip
            className={css.tooltip}
            message="Download"
            placement="top"
            cursor="pointer"
            eventsEnabled={false}
          >
            <Icon name="Download" />
          </Tooltip>
        </ActionButton>
      )}
    </>
  );
}

export default FileActions;
