import { Button, Dropdown, Menu } from 'antd';
import {
  DownloadOutlined,
  RedoOutlined,
  EllipsisOutlined,
} from '@ant-design/icons';
import { ActionButton, primaryButton, UploadFile } from './buttonSet';
import { Props, TypeButton, TypeDropDownButtonConfig } from './types';

const SingleActionsCard = ({ buttonsConfig }: Props): JSX.Element => {
  const dropDownButtonConfig: TypeDropDownButtonConfig = {
    upload: ({ messages, action, fileName, icon, disabled }) => ({
      key: fileName,
      label: (
        <UploadFile
          fileName={fileName}
          onClick={action}
          messages={messages}
          icon={icon}
          disabled={disabled}
        />
      ),
    }),
    download: ({ messages, action, icon, disabled }) => ({
      key: 'download',
      label: (
        <ActionButton
          icon={icon || DownloadOutlined}
          onClick={action}
          label={messages}
          disabled={disabled}
        />
      ),
    }),
    customButton: ({ messages, action, icon, disabled, key }) => ({
      key: key,
      label: (
        <ActionButton
          icon={icon || RedoOutlined}
          onClick={action}
          label={messages}
          disabled={disabled}
        />
      ),
    }),
  };

  const menuItemsArray = (
    menuItems: TypeButton[],
  ): { key: string; label: JSX.Element }[] => {
    return menuItems.map((item) =>
      dropDownButtonConfig[item.type as 'upload' | 'download' | 'customButton'](
        {
          key: item.key,
          icon: item.icon,
          action: item.action,
          disabled: item.disabled,
          messages: item.translation,
          fileName: item.fileName || ' ',
        },
      ),
    );
  };

  return (
    <div style={{ display: 'flex', justifyContent: 'center' }}>
      {buttonsConfig.map((item, index) => {
        return Array.isArray(item) ? (
          <Dropdown
            key={index}
            overlay={
              <Menu
                items={menuItemsArray(item)}
                onClick={(value) => value.domEvent.stopPropagation()}
              />
            }
          >
            <Button type="link" onClick={(e) => e.stopPropagation()}>
              <EllipsisOutlined />
            </Button>
          </Dropdown>
        ) : (
          primaryButton[item?.key as 'edit' | 'delete'] &&
            primaryButton[item?.key as 'edit' | 'delete']({
              key: item.key,
              icon: item.icon,
              action: item.action,
              translation: item.translation,
            })
        );
      })}
    </div>
  );
};

export default SingleActionsCard;
