import React, { Component } from 'react';
import QueueAnim from 'rc-queue-anim';
import AutoComplete from 'material-ui/AutoComplete';
import { Tabs, Tab } from 'material-ui/Tabs';
import Slider from 'material-ui/Slider';
import TimePicker from 'material-ui/TimePicker';
import DatePicker from 'material-ui/DatePicker';
import TextField from 'material-ui/TextField';
import Toggle from 'material-ui/Toggle';
import Snackbar from 'material-ui/Snackbar';
import { RadioButton, RadioButtonGroup } from 'material-ui/RadioButton';
import MenuItem from 'material-ui/MenuItem';
import SelectField from 'material-ui/SelectField';
import DropDownMenu from 'material-ui/DropDownMenu';
import { List, ListItem } from 'material-ui/List';
import ListExampleSimple from '../../../../ui/routes/lists/components/Simple';
import ListExampleMessages from '../../../../ui/routes/lists/components/Messages';
import Dialog from 'material-ui/Dialog';
import ToolbarSection from '../../../../ui/routes/components/components/Toolbar2.js';
import BottomNavigationExampleSimple from '../../../../ui/routes/components/components/BottomNavigation';
import { NEMTLocation } from '../../../../../components/NEMTLocation';
import RoadTripLink from '../../../../../components/RoadtripLink';
import GMaps from './Maps'
import Drawer from 'material-ui/Drawer';
import AppBar from 'material-ui/AppBar';
import RaisedButton from 'material-ui/RaisedButton';
import FlatButton from 'material-ui/FlatButton';
import Divider from 'material-ui/Divider';
import IconMenu from 'material-ui/IconMenu';
import IconButton from 'material-ui/IconButton';
import Download from 'material-ui/svg-icons/file/file-download';
import ArrowDropRight from 'material-ui/svg-icons/navigation-arrow-drop-right';
// import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import ActionHome from 'material-ui/svg-icons/action/home';
import ActionWork from 'material-ui/svg-icons/action/work';
import MapsMyLocation from 'material-ui/svg-icons/maps/my-location';
import MapsAddLocation from 'material-ui/svg-icons/maps/add-location';
import MapsNearMe from 'material-ui/svg-icons/maps/near-me';
import MapsLocalHospital from 'material-ui/svg-icons/maps/local-hospital';
import MapsLocalPharrmacy from 'material-ui/svg-icons/maps/local-pharmacy';
import ActionGrade from 'material-ui/svg-icons/action/grade';
import { fullWhite } from 'material-ui/styles/colors';
import ActionAndroid from 'material-ui/svg-icons/action/android';
import FontIcon from 'material-ui/FontIcon';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import MuiGeoSuggest from 'material-ui-geosuggest';
import { orange500, blue500 } from 'material-ui/styles/colors';
import areIntlLocalesSupported from 'intl-locales-supported';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import ContentAdd from 'material-ui/svg-icons/content/add';
import moment from 'moment';
import { Card, CardActions, CardHeader, CardMedia, CardTitle, CardText } from 'material-ui/Card';
import Draggable, { DraggableCore } from 'react-draggable'; // Both at the same time
import Imgix from 'react-imgix'
import Paper from 'material-ui/Paper';

import { grey400, darkBlack, lightBlack } from 'material-ui/styles/colors';

import MoreHorizIcon from 'material-ui/svg-icons/navigation/more-horiz';

import Instance from '../../../../../../../components/Connection';
import ContactList from '../../../../../../app/components/ContactList';
let DateTimeFormat;

if (areIntlLocalesSupported(['fr', 'fa-IR'])) {
  DateTimeFormat = global.Intl.DateTimeFormat;
}


const styles = {
  errorStyle: {
    color: orange500,
  },
  underlineStyle: {
    borderColor: orange500,
  },
  floatingLabelStyle: {
    color: blue500,
  },
  floatingLabelFocusStyle: {
    color: blue500,
  },
};

const style = {
  opacity: '.95',
  margin: '3',
  padding: '4',
  height: '65px'
};

const buttonStyle = {
  marginTop: 10,
};

