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 { NEMTLocation } from '../../../../../components/NEMTLocation';
import ContactList from '../../../../../components/ContactList';
import Dialog from 'material-ui/Dialog';
import ActionGrade from 'material-ui/svg-icons/action/grade';
import MenuItem from 'material-ui/MenuItem';
import MoreHorizIcon from 'material-ui/svg-icons/navigation/more-horiz';
import IconMenu from 'material-ui/IconMenu';
import { grey400, darkBlack, lightBlack } from 'material-ui/styles/colors';
import Instance from '../../../../../../../components/Connection';

import ContentAdd from 'material-ui/svg-icons/content/add';

// const FloatingActionButtonExampleSimple = () => (
// <div>
// <FloatingActionButton style={{float:'left'}} secondary={true} href="/#/app/form/steppers/">
// <ContentAdd />
// </FloatingActionButton>
// </div>
// )

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


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

const getDTList = function (rides) {
let list = [];
rides.forEach((r, i) => {

var driverVehicle;
if (r.plate == null) { } else { driverVehicle = r.vehicle + ' | ' + r.plate };

var driverSummary;
if (r.driver_name == null) { driverSummary = "" } else { driverSummary = r.driver_name + ' | ' + r.driver_rating };

const iconButtonElement = (
<IconButton
style={{ padding: '0px', height: '20px' }}
touch={true}
tooltip="Actions"
tooltipPosition="top-left"
>
<MoreHorizIcon color={grey400} />
</IconButton>
);

const flatButtonElement = (
<FlatButton
style={{ padding: '0px', height: '20px' }}
touch={true}
tooltip="Actions"
tooltipPosition="top-left"
>
<MoreHorizIcon color={grey400} />
</FlatButton>
);


<FlatButton label="Actions" primary={true} />

let actionsMenu = [];

actionsMenu.push(
<MenuItem key='1' >
<a href={"/#/ride/" + r.id + "/" + r.user_id}>Ride</a>
</MenuItem>
);

actionsMenu.push(
<MenuItem key='2' >
<a href={"/#/app/page/map/" + r.id}> Ride Details </a>
</MenuItem>
);

actionsMenu.push(
<MenuItem key='3' >
<a href={"/#/app/table/visits"}>Visit </a>
</MenuItem>
);

actionsMenu.push(
<MenuItem key='4' onTouchTap={(e) => {
e.preventDefault();
this.handleShare(e);
return false;
}}>
<a href={location.href}> Share Ride </a>
</MenuItem>);

if (r.status.key !== 'canceled') {
actionsMenu.push(
<MenuItem key='5' >
<a href="/#/app/table/rides" className="cancel_ride"> Cancel</a>
</MenuItem>);
};





if (r.status.key === 'willCall') {
actionsMenu.push(
<MenuItem key='6' onTouchTap={(e) => {
e.preventDefault();
this.handleReady(e);
return false;
}}>
<a href={location.href}> Ready Now </a>
</MenuItem>);
}


 actionsMenu.push(
<MenuItem key='7' onTouchTap={(e) => {
e.preventDefault();
this.handleArchive(e);
 return false;
 }}>
 <a href={location.href}> Archive </a>
</MenuItem>);


list.push(
<tr key={r.id}>
<td>{r.time}</td>
<td>{r.status}</td>
<td>
{/* <a href={"/#/ride/" + r.id + "/" + r.user_id}>Ride</a> |
<a href={"/#/app/page/map/" + r.id}> Details | </a>
<a href={"/#/app/table/visits"}>Visit | </a> */}

<ContactList data={{
driverMobile: r.driver_phone,
memberMobile: r.mobile,
memberEmail: r.email,
schedulerEmail: r.scheduler_email,
schedulerMobile: r.scheduler_phone,
rideID: r.ride_uuid
}} />

<IconMenu iconButtonElement={iconButtonElement}>
{actionsMenu}
</IconMenu>
</td>
<td><NEMTLocation data={r} title={"Pickup"} value={""} buttonvalue={r.pickup} onPlaceChanged={handleProviderChanged} type="flat" /></td>
<td><NEMTLocation data={r} title={"Destination"} value={""} buttonvalue={r.destination} onPlaceChanged={handleProviderChanged} locationType="provider" type="flat" /></td>
<td><a href={"/#/app/member/" + r.user_id}>{r.memberName}</a></td>
<td>{r.trip_type}</td>
<td>{driverSummary} </td>
<td>{r.eta}</td>
<td>{r.duration} </td>
<td>{r.mileage}</td>
<td>{driverVehicle}</td>
<td><a href={"/#/app/member/" + r.user_id}>{r.member}</a></td>
<td> <a href={""}>{r.scheduler}</a></td>
<td>{r.visitExternalID}</td>
<td>{moment(r.created).format('MM/DD/YY, h:mm a')}</td>
<td>{moment(r.updated).format('MM/DD/YY, h:mm a')}</td>
{/* <td> <a href={""}>{r.created_user.name} </a></td> */}
</tr>
);
}, this);
return list;
}

