import React, { ComponentType } from 'react';
import { Button, Upload, UploadProps } from 'antd';
import {
  CheckCircleOutlined,
  DeleteOutlined,
  EditOutlined,
  UploadOutlined,
} from '@ant-design/icons';
import styles from 'pages/DevicesDashboard/Devices.module.scss';

export const ActionButton = ({
  icon,
  title,
  label,
  onClick,
  disabled,
}: {
  icon: ComponentType;
  title?: string;
  label?: string;
  onClick?: (event?: React.MouseEvent) => void;
  disabled?: boolean;
}): JSX.Element => {
  const Icon = icon ? icon : CheckCircleOutlined;
  const handleClick = (event: React.MouseEvent): void => {
    if (onClick) {
      onClick(event);
    }
  };
  const isLabel = label ? label : null;
  const isTitle = isLabel ? '' : title;

  return (
    <Button
      title={isTitle}
      type="link"
      className={styles['button']}
      icon={<Icon className={styles['iconsActions']} />}
      onClick={(event) => handleClick(event)}
      disabled={disabled}
    >
      {isLabel}
    </Button>
  );
};

export const UploadFile = ({
  icon,
  onClick,
  disabled,
  messages,
  fileName,
}: {
  onClick: (file: FormData) => void;
  messages: string;
  fileName: string;
  icon?: ComponentType;
  disabled?: boolean;
}): JSX.Element => {
  const file = new FormData();
  const props: UploadProps = {
    name: fileName,
    showUploadList: false,
    customRequest: async (value) => {
      await file.append(fileName, value.file);
      onClick(file);
    },
  };
  return (
    <Upload {...props}>
      <ActionButton
        icon={icon || UploadOutlined}
        label={messages}
        disabled={disabled}
      />
    </Upload>
  );
};

export const primaryButton = {
  edit: ({
    key,
    icon,
    action,
    disabled,
    translation,
  }: {
    key: string;
    translation: string;
    action: () => void;
    icon?: ComponentType;
    disabled?: boolean;
  }) => (
    <ActionButton
      key={key}
      icon={icon || EditOutlined}
      title={translation}
      disabled={disabled}
      onClick={(event?: React.MouseEvent) => {
        event?.stopPropagation();
        action();
      }}
    />
  ),
  delete: ({
    icon,
    action,
    disabled,
    translation,
  }: {
    translation: string;
    action: () => void;
    icon?: ComponentType;
    disabled?: boolean;
  }) => (
    <ActionButton
      key={translation}
      title={translation}
      icon={icon || DeleteOutlined}
      disabled={disabled}
      onClick={(event?: React.MouseEvent) => {
        event?.stopPropagation();
        action();
      }}
    />
  ),
};
