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 Instance from '../../../../../../../components/Connection';

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

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 getDTList = function (provider) {
  let list = [];

  provider.forEach((r, i) => {
    list.push(
      <tr key={r.provider_uuid}>
        <td><a href="/#/app/table/rides" className="cancel_ride"><i className="material-icons">email</i></a>&nbsp;<a href={"/#/app/page/map/" + r.id}><i className="material-icons"><i className="material-icons">phone</i></i></a><a href="/#/app/table/rides" ><i className="material-icons">sms</i></a> </td>
        <td>12/17/2018</td>
        <td>11:14 AM CST</td>
        <td>SMS</td>
        <td>I need change!</td>
        <td>Member</td>
        {/* <td><a href="#"> Jane Doe</a> </td> */}
        <td><a href={"/#/app/member/" + r.user_id}>{r.memberName}</a></td>
        <td>Read</td>
        <td>Jane  Di Spachta</td>
        <td><a href="#">A33333JSJ999AQWS</a> </td>
        <td><a href="#">33JSJ93333JSJ999AQWS</a> </td>
        <td><a href="#">Rush Memorial Hospital</a> </td>
        <td><a href="#">93333JSJ999AQWSSSA</a> </td>
        {/* <td><a href={"/#/app/member/" + r.useruuid}>{r.name}</a></td>
        <td><a href={"/#/app/member/" + r.useruuid}>{r.member}</a></td>
        <td>{r.eligible} <a href=""><i className="material-icons">refresh</i></a> </td>
        <td><a href={"/#/app/member/" + r.useruuid}>{r.rides}</a></td>
        <td><a href={"/#/app/member/" + r.useruuid}>{r.home}</a></td>
        <td>{r.work}</td>
        <td>{r.phonenumber}<a href="/#/app/table/rides" ><i className="material-icons">phone</i></a> <a href="/#/app/table/rides" ><i className="material-icons">sms</i></a> </td>
        <td>{r.email}<a href="/#/app/table/rides" ><i className="material-icons">email</i></a> </td>
        <td>{r.gender}</td>
        <td>{r.birthdate}</td> */}


        {/* <td><a href={"/#/app/member/" + r.user_id}>{r.memberName}</a></td>
        <td><a href={"/#/app/member/" + r.user_id}>{r.member}</a></td>
        <td><NEMTLocation data={r} title={"Pickup"} value={""} buttonvalue={r.pickup} onPlaceChanged={handleProviderChanged} textSize={30} type="flat" /></td>
        <td><NEMTLocation data={r} title={"Destination"} value={""} buttonvalue={r.destination} onPlaceChanged={handleProviderChanged} textSize={30} locationType="provider" type="flat" /></td>
        <td><a href="/#/app/table/rides" ><i className="material-icons">phone</i></a> <a href="/#/app/table/rides" ><i className="material-icons">sms</i></a> {r.driver_name} | {r.driver_rating} stars </td>
         <td>{r.muk_id}</td>
        <td>{r.internal_id}</td>
        <td>{r.name}</td>
        <td>{r.address.street_address_1 + " " + (r.address.street_address_2 || "") + " - " + r.address.city + " - " + r.address.state + " (" + r.address.zipcode + ")"}</td>
        <td>{r.address.phone_number}</td> */}
      </tr>
    );
  }, this);

  return list;
}

class DatatableComponent extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
  }

  state = {
    providers: []
  }

  reloadTableData(names) {
    const table = $(ReactDOM.findDOMNode(self.example)).DataTable();
    table.clear();
    table.rows.add(names);
    table.draw();
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.newProviders && nextProps.newProviders.length > 0) {
      const self = this;
      Instance.getRawConn().get('/v1/nemt/provider/participating?sort=name').then((res) => {
        let providers = res.data;
        let newProv = nextProps.newProviders.map(p => {
          return [p.muk_id, p.internal_id, p.name, p.address.street_address_1 + " " + (p.address.street_address_2 || "") + " - " + p.address.city + " - " + p.address.state + " (" + p.address.zipcode + ")", p.address.phone_number];
        });

        const table = $(ReactDOM.findDOMNode(self.example)).DataTable();
        table.rows.add(newProv);
        providers = getDTList(providers)
        self.setState(Object.assign(self.state, { providers: providers }));
        table.draw(true);

        self.decorateButtons();
        self.decorateSelect();
        self.decorateColumns();
      }).catch((err) => { console.error(err); });
    }
  }

  componentWillUnmount() {
    $(ReactDOM.findDOMNode(this.example)).DataTable().destroy(true);
  }

  componentDidMount() {
    const state = this;

    Instance.getRawConn().get('/v1/nemt/provider/participating?sort=name').then((res) => {
      let providers = res.data;
      providers = getDTList(providers);
      state.setState(Object.assign(state.state, { providers: providers }));
      $(ReactDOM.findDOMNode(state.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], 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>Actions</th>
            <th>Date</th>
            <th>Time</th>
            <th>Type</th>
            <th>Message</th>
            <th>Source</th>
            <th>Member</th>
            <th>Dispatcher</th>
            <th>Status</th>
            <th>Visit</th>
            <th>Ride</th>
            <th>Provider</th>
            <th>Message ID</th>
            {/* <th>MUK</th>
          <th>Internal ID</th>
          <th>Name</th>
          <th>Address</th>
          <th>Phone</th> */}
          </tr>
        </thead>
        <tbody>
          {this.state.providers}
        </tbody>
      </Table>

    );
    <BottomNavigationExampleSimple />

  }
}

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

  state = {
    providerChange: [],
  }

  componentWillReceiveProps(nextProps) {
    let providers = nextProps.providerChange;
    this.setState(Object.assign(this.state, { providerChange: providers }));
  }

  componentDidMount() {
    let providers = this.props.providerChange;
    this.setState(Object.assign(this.state, { providerChange: providers }));
  }

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