class DatatableComponent extends React.Component {
state = {
items: [],
data: [],
list: [],
open: false,
archive:false,
confirmCancel: false,
message: "Are you sure you want to cancel this ride?"
}

componentDidMount() {
const state = this;
Instance.getRawConn().get('/v1/nemt/rides').then((res) => {
let riders = res.data.map(v => {
var data = {
open: 'false',
message: "Are you sure you want to Cancel this ride?",
id: v.ride_uuid,
user_id: v.user.useruuid,
memberName: v.user.last + ", " + v.user.first,
member: v.user.member,
time: '',
pickup: '',
destination: '',
status: v.status.value,
eta: '',
duration: 0,
mileage: '0 miles',
vehicle: v.vehicle.color + ' ' + v.vehicle.make + ' ' + v.vehicle.model,
plate: v.vehicle.license_plate,
mobile: v.user.phonenumber,
email: v.user.email,
scheduler_email: v.created_user.email,
scheduler_phone: v.created_user.phonenumber,
driver_name: v.driver.first_name,
driver_rating: v.driver.rating,
driver_phone: v.driver.phone_number,
lyftID: v.internal_id,
rideID: v.ride_uuid,
visitID: v.visit.visit_uuid,
visitExternalID: v.visit.visit_external_id,
action: '',
scheduler: v.created_user.last + ", " + v.created_user.first,
created: v.create_at,
updated: v.update_at,
confirmCancel: false,
trip_type: v.trip_type.value.replace(' / Will Call', ''),
};

if (v.pickup_time) data.time = new Date(v.pickup_time);
if (v.route.origin.name && v.route.origin.name !== '') data.pickup = v.route.origin.name;
else data.pickup = v.route.origin.address;

if (v.route.destination.name && v.route.destination.name !== '') data.destination = v.route.destination.name;
else data.destination = v.route.destination.address;

if (v.route.distance) data.mileage = v.route.distance + ' miles';
if (v.route.duration) data.duration = formatTime(v.route.duration);
if (v.route.eta) data.eta = formatTime(v.route.eta);

if (v.status.key === 'willCall') {
data.time = ''
} else {
data.time = moment(data.time).format('MM/DD/YY, h:mm a')
}
return data;
});

let list = getDTList(riders);

$.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, { list: list }));

// Delete a record



$(ReactDOM.findDOMNode(state.example)).on('click', 'menuitem.a.cancel_ride', function (e) {
e.preventDefault();


const table = $(ReactDOM.findDOMNode(state.example)).DataTable();
const obj = table.row($(this).closest('tr')).data();
state.setState(Object.assign(state.state, { open: true }));
// console.log(obj)
if (state.state.confirmCancel)
// if (true )
{
let rideID = obj.lyftID;
let url = '/v1/nemt/rides/' + rideID + '/cancel'
Instance.getRawConn().post(url).then(function (res) {
state.setState(Object.assign(state.state, { message: 'NEMT ride #' + rideID + ' has been cancelled' }));

console.log(res.data);
}).catch(function (err) {
state.setState(Object.assign(state.state, { message: 'Error: ' + JSON.stringify(res) }));

// alert('Error: ' + JSON.stringify(res));
console.error(err);
});
}
});

const dt = $(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], 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((err) => {
console.error('Error returned by getRides(): ', 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'
});
}

handleETA = (e) => {
e.preventDefault()
const state = this;
if (state.props.data !== undefined) {
state.setState(Object.assign(state.state, state.props.data));
}

if (state.state.eta) {
let rideID = state.state.ride.ride_uuid;
let message = 'Estimated Distance : ' + state.state.eta.distance_miles + ' miles\nEstimated Time: ' + state.state.eta.formatted_time

let url = '/v1/nemt/rides/' + rideID + '/message';
url = encodeURI(url);
Instance.getRawConn().post(url, { message: message }).then(function (res) {
alert('ETA Sent');
}).catch(function (err) {
console.error(err);
});
}
}

handleReady(e) {
let self = this;
Instance.getRawConn().post(`/v1/nemt/rides/${self.state.ride.ride_uuid}/ready`).then((res) => {
if (self.props.onRideChange) {
self.props.onRideChange(res.data);
}
self.setState(Object.assign(self.state, { dialogMessage: `You ride has been requested`, dialogTitleMessage: 'Return Ride', dialogOpen: true, dialogType: 'OK' }));
}).catch(console.error);
}

handleClose(e) {
let self = this;
self.setState(Object.assign(self.state, { dialogMessage: `Do you want to cancel the this ride?`, dialogTitleMessage: 'Cancel Ride', dialogOpen: false }));
}

handleCancel(e) {
let self = this;
self.setState(Object.assign(self.state, {
dialogMessage: `Do you want to cancel the this ride?`, dialogTitleMessage: 'Cancel Ride', dialogOpen: true, dialogType: 'YesNo'
}));
}

handleArchive = () => {
this.setState(Object.assign({ archive: true }));
console.log('handleArchive')
};

handleOpen = () => {
this.setState(Object.assign({ open: true }));
console.log('handleOpen')
};

handleCloseYes = () => {
this.setState(Object.assign({ confirmCancel: true, open: false }));
console.log('handleCloseYes')
};

handleClose = () => {
this.setState(Object.assign({ confirmCancel: false, open: false }));
// this.setState({ open: false, confirmCancel:false });
console.log('handleClose')
};

render() {
const actions = [
<FlatButton
label="Yes"
primary={true}
onClick={this.handleCloseYes}
// onClick = {state.setState(Object.assign(state, { open: true }))}

/>,
<FlatButton
label="No"
secondary={true}
onClick={this.handleClose}
/>,
];

return (
<div>
<Dialog
title="Cancel Ride"
actions={actions}
modal={false}
open={this.state.open}
onRequestClose={this.handleClose}
>
{this.state.message}
</Dialog>
{/* < FloatingActionButtonExampleSimple /> */}
<Table ref={(c) => this.example = c} className='display' cellSpacing='0' width='100%'>
<thead>
<tr>
<th>Pickup Time</th>
<th>Status</th>
<th>Actions</th>
<th>Origin</th>
<th>Destination</th>
<th>Member</th>
<th>Ride Type</th>

{/* <th>Destination</th> */}
<th>Driver</th>
<th>ETA</th>
<th>Duration</th>
<th>Mileage</th>
<th>Vehicle</th>
<th>Member ID</th>
<th>Scheduler</th>
<th>External ID</th>
<th>Created</th>
<th>Updated</th>

</tr>
</thead>
<tbody>
{this.state.list}
</tbody>
</Table>
</div>
);
<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>
);
}
}