import React from 'react';
import { CheckBox } from '../formElements';
import ReactTableComponent from './ReactTableComponent';
import { RadioButton } from 'material-ui';
import styled from 'styled-components';
import PropTypes from 'prop-types';

const OtherStyles = styled.div`${({ height }) => `
.ReactTable .rt-tbody {
  height :${height ? height + 'px' : '100%'};
}

.ReactTable {
  .rt-thead {
    .rt-th {
      &:first-child {
        border-right: 0px;
      }
    }
  }
  .rt-tbody {
    .rt-td {
      border-right: 0px;
      padding-left: 20px
    }
  }
}
`}`

export default class RadioButtonTable extends React.Component {
  constructor(props) {
    super(props)
    this.state = { selected: {} }
  }

  toggleRow(key) {
    var selected = this.state.selected
    selected[key] = !selected[key]
    this.props.data.map((val, i) => {
      if (key != i) { selected[i] = false }
    })
    this.setState({ selected }, this.props.getSelectedRow(this.props.data[key]))
  }

  render() {
    var self = this;
    var { radioBoxWidth, columns, ...rest } = this.props
    var newColumns = [].concat(columns)
    newColumns.unshift({
      sortable: false,
      width: radioBoxWidth,
      id: "checkbox",
      Cell: ({ original, row }) => {
        var key = row._viewIndex
        return (
          <RadioButton
            checked={self.state.selected[key]}
            onClick={() => self.toggleRow(key)}
          />
        )
      }
    })
    return (
      <OtherStyles className="table" height={this.props.height}>
        <ReactTableComponent
          resizable={false}
          columns={newColumns}
          showPagination={false}
          defaultPageSize={this.props.data.length}
          {...rest}
        />
      </OtherStyles>
    )
  }
}

RadioButtonTable.propTypes = {
  data: PropTypes.array,
  columns: PropTypes.array,
  radioBoxWidth: PropTypes.number,
  getSelectedRow: PropTypes.func,
}