import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import dt from 'datatables.net';
import responsive from 'datatables.net-responsive';
import buttons from 'datatables.net-buttons';
import ToolbarSection from '../../../../ui/routes/components/components/Toolbar3.js';
import IconButton from 'material-ui/IconButton';
import FlatButton from 'material-ui/FlatButton';
import {
  Row,
  Col,
  Grid,
  Panel,
  Table,
  PanelBody,
  PanelHeader,
  FormControl,
  PanelContainer,
} from '@sketchpixy/rubix';
import moment from 'moment';
import Dialog from 'material-ui/Dialog';
import Instance from '../../../../../../../components/Connection';

dt.responsive = responsive;
$.dataTable = dt;

// IconButtonExampleTouch2 = () => (
//   <FlatButton href="#/app/form/steppers/"><i className="material-icons">schedule</i><span className="nav-text"></span></FlatButton>
// );

const locationModal = () => (
  <NEMTLocation data={this.state} title={"Provider"} value={""} buttonvalue={this.state.buttonProviderText} onPlaceChanged={this.handleProviderChanged} textSize={30} locationType="provider" />
);

const formatTime = function (sec_num) {
  var hours = Math.floor(sec_num / 3600);
  var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
  var seconds = sec_num - (hours * 3600) - (minutes * 60);

  if (hours < 10) { hours = "0" + hours; }
  if (minutes < 10) { minutes = "0" + minutes; }
  if (seconds < 10) { seconds = "0" + seconds; }
  return hours + ':' + minutes + ':' + seconds;
}

const handleProviderChanged = function (destination) {
  console.log(destination);
}

