import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import dt from 'datatables.net';
import responsive from 'datatables.net-responsive';
import IconButton from 'material-ui/IconButton';
import RaisedButton from 'material-ui/RaisedButton';
import ContentAdd from 'material-ui/svg-icons/content/add';
import RoadTripLink from '../../../../../components/RoadtripLink';

import {
  Row,
  Col,
  Grid,
  Panel,
  Table,
  PanelBody,
  PanelHeader,
  FormControl,
  PanelContainer,
} from '@sketchpixy/rubix';
import Instance from '../../../../../../../components/Connection';

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

function formatPhoneNumber(s) {
  var s2 = ("" + s).replace(/\D/g, '');
  var m = s2.match(/^(\d{3})(\d{3})(\d{4})$/);
  return (!m) ? null : "(" + m[1] + ") " + m[2] + "-" + m[3];
}

const handleRide = function (r) {
  location.href = `/#/app/page/map/${r.ride_uuid}`;
}

const getDTList = function (member) {
  let list = [];

  member.forEach((r, i) => {
    let bookRide = '';
    if (r.trip_type.key === 'no_trip') {
      bookRide = (<a href={`/#/app/form/visitride/${r.visit_uuid}`}>Book Ride</a>)
    }

    list.push(
      <tr key={r.visit_uuid}>
        <td>{moment(r.visit_datetime).format('MM/DD/YYYY - h:mm a')}</td>
        <td><a href={""}>{r.provider.name}</a></td>
        <td><a href={"/#/app/member/" + r.user.useruuid}>{r.user.name}</a></td>
        <td>{bookRide}</td>
        <td><RoadTripLink rides={r.rides} isOpened={false} currentRide={null} visit={r} onRideClick={handleRide} /></td>
        <td><a href={"/#/app/member/" + r.user.useruuid}>{r.user.member}</a></td>
        <td>{r.provider.provider_uuid}</td>
        <td>{r.visit_uuid}</td>
        <td>{r.visit_external_id}</td>
        <td> <a href={""}>{r.created_user.name} </a></td>
        <td>{moment(r.created).format('MM/DD/YYYY - h:mm a')}</td>
        <td>{moment(r.updated).format('MM/DD/YYYY - h:mm a')}</td>
      </tr>
    );
  }, this);

  return list;
}

class DatatableComponent extends React.Component {
  state = {
    visits: []
  }

  componentDidMount() {
    const state = this
    Instance.getRawConn().get('/v1/nemt/visits/').then((res) => {
      let visits = res.data;

      let visitlist = getDTList(visits);
      $.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');

      state.setState(Object.assign(state.state, { visits: visitlist }));
      $(ReactDOM.findDOMNode(state.example))
        .addClass('nowrap')
        .dataTable({
          responsive: true,
          dom: 'Bfrtip',
          buttons: [
            'copy', 'pdf'
          ],
          "bStateSave": true,
          details: {
            type: 'inline'
          },
          columnDefs: [
            { targets: [-1, -3], className: 'dt-body-right mdl-data-table__cell--non-numeric' }
          ]
        });
      state.decorateButtons();
      state.decorateSelect();
      state.decorateSearchBar();
      state.decorateColumns();
    }).catch((err) => { console.error(err); });
  }

  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>Visit Time</th>
            <th>Provider</th>
            <th>Member </th>
            <th>Ride</th>
            <th>Rides </th>
            <th>Subscriber ID</th>
            <th>Provider ID</th>
            <th>Visit ID</th>
            <th>External ID</th>
            <th>Scheduler</th>
            <th>Created</th>
            <th>Updated</th>
          </tr>
        </thead>
        <tbody>
          {this.state.visits}
        </tbody>
      </Table>

    );
    <BottomNavigationExampleSimple />

  }
}

export default class Datatablesjs extends React.Component {
  render() {
    return (
      <Row>
        <Col xs={12}>
          <PanelContainer>
            <Panel>
              <PanelBody>
                <Grid>
                  <Row>
                    <Col xs={12}>
                      <DatatableComponent />
                      <br />
                    </Col>
                  </Row>
                </Grid>
              </PanelBody>
            </Panel>
          </PanelContainer>
        </Col>
      </Row>
    );
  }
}