const getConfirmationData = () => {
  let confirmationData = {
    rideTypeValue: 0,
    providerID: 0,
    providerName: '',
    visitDate: null,
    visitTime: null,
    pickupLocation: null,
    pickupTime: null,
    user: null
  };

  const confirmationStorage = localStorage.getItem("confirmation");
  if (confirmationStorage !== undefined && confirmationStorage !== null && confirmationStorage !== '') {
    confirmationData = Object.assign(confirmationData, JSON.parse(confirmationStorage));
  }

  let user = localStorage.getItem("userData")
  if (user && user !== null && user !== '') {
    user = JSON.parse(user);
    confirmationData = Object.assign(confirmationData, { user: user });
  }

  return confirmationData;
};

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

    this.state = {
      stepIndex: 0,
      rideTypeValue: 0,
      providerID: 0,
      providerName: '',
      visitDate: null,
      visitTime: null,
      pickupLocation: null,
      pickupTime: null,
      origin: {},
      destination: {},
      user: {
        first: "",
        last: "",
        member: "",
        phonenumber: ""
      },
      eta: {
        distance_miles: 0,
        duration_seconds: 0,
        formatted_time: ""
      },
      ride: {
        "ride_uuid": "",
        "user": {
          "useruuid": "",
          "name": "",
          "member": ""
        },
        "status": {
          "key": "",
          "value": ""
        },
        "type": {
          "key": "",
          "value": ""
        },
        "notes": "",
        "passenger": {
          "user_id": "",
          "image_url": "",
          "first_name": "",
          "last_name": "",
          "phone_number": ""
        },
        "driver": {
          "rating": "",
          "image_url": "",
          "first_name": "",
          "phone_number": ""
        },
        "vehicle": {
          "color": "",
          "make": "",
          "license_plate": "",
          "image_url": "",
          "year": 0,
          "license_plate_state": "",
          "model": ""
        },
        "route": {
          "origin": {
            "name": "",
            "lat": 0,
            "lng": 0,
            "address": ""
          },
          "destination": {
            "name": "",
            "lat": 0,
            "lng": 0,
            "address": ""
          },
          "location": {
            "lat": 0,
            "lng": 0,
            "bearing": 0
          },
          "route_kml": "",
          "distance": 0,
          "duration": 0,
          "eta": 0,
          "eta_formatted": '',
        },
        "trip_type": {
          "key": "",
          "value": "",
        },
        "visit": {
          "visit_uuid": "",
          "visit_external_id": "",
          "pickup": {
            "id": "",
            "name": ""
          },
          "destination": {
            "id": "",
            "name": ""
          },
          "provider": {
            "provider_uuid": "",
            "name": ""
          },
          "created_user": {
            "useruuid": "",
            "name": ""
          },
          "trip_type": {
            "key": "",
            "value": "",
          },
        },
        "visit_date": new Date(),
        "visit_time": new Date(),
        "pickup_time": new Date()
      },
      rideInfo: {
        "ride_uuid": "",
        "user": {
          "useruuid": "",
          "name": "",
          "member": ""
        },
        "status": {
          "key": "",
          "value": ""
        },
        "type": {
          "key": "",
          "value": ""
        },
        "route_kml": "",
        "notes": "",
        "passenger": {
          "user_id": "",
          "image_url": "",
          "first_name": "",
          "last_name": "",
          "phone_number": ""
        },
        "driver": {
          "rating": "",
          "image_url": "",
          "first_name": "",
          "phone_number": ""
        },
        "vehicle": {
          "color": "",
          "make": "",
          "license_plate": "",
          "image_url": "",
          "year": 0,
          "license_plate_state": "",
          "model": ""
        },
        "route": {
          "origin": {
            "name": "",
            "lat": 0,
            "lng": 0,
            "address": ""
          },
          "destination": {
            "name": "",
            "lat": 0,
            "lng": 0,
            "address": ""
          }
        }
      }
    }
    this.handleRide = this.handleRide.bind(this);
    this.handleCancel = this.handleCancel.bind(this);
    this.handleClose = this.handleClose.bind(this);
    this.handleYes = this.handleYes.bind(this);
    this.handleReady = this.handleReady.bind(this);
    this.handleShare = this.handleShare.bind(this);
    // this.handleRideChange = this.handleRideChange.bind(this);

  }

  static propTypes = {
    data: React.PropTypes.object.isRequired,
    params: React.PropTypes.object.isRequired,
  }

  componentWillReceiveProps(nextProps) {
    let params = nextProps.params;
    params.visit_date = new Date(params.visit_date);
    params.visit_time = new Date(params.visit_time);
    params.pickup_time = new Date(params.pickup_time);


    if (!params.visit.provider.provider_uuid) params.visit.provider.provider_uuid = "";
    if (!params.visit.pickup.id) params.visit.pickup.id = "";
    if (!params.route.eta) params.route.eta = 0;

    var minutes = Math.floor(params.route.eta / 60);
    var seconds = params.route.eta % 60;
    var formattedTime = `${minutes} minutes`
    if (minutes > 10) {
      var t = new Date();
      t.setSeconds(t.getSeconds() + params.route.eta);
      formattedTime = moment(t).format("hh:mm a");
    }

    params.route.eta_formatted = formattedTime;

    this.setState(Object.assign(this.state, { ride: params }));
  }

  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'
    }));
  }

  handleYes(e) {
    let self = this;
    self.setState(Object.assign(self.state, { dialogMessage: `Do you want to cancel the this ride?`, dialogTitleMessage: 'Cancel Ride', dialogOpen: false }));
    let url = '/v1/nemt/rides/' + self.state.ride.ride_uuid + '/cancel'
    Instance.getRawConn().post(url).then(function (res) {
      self.setState(Object.assign(self.state, { dialogMessage: `You ride has been canceled`, dialogTitleMessage: 'Canceled Ride', dialogOpen: true, dialogType: 'OK' }));
    }).catch(console.error);
  }

  handleShare(e) {
    let self = this;
    let url = '/v1/nemt/rides/' + self.state.ride.ride_uuid + '/share'
    Instance.getRawConn().post(url).then(function (res) {
      self.setState(Object.assign(self.state, { dialogMessage: `This ride has been shared with the member`, dialogTitleMessage: 'Shared Ride', dialogOpen: true, dialogType: 'OK' }));
    }).catch(console.error);
  }


  handleRideChange(r) {
    if (this.props.onRideUpdate) {
      this.props.onRideUpdate(r);
    }
  }

  componentDidMount() {
    let data = this.props.data;
    data.visitDate = new Date(data.visitDate);
    data.visitTime = new Date(data.visitTime);
    data.pickupTime = new Date(data.pickupTime);

    this.setState(Object.assign(this.state, data));

    let params = this.props.params;
    params.visit_date = new Date(params.visit_date);
    params.visit_time = new Date(params.visit_time);
    params.pickup_time = new Date(params.pickup_time);

    if (!params.visit.provider.provider_uuid) params.visit.provider.provider_uuid = "";
    if (!params.visit.pickup.id) params.visit.pickup.id = "";
    if (!params.route.eta) params.route.eta = 0;

    var minutes = Math.floor(params.route.eta / 60);
    var seconds = params.route.eta % 60;
    var formattedTime = `${minutes} minutes`
    if (minutes > 10) {
      var t = new Date();
      t.setSeconds(t.getSeconds() + params.route.eta);
      formattedTime = moment(t).format("hh:mm a");
    }

    params.route.eta_formatted = formattedTime;

    this.setState(Object.assign(this.state, { ride: params }));
  }

  handlePickupChanged(res, state) {
    let route = state.state.ride.route;
    route.origin = {
      name: res.name,
      lat: res.lat,
      lng: res.lng,
      address: res.address
    }

    let ride = state.state.ride;
    ride.route = route;

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

  handleProviderChanged(res, state) {

    let route = state.state.ride.route;
    route.destination = {
      name: res.name,
      lat: res.lat,
      lng: res.lng,
      address: res.address
    }

    let ride = state.state.ride;
    ride.route = route;

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

  handleStatusChange(event, index, value, state) {
    let self = state;
    let ride = this.state.ride;
    ride.status.key = value;
    ride.status.value = event.target.innerText;

    Instance.getRawConn().get(`/v1/lyfthook/${ride.ride_uuid}/${ride.status.key}`).then(res => {
      res.data.visitDate = new Date(res.data.visitDate);
      res.data.visitTime = new Date(res.data.visitTime);
      res.data.pickupTime = new Date(res.data.pickupTime);

      var minutes = Math.floor(res.data.route.eta / 60);
      var seconds = res.data.route.eta % 60;
      var formattedTime = `${minutes} minutes`
      if (seconds > 0) {
        formattedTime += ` ${seconds} seconds`
      }
      res.data.route.eta_formatted = formattedTime;

      self.setState(Object.assign(self.state, {
        ride: res.data,
      }))
    }).catch(err => {
      console.error(err);
    });
  }

  handleRide(ride) {
    if (this.props.onRideChange) {
      this.props.onRideChange(ride);
    }
    //this.setState(Object.assign(this.state, { ride: ride }));
    //location.href = "/#/app/page/map/" + ride.ride_uuid;
  }

  render() {
    const rightStyle = {
      width: '80px',
      margin: '0 5px 0 10px'
    }

    const imageStyle = { width: "64px", height: "40px" }
    const carImageStyle = { width: "50px", height: "22px" }
    let data = this.state.ride.route;


    let rideDetails = (
      <Card
        style={{
          float: 'left',
          fontSize: '6',
          opacity: '1',
          top: '55px',
          left: '8px',
          top: '60px',
          left: '10px',
          position: 'fixed',
          padding: '0px',
          paddingLeft: '4px',

        }}
      >
        <CardHeader
          title="Details"
          // actAsExpander
          showExpandableButton
          titleColor="#424242"
          subtitleColor="#424242"
          style={{
            opacity: '1', fontSize: '7px', padding: '5px !important', color: '#424242', borderRadius: '30', height: 'auto',
            width: '85'
          }}
        />
        <CardText
          expandable
          style={{ color: '#424242', fontSize: '7px', borderRadius: '20px' }}
        >

          <table className="mdl-data-table table-bordered table-striped cf no-margin" style={{ backgroundColor: 'white' }}>

            <tr className="">
              <td style={{ fontWeight: 'bold' }} >MemberID</td>
              <td className="">
                {this.state.ride.user.member}
              </td>
            </tr>

            <tr className="">
              <td style={{ fontWeight: 'bold' }} >RideID</td>
              <td className="">
                {this.state.ride.ride_uuid}
              </td>
            </tr>

            <tr className="">
              <td style={{ fontWeight: 'bold' }} >Status</td>
              <td>
                <DropDownMenu
                  value={this.state.ride.status.value}
                  onChange={(e, i, v) => { this.handleStatusChange(e, i, v, this) }}
                >
                  <MenuItem value={'accepted'} primaryText="Accepted" />
                  <MenuItem value={'scheduled'} primaryText="Scheduled" />
                  <MenuItem value={'canceled'} primaryText="Canceled" />
                  <MenuItem value={'pending'} primaryText="Pending" />
                  <MenuItem value={'arrived'} primaryText="Arrived" />
                  <MenuItem value={'pickedUp'} primaryText="Picked Up" />
                  <MenuItem value={'droppedOff'} primaryText="Dropped Off" />
                </DropDownMenu></td>
            </tr>

            <tr className="">
              <td style={{ fontWeight: 'bold' }} >Distance</td>
              <td className="">{this.state.ride.route.distance} miles</td>
            </tr>

            <tr className="">
              <td style={{ fontWeight: 'bold' }} >Duration</td>
              <td className="">{moment(this.state.ride.route.duration).format("hh:mm")}</td>
            </tr>

            <tr className="">
              <td style={{ fontWeight: 'bold' }} >ETA</td>
              <td className="">{this.state.ride.route.eta_formatted}</td>
            </tr>

            <tr className="">
              <td style={{ fontWeight: 'bold' }} >Provider ID</td>
              <td className="">{this.state.ride.visit.provider.provider_uuid} </td>
            </tr>

            <tr className="">
              <td style={{ fontWeight: 'bold' }} >Provider</td>
              <td className="">{this.state.ride.visit.provider.name} </td>
            </tr>

            <tr className="">
              <td style={{ fontWeight: 'bold' }} >Visit ID</td>
              <td className="">
                {this.state.ride.visit.visit_uuid}
              </td>
            </tr>

            <tr className="">
              <td style={{ fontWeight: 'bold' }} >Visit External ID</td>
              <td className="">{this.state.ride.visit.visit_external_id} </td>
            </tr>

            <tr className="">
              <td style={{ fontWeight: 'bold' }} >Notes</td>
              <td className="">{this.state.ride.notes}</td>
            </tr>

            <tr className="">
              <td style={{ fontWeight: 'bold' }} >Scheduler</td>
              <td className="numeric">{this.state.ride.visit.created_user.name}</td>
            </tr>
          </table>

        </CardText>
      </Card>
    )

    let scaledImage = (<Imgix src={this.state.ride.vehicle.image_url} width={50} type='img' />);

    var currentStatus = this.state.ride.status.key;

    let vehicleSummary;

    if (currentStatus !== 'pending' && currentStatus !== 'scheduled' && currentStatus !== 'willCall') {
      vehicleSummary = this.state.ride.vehicle.color + ' ' + this.state.ride.vehicle.make + ' ' + this.state.ride.vehicle.model + '(' + this.state.ride.vehicle.license_plate + ')'
    }
    else { vehicleSummary = 'not assigned' }

    const rideContactList = {
      driverMobile: this.state.ride.driver.phone_number,
      memberMobile: this.state.ride.driver.phone_number,

      // memberMobile:  this.state.ride.passenger.phone_number,

      memberEmail: this.state.ride.user.memberEmail,
      // schedulerEmail:  this.state.ride.user.created_user.schedulerEmail,
      schedulerEmail: "this.state.ride.user.created_user.schedulerEmail",
      // this.state.schedulerEmail,
      // this.state.schedulerEmail,
      schedulerMobile: "this.state.schedulerEmail",
      rideID: "w232323232323",
    };

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

    let actionsMenu = [];
    if (this.state.ride.visit.rides) {
      this.state.ride.visit.rides.forEach(r => {
        if (r.ride_uuid !== this.state.ride.ride_uuid) {
          const url = `/#/app/page/map/${r.ride_uuid}`
          let menuItem = (
            <MenuItem onTouchTap={(e) => {
              e.preventDefault();
              if (this.props.onRideChange) {
                this.props.onRideChange(r);
              }
              location.href = url;
              return false;
            }} >
              <a href={url}> {r.trip_type.value.replace(' / Will Call', '')} </a>
            </MenuItem>
          )

          actionsMenu.push(menuItem);
        }
      }, this);
    }

    // actionsMenu.push(<MenuItem>
    //   <ContactList data={rideContactList} />
    // </MenuItem>);

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

    if (this.state.ride.status.key !== 'canceled') {
      actionsMenu.push(
        <MenuItem onTouchTap={(e) => {
          e.preventDefault();
          this.handleCancel(e);
          return false;
        }}>
          <a href={location.href}> Cancel Ride </a>
        </MenuItem>);
    }

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

    const rightIconMenu = (
      <IconMenu iconButtonElement={iconButtonElement}>
        {actionsMenu}
      </IconMenu>
    );

    let actions = []

    if (this.state.dialogType == 'YesNo') {
      actions = [
        <FlatButton
          label="Yes"
          primary={true}
          onClick={this.handleYes}
        />,
        <FlatButton
          label="No"
          secondary={true}
          onClick={this.handleClose}
        />,
      ];
    } else {
      actions = [
        <FlatButton
          label="OK"
          secondary={true}
          onClick={this.handleClose}
        />,
      ];
    }

    let actionButtons = [];
    if (this.state.ride.status.key !== 'canceled' && this.state.ride.status.key !== 'droppedOff') {
      actionButtons = [
        <RaisedButton
          label="I am Ready"
          primary={true}
          onTouchTap={this.handleReady}
          disabled={true}
        />,
        <RaisedButton
          label="Cancel"
          style={{ margintop: '0px' }}
          primary={false}
          onTouchTap={this.handleCancel}
        />
      ]
    }

    let carInfo = (
      <tr >
        <td style={{ fontWeight: 'normal', color: '#424242', borderColor: '#212121', borderWidth: '1px', borderRadius: '12px', borderStyle: 'solid', paddingLeft: '4px', paddingRight: '4px', fontSize: '10px' }} className="numeric">{this.state.ride.passenger.first_name} {this.state.ride.passenger.last_name}</td>
        <td style={{ fontWeight: 'bold', color: '#2077db', borderColor: '#212121', borderWidth: '1px', borderRadius: '12px', borderStyle: 'solid', paddingLeft: '4px', paddingRight: '4px', fontSize: '10px' }} className="numeric">
          {this.state.ride.status.value}
        </td>

        <td style={{ fontWeight: 'normal', color: '#424242', borderColor: '#212121', borderWidth: '1px', borderRadius: '12px', borderStyle: 'solid', paddingLeft: '4px', paddingRight: '4px', fontSize: '10px' }} className="numeric">
          {this.state.ride.trip_type.value.replace(' / Will Call', '')}
        </td>

        <td style={{ fontWeight: 'normal', color: '#424242', borderColor: '#212121', borderWidth: '1px', borderRadius: '12px', borderStyle: 'solid', paddingLeft: '4px', paddingRight: '4px', fontSize: '10px' }} className="numeric">
          {rightIconMenu} <ContactList data={rideContactList} />
        </td>

        <td style={{ fontWeight: 'normal', color: '#424242', borderColor: '#212121', borderWidth: '1px', borderRadius: '12px', borderStyle: 'solid', paddingLeft: '4px', paddingRight: '4px', fontSize: '10px' }} className="numeric">
          {vehicleSummary}
        </td>


        <td style={{ fontWeight: 'bold', color: '#2077db', borderColor: '#212121', borderWidth: '1px', borderRadius: '12px', borderStyle: 'solid', paddingLeft: '4px', paddingRight: '4px', fontSize: '10px' }} className="numeric">{this.state.ride.route.eta_formatted}</td>

      </tr>
    );
    if (this.state.ride.status.key === "pending" || this.state.ride.status.key === "willCall" || this.state.ride.status.key === "scheduled" || this.state.ride.status.key === "canceled") {
      carInfo = (
        <tr >
          <td style={{ fontWeight: 'normal', color: '#424242', borderColor: '#212121', borderWidth: '1px', borderRadius: '12px', borderStyle: 'solid', paddingLeft: '4px', paddingRight: '4px', fontSize: '10px' }} className="numeric">{this.state.ride.passenger.first_name} {this.state.ride.passenger.last_name}</td>
          <td style={{ fontWeight: 'normal', color: '#424242', borderColor: '#212121', borderWidth: '1px', borderRadius: '12px', borderStyle: 'solid', paddingLeft: '4px', paddingRight: '4px', fontSize: '10px' }} className="numeric">
            {this.state.ride.status.value}
          </td>
          <td style={{ fontWeight: 'normal', color: '#424242', borderColor: '#212121', borderWidth: '1px', borderRadius: '12px', borderStyle: 'solid', paddingLeft: '4px', paddingRight: '4px', fontSize: '10px' }} className="numeric">
            {this.state.ride.trip_type.value.replace(' / Will Call', '')}
          </td>
          <td style={{ fontWeight: 'normal', color: '#424242', borderColor: '#212121', borderWidth: '1px', borderRadius: '12px', borderStyle: 'solid', paddingLeft: '4px', paddingRight: '4px', fontSize: '10px' }} className="numeric">
            {rightIconMenu} <ContactList data={rideContactList} />
          </td>
          <td style={{ fontWeight: 'normal', color: '#424242', borderColor: '#212121', borderWidth: '1px', borderRadius: '12px', borderStyle: 'solid', paddingLeft: '4px', paddingRight: '4px', fontSize: '10px' }} className="numeric"></td>
          <td style={{ fontWeight: 'normal', color: '#424242', borderColor: '#212121', borderWidth: '1px', borderRadius: '12px', borderStyle: 'solid', paddingLeft: '4px', paddingRight: '4px', fontSize: '10px' }} className="numeric"></td>
        </tr>)
    }

    let statusSummary = (
      <Paper style={{ opacity: '.85', margin: '3', padding: '3', height: '55px' }} zDepth={1} >
        <table className="cf" style={{ fontSize: '11px', margin: '0px', border: '0px', padding: '0px !important', opacity: .9 }}>
          <thead >
            <tr style={{ height: '10px' }}>
              <th style={{ borderColor: '#212121', borderWidth: '1px', borderRadius: '12px', borderStyle: 'solid', paddingLeft: '4px', paddingRight: '4px', fontSize: '10px' }}>Member </th>
              <th style={{ borderColor: '#212121', borderWidth: '1px', borderRadius: '12px', borderStyle: 'solid', paddingLeft: '4px', paddingRight: '4px', fontSize: '10px' }}>Status</th>
              <th style={{ borderColor: '#212121', borderWidth: '1px', borderRadius: '12px', borderStyle: 'solid', paddingLeft: '4px', paddingRight: '4px', fontSize: '10px' }}>Type</th>
              <th style={{ borderColor: '#212121', borderWidth: '1px', borderRadius: '12px', borderStyle: 'solid', paddingLeft: '4px', paddingRight: '4px', fontSize: '10px' }}>Actions</th>

              <th style={{ borderColor: '#212121', borderWidth: '1px', borderRadius: '12px', borderStyle: 'solid', paddingLeft: '4px', paddingRight: '4px', fontSize: '10px' }}>Vehicle</th>

              <th style={{ borderColor: '#212121', borderWidth: '1px', borderRadius: '12px', borderStyle: 'solid', paddingLeft: '4px', paddingRight: '4px', fontSize: '10px' }}>ETA</th>


            </tr>
          </thead>
          <tbody>
            {carInfo}
          </tbody>
        </table>

      </Paper>

    )

    let pickupTime = (<TimePicker
      disabled={false}
      floatingLabelText="Pickup"
      floatingLabelFixed={true}
      underlineShow={false}
      id='pickupTimePicker'
      hintText="Pickup Time"
      format="ampm"
      minutesStep={5}
      value={this.state.ride.pickup_time}
      textFieldStyle={{ height: '48px', fontSize: '14px', width: '70px', color: '#424242' }}
      style={{ width: '100px', color: 'rgba(0, 153, 204) !important' }}
    />)
    if (this.state.ride.status.key === 'willCall') {
      pickupTime = (<TextField hintText="Pickup" underlineShow={false} floatingLabelText="Pickup" value={"Will Call"} disabled={true} style={{ fontSize: '12px' }} />);
    }

    let pickupNEMTLocation = (<NEMTLocation type="flat" data={data} title={'Pickup'} value={""} buttonvalue={this.state.ride.route.origin.name} onPlaceChanged={(event) => this.handlePickupChanged(event, this)} textSize={35} locationType={"pickup"} icon={<MapsAddLocation color={fullWhite} />} />)
    let destinationNEMTLocation = (<NEMTLocation type="flat" disabled={true} data={data} title={"Destination"} value={""} buttonvalue={this.state.ride.route.destination.name} onPlaceChanged={(event) => this.handleProviderChanged(event, this)} textSize={25} locationType={"provider"} icon={<MapsNearMe color={fullWhite} />} />);
    let visitTime = (<TimePicker
      disabled={false}
      floatingLabelText="Visit Time"
      floatingLabelFixed={true}
      format="ampm"
      hintText="Visit Time"
      underlineShow={false}
      textFieldStyle={{ height: '48px', fontSize: '14px', width: '80px', color: 'rgb(222, 153, 204) !important' }}
      value={this.state.ride.visit_time}
      onChange={this.handleTime}
      minutesStep={5}
    />)
    if (this.state.ride.trip_type.key === 'from_visit' || this.state.ride.trip_type.key === 'from_visit_call') {
      visitTime = null;

      pickupNEMTLocation = (<NEMTLocation type="flat" data={data} title={'Pickup'} value={""} buttonvalue={this.state.ride.route.destination.name} onPlaceChanged={(event) => this.handlePickupChanged(event, this)} textSize={35} locationType={"provider"} icon={<MapsAddLocation color={fullWhite} />} />)
      destinationNEMTLocation = (<NEMTLocation type="flat" disabled={true} data={data} title={"Destination"} value={""} buttonvalue={this.state.ride.route.origin.name} onPlaceChanged={(event) => this.handleProviderChanged(event, this)} textSize={25} locationType={"pickup"} icon={<MapsNearMe color={fullWhite} />} />);
    }

    return (
      <article className="article padding-sm-v article-bordered">
        {statusSummary}
        {rideDetails}
        <GMaps data={this.state.ride} />
        <div className="container-fluid with-maxwidth" style={{ float: 'right', bottom: '0px', padding: '0px', maxWidth: '300px' }} >
          <Paper style={style} zDepth={5} >
            <div className="float-left">
              <DatePicker
                formatDate={new DateTimeFormat('en-US', {
                  weekday: 'short',
                  day: 'numeric',
                  month: 'long',
                }).format}
                disabled={false}
                underlineShow={false}
                id='pickupDatePicker'
                hintText="Ride Date"
                firstDayOfWeek={0}
                container="inline"
                textFieldStyle={{ width: '90px', height: '30px', fontSize: '12px' }}
                floatingLabelStyle={styles.floatingLabelStyle}
                floatingLabelFocusStyle={styles.floatingLabelFocusStyle}
                value={this.state.ride.visit_date}
              />
              {pickupNEMTLocation}
            </div>
            <div className="float-right" style={rightStyle}>
              {pickupTime}
            </div>
          </Paper>

          <Paper style={style} zDepth={2} >
            <div className="float-left">
              <DatePicker
                formatDate={new DateTimeFormat('en-US', {
                  weekday: 'short',
                  day: 'numeric',
                  month: 'long',
                }).format}
                disabled={false}
                id='pickupDatePicker'
                underlineShow={false}
                hintText="Visit Date"
                firstDayOfWeek={0}
                container="inline"
                textFieldStyle={{ height: '30px', width: '90px', fontSize: '12px' }}
                floatingLabelStyle={styles.floatingLabelStyle}
                floatingLabelFocusStyle={styles.floatingLabelFocusStyle}
                value={this.state.ride.visit_date}
              />
              {destinationNEMTLocation}
            </div>

            <div className="float-right" style={rightStyle}>
              {visitTime}
            </div>

          </Paper>

        </div>
        <Dialog
          title={this.state.dialogTitleMessage}
          actions={actions}
          modal={false}
          open={this.state.dialogOpen}
          onRequestClose={this.handleClose}
        >
          {this.state.dialogMessage}
        </Dialog>

      </article>
    )
  }
}

class Page extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      timeout: null,
      ride: {
        "ride_uuid": "",
        "user": {
          "useruuid": "",
          "name": "",
          "member": ""
        },
        "status": {
          "key": "",
          "value": ""
        },
        "type": {
          "key": "",
          "value": ""
        },
        "notes": "",
        "passenger": {
          "user_id": "",
          "image_url": "",
          "first_name": "",
          "last_name": "",
          "phone_number": ""
        },
        "driver": {
          "rating": "",
          "image_url": "",
          "first_name": "",
          "phone_number": ""
        },
        "vehicle": {
          "color": "",
          "make": "",
          "license_plate": "",
          "image_url": "",
          "year": 0,
          "license_plate_state": "",
          "model": ""
        },
        "route": {
          "origin": {
            "name": "",
            "lat": 0,
            "lng": 0,
            "address": ""
          },
          "destination": {
            "name": "",
            "lat": 0,
            "lng": 0,
            "address": ""
          },
          "location": {
            "lat": 0,
            "lng": 0,
            "bearing": 0
          },
          "route_kml": "",
          "distance": 0,
          "duration": 0,
          "eta": 0
        },
        "trip_type": {
          "key": "",
          "value": "",
        },
        "visit": {
          "visit_uuid": "",
          "visit_external_id": "",
          "pickup": {
            "id": "",
            "name": ""
          },
          "destination": {
            "id": "",
            "name": ""
          },
          "provider": {
            "provider_uuid": "",
          },
          "created_user": {
            "useruuid": "",
            "name": ""
          },
          "trip_type": {
            "key": "",
            "value": "",
          },
        },
        "visit_date": new Date(),
        "visit_time": new Date(),
        "pickup_time": new Date(),
      }
    }

    this.handleRide = this.handleRide.bind(this);

    // this.handleCancel = this.handleCancel.bind(this);
    // this.handleClose = this.handleClose.bind(this);
    // this.handleYes = this.handleYes.bind(this);
    // this.handleReady = this.handleReady.bind(this);
    // this.handleRideChange = this.handleRideChange.bind(this);
    // this.refreshContent = this.refreshContent.bind(this);
  }

  componentDidMount() {
    this.refreshContent(this.props.params.ride_uuid);
  }

  refreshContent(rideID) {
    const self = this;
    Instance.getRawConn().get('/v1/nemt/rides/' + rideID + '/eta').then((res) => {
      self.setState(Object.assign(self.state, { ride: res.data }));
      switch (self.state.ride.status.key) {
        case "scheduled":
        case "accepted":
        case "arrived":
        case "pickedUp":
        case "pending":

          const timeout = setTimeout(function () {
            self.refreshContent(rideID);
          }.bind(this), 30000);
          self.setState(Object.assign(self.state, { timeout: timeout }));
          break;
      }
    }).catch(err => {
      console.error('Error to get riders: ', err);
    });
  }



  handleRide(ride) {
    if (this.state.timeout) {
      clearTimeout(this.state.timeout);
      this.setState(Object.assign(this.state, { timeout: null }));
    }
    this.refreshContent(ride.ride_uuid);
  }

  render() {
    console.log('Current state: ', this.state);
    return (
      <section className="chapter">
        <QueueAnim type="top" className="ui-animate">
          <div key="3"><Services data={getConfirmationData()} params={this.state.ride} onRideChange={this.handleRide} /></div>
          {/* <BottomNavigationExampleSimple data={getConfirmationData()} params={this.state.ride} /> */}
        </QueueAnim>
      </section>
    );
  }
};

module.exports = Page; 