import React from 'react';

class FieldRepeater extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      rows: props.rows || []
    };

    this.handleNewRow = this.handleNewRow.bind(this);
    this.handleRemoveRow = this.handleRemoveRow.bind(this);
  }

  handleNewRow() {
    this.setState({ rows: this.state.rows.concat([this.props.children]) });
  }

  handleRemoveRow(e) {
    this.state.rows.splice(e.target.getAttribute('data-index'), 1);

    this.setState({
      rows: this.state.rows
    })
  }

  render() {

    return (
      <>
        <div className="box-content">
          <div className="columns">
            <div className="column-12">
              <div className="field field-info">
                <h3 className="field-info-title">{this.props.title}</h3>
                <p className="field-info-text">{this.props.desc}</p>
              </div>
            </div>
            <div className="column-12">
              <div className="field">
                {this.state.rows.map((row, index) => {
                  return (
                    <div className="box-repeater" key={index}>
                      <div className="box-repeater-header">
                        <h4>{index + 1 + ' ' + this.props.title + ' item'}</h4>
                        <button type="button" className="btn btn-red btn-link btn-small" data-index={index} onClick={this.handleRemoveRow}>Remove</button>
                      </div>
                      <div className="box-repeater-content">
                        {React.cloneElement(row, { index })}
                      </div>
                    </div>
                  )
                })}
              </div>
            </div>
          </div>
        </div>
        <div className="box-footer">
          <button type="button" className="btn btn-blue" onClick={this.handleNewRow}>Add new item</button>
        </div>
      </>
    )
  }
}

export default FieldRepeater;
