import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Spinner from '../../Spinner';
import TextIcon from '../../TextIcon';
import Button from '../../Button';
import Icon from '../../Icon';

import './list-file.scss';

const propTypes = {
  value: PropTypes.PropTypes.arrayOf(
    PropTypes.shape({
      name: PropTypes.string,
      preview: PropTypes.string,
      loading: PropTypes.bool
    })
  ).isRequired,
  handleDelete: PropTypes.func,
  handleEdit: PropTypes.func,
  children: PropTypes.node
};

const defaultProps = {
  handleDelete: undefined,
  handleEdit: undefined,
  children: undefined
};

class ListFile extends PureComponent {
  handlerDelete = (file, row) => () => {
    const { handleDelete } = this.props;
    if (handleDelete) {
      handleDelete(file, row);
    }
  };

  handlerEdit = (file, row) => () => {
    const { handleEdit } = this.props;
    if (handleEdit) {
      handleEdit(file, row);
    }
  };

  render() {
    const { value, handleDelete, handleEdit, children } = this.props;
    return (
      <div styleName="base">
        {value
          .map((file, row) => {
            const { loading, key, preview, name } = file;
            return (
              <div styleName="content" key={key || preview}>
                {loading ?
                  <Spinner
                    noLabel
                    styleName="spinner"
                  /> :
                  loading === false && <Icon
                    styleName="icon"
                    size="sm"
                    name="ok-circle"
                  />
                }
                <div styleName="file-name">
                  <TextIcon name="doc" size="sm">
                    {name}
                    {handleDelete &&
                    <Button
                      onClick={this.handlerDelete(file, row)}
                      type="button"
                      styleName="button-trash"
                      variant="icon"
                      size="sm"
                    >
                      <Icon name="trash" size="xs" />
                    </Button>}
                    {handleEdit &&
                    <Button
                      onClick={this.handlerEdit(file, row)}
                      type="button"
                      styleName="button-trash"
                      variant="icon"
                      size="sm"
                    >
                      <Icon name="edit" size="xs" />
                    </Button>}
                  </TextIcon>
                </div>
              </div>
            );
          })
        }
        {children}
      </div>
    );
  }
}

ListFile.propTypes = propTypes;
ListFile.defaultProps = defaultProps;

export default ListFile;