class DatatableComponent extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      items: [],
      data: [],
      list: [],
      orgType: {},
    };

    this.getOrganizations = this.getOrganizations.bind(this);
  }

  getDTList(organization) {
    return organization.map(o => {
      let status = o.active ? 'Active' : 'Inactive';
      status = o.suspended ? 'Suspended' : status;
      status = o.blocked ? 'Blocked' : status;

      return (<tr key={o.id}>
        <td><a href={`/#/app/organization/${o.id}`}>{o.name}</a></td>
        <td><a href={`/#/app/organization/${o.id}`}>{o.type.name}</a></td>
        <td><a href={`/#/app/organization/${o.id}`}>{status}</a></td>
        <td><a href={`/#/app/organization/${o.id}`}>{moment(o.created).format('MM/DD/YY - h:mm a')}</a></td>
        <td><a href={`/#/app/organization/${o.id}`}>{moment(o.updated).format('MM/DD/YY - h:mm a')}</a></td>
        <td>{o.author.name}</td>
        <td>{o.last_editor.name}</td>
      </tr>)
    });
  }

  getOrganizations() {
    const self = this;
    if (this.state.orgType) {
      Instance.getRawConn().get("/v1/nemt/organization").then((res) => {
        let list = this.getDTList(res.data);

        $.fn.dataTable.moment = function (format, locale) {
          var types = $.fn.dataTable.ext.type;

          // Add type detection
          types.detect.unshift(function (d) {
            return moment(d, format, locale, true).isValid() ?
              'moment-' + format :
              null;
          });

          // Add sorting method - use an integer for the sorting
          types.order['moment-' + format + '-pre'] = function (d) {
            return moment(d, format, locale, true).unix();
          };
        };

        $.fn.dataTable.moment('MM/DD/YYYY h:mm a');

        self.setState(Object.assign(self.state, { list: list }));

        const dt = $(ReactDOM.findDOMNode(self.example))
          .addClass('nowrap')
          .dataTable({
            responsive: true,
            dom: 'Bfrtip',
            buttons: [
              'copy', 'pdf'
            ],
            //  columns: TABLE_COLUMNS_SORT_STYLE,
            responsive: true,
            "bStateSave": true,
            details: {
              type: 'inline'
            },
            columnDefs: [
              { targets: [-1, -3], orderable: true, className: 'dt-body-right mdl-data-table__cell--non-numeric' }
            ],
            order: [[0, 'desc']]
          });

        dt.on('column-visibility.dt', function (e, settings, column, state) {
          console.log(
            'Column ' + column + ' has changed to ' + (state ? 'visible' : 'hidden')
          );
        });

        dt.on('responsive-display', function (e, datatable, row, showHide, update) {
          console.log('Details for row ' + row.index() + ' ' + (showHide ? 'shown' : 'hidden'));
        });

        this.decorateButtons();
        this.decorateSelect();
        this.decorateSearchBar();
        this.decorateColumns();
      }).catch(console.error);
    }
  }

  componentWillReceiveProps(nextProps) {
    const self = this;
    this.setState(Object.assign(this.state, { orgType: nextProps.orgType }));
    //this.getOrganizations();
  }

  componentDidMount() {
    const self = this;
    if (this.props.orgType) {
      this.setState(Object.assign(this.state, { orgType: this.props.orgType }));
      this.getOrganizations();
    }
  }

  decorateColumns() {
    let cols = $('td');
    let colStyle = {
      'font-family': 'Roboto, sans-serif',
      'font-size': '13px',
      'font-weight': '300',
      'text-align': 'left',
    };
    cols.css(colStyle);
    cols.removeClass('sorting_1');

    let headers = $('th');
    let headerStyle = {
      'color': 'rgb(158, 158, 158)',
      'text-align': 'left',
      'font-weight': '600',
      'font-size': '12px'
    };
    headers.css(headerStyle);

    let oddRows = $('.odd');
    let evenRows = $('.even');

    let oddStyle = {
      'background': 'rgba(127, 221, 233, 0.4)',
      'text-shadow': 'none',
      'border-bottom': '1px solid rgb(224, 224, 224)',
      'color': 'rgba(0, 0, 0, 0.87)',
      'height': '45px'
    };
    oddRows.css(oddStyle);

    let evenStyle = oddStyle;
    evenStyle['background'] = '#fff';

    evenRows.css(evenStyle);
  }

  decorateSelect() {
    let instance = this;
    let selectElement = $('select[class]');
    selectElement.addClass('mdl');

    selectElement.click(function () {
      instance.decorateButtons();
    });

    let selectLabel = $('#DataTables_Table_0_length > label');
    let style = {
      'color': 'rgb(158, 158, 158)',
      'text-align': 'left',
      'font-weight': '500',
      'font-size': '11px'
    };
    selectLabel.css(style);
  }

  decorateSearchBar() {
    let instance = this;

    let searchbar = $('input[type="search"]');
    searchbar.bind('input', function () {
      instance.decorateButtons();
      instance.decorateColumns();
    });

    searchbar.addClass('mdl-textfield__input');
    searchbar.attr('placeholder', '');

    let searchLabel = $('#DataTables_Table_0_filter > label');
    searchLabel.css({ 'color': '#fff' });
    searchbar.css({ 'color': 'rgb(158, 158, 158)' })

    let searchFilter = $('#DataTables_Table_0_filter');
    searchFilter.append('<svg viewBox="0 0 24 24" style="display: inline-block; color: rgba(0, 0, 0, 0.87); fill: currentcolor; height: 24px; width: 24px; user-select: none; transition: all 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms; margin-top: 12px;"><path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path></svg>');
  }

  decorateButtons() {
    let instance = this;
    let paginateButtons = $('a.paginate_button');
    paginateButtons.addClass('mdl-button');

    let selectedButton = $('a.paginate_button.current');
    selectedButton.addClass('mdl-button mdl-button--raised mdl-button--colored');

    let style = {
      'background': 'rgb(0, 188, 212)',
      'font-weight': '400',
    };
    selectedButton.css(style);

    paginateButtons.click(function () {
      instance.decorateButtons();
      instance.decorateColumns();
    });

    let sortingButtons = $('th.sorting, th.sorting_asc, th.sorting_desc');
    sortingButtons.click(function () {
      instance.decorateButtons();
      instance.decorateColumns();
    });

    let entriesLabel = $('#DataTables_Table_0_info');
    entriesLabel.css({
      'color': 'rgb(158, 158, 158)',
      'text-align': 'left',
      'font-weight': '400',
      'font-size': '12px'
    });
  }

  render() {
    return (
      <Table ref={(c) => this.example = c} className='display' cellSpacing='0' width='100%'>
        <thead>
          <tr>
            <th>Name</th>
            <th>Type</th>
            <th>Status</th>
            <th>Created</th>
            <th>Updated</th>
            <th>Author</th>
            <th>Last Editor</th>
          </tr>
        </thead>
        <tbody>
          {this.state.list}
        </tbody>
      </Table>
    );
  }
}

export default class Datatablesjs extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
  }

  componentDidMount() {
    //console.log(this.props);
  }

  componentWillReceiveProps(nextProps) {
    this.props = nextProps;
  }

  render() {
    return (
      <Row>
        <Col xs={12}>
          <PanelContainer>
            <Panel>
              <PanelBody>
                <Grid>
                  <Row>
                    <Col xs={12}>
                      <DatatableComponent orgType={this.props.orgType} />
                      <br />
                    </Col>
                  </Row>
                </Grid>
              </PanelBody>
            </Panel>
          </PanelContainer>
        </Col>
      </Row>
    );
  }
}