import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
const axios = require('axios');

import FlatButton from 'material-ui/FlatButton';
import Dialog from 'material-ui/Dialog';
import { List, ListItem, makeSelectable } from 'material-ui/List';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import Subheader from 'material-ui/Subheader';
import Divider from 'material-ui/Divider';
import Checkbox from 'material-ui/Checkbox';
import MapsLocalHospital from 'material-ui/svg-icons/maps/local-hospital';
import Instance from '../../../../../../../components/Connection';

const customContentStyle = {
  width: '100%',
  maxWidth: 'none',
};

const groupBy = function (array, f) {
  var groups = {};
  array.forEach(function (o) {
    var group = JSON.stringify(f(o));
    groups[group] = groups[group] || [];
    groups[group].push(o);
  });
  return Object.keys(groups).map(function (group) {
    return groups[group];
  })
}


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

  state = {
    Messages: [],
    selectedMessages: [],
    open: false,
    buttonValue: '',
    icon: '',
    floatingLabelText: '',
    value: '',
    geolocation: {
      lat: 0,
      long: 0
    }
  };

  static propTypes = {
    title: React.PropTypes.string,
    buttonValue: React.PropTypes.string,
    icon: React.PropTypes.string,
    onMessagesAdded: React.PropTypes.function
  };

  handleOpen = (e, self) => {
    self.setState(Object.assign(self.state, { open: true, Messages: [], selectedMessages: [], value: '' }));
  };

  handleCancel = (e, self) => {
    self.setState(Object.assign(self.state, { open: false }));
  };

  handleClose = (e, self) => {
    if (self.state.selectedMessages.length > 0) {
      let params = []

      self.state.selectedMessages.forEach(p => {
        let result = params.find(pr => p.id === pr.id);
        if (result) {
          let index = params.indexOf(result);
          if (index > -1) {
            params.splice(index, 1);
            result.raw.fivePartKeyGroups.push(p.raw.fivePartKeyGroups);
            params.push(result);
          }
        } else {
          params.push(p);
        }
      }, this);

      params = params.map(p => { return p.raw; });

      if (params && params.length > 0) {
        let url = `/v1/nemt/Message`;
        Instance.getRawConn().post(url, params).then(res => {
          if (self.props.onMessagesAdded) {
            self.props.onMessagesAdded(res.data);
          }
        });
      }
    }
    self.setState(Object.assign(self.state, { open: false }));
  };

  handleRemoveMessage = (event, Message, self) => {
    event.preventDefault();
    let selectedMessages = self.state.selectedMessages;
    let result = selectedMessages.find(p => p.object_id === Message.object_id);
    if (result) {
      const index = selectedMessages.indexOf(result);
      if (index > -1) {
        selectedMessages.splice(index, 1);
      }
    }
    self.setState(Object.assign(self.state, { selectedMessages: selectedMessages }));
  }

  handleMessageClick = (event, Message, self) => {
    event.preventDefault();
    let selectedMessages = self.state.selectedMessages;
    debugger;
    let result = selectedMessages.find(p => p.object_id === Message.object_id);
    if (result) {
      const index = selectedMessages.indexOf(result);
      if (index > -1) {
        selectedMessages.splice(index, 1);
      }
    } else {
      selectedMessages.push(Message);
    }
    self.setState(Object.assign(self.state, { selectedMessages: selectedMessages }));
  }

  searchMessage(e) {
    let MessageName = e.target.value;
    this.setState(Object.assign(this.state, { value: MessageName }));
    let url = `/v1/nemt/Message?lat=${this.state.geolocation.lat}&long=${this.state.geolocation.long}&limit=20&name=${MessageName}&sortby=distance`
    Instance.getRawConn().get(encodeURI(url)).then(res => {
      if (res.data.resultStatus === "SUCCESS") {
        if (res.data.Messages && res.data.Messages.length > 0) {
          var places = [];
          res.data.Messages.forEach(p => {
            var result = groupBy(p.fivePartKeyGroups, function (item) {
              return [item.MessageNum, item.MessageNumSuffix, item.locationSeqNum, item.planCode, item.productId];
            });

            result = result.map(r => {
              let raw = p;
              raw.fivePartKeyGroups = r;

              let clickResult = {
                id: p.mukId,
                address: `${p.streetName_1}, ${p.cityName}, ${p.state} (${p.zipCode})`,
                lat: parseFloat(p.latitude),
                lng: parseFloat(p.longitude),
                name: p.MessageName,
                type: "Message",
                internal_id: r[0].MessageNum,
                internal_id_suffix: r[0].MessageNumSuffix,
                location_seq_num: r[0].locationSeqNum,
                plan_code: r[0].planCode,
                product_id: r[0].productId,
                treatment_code: r[0].treatmentCategoryCode,
                object_id: p.mukId + '-' + r[0].MessageNum + '-' + r[0].planCode + '-' + r[0].productId,
                raw: raw,
                text: `${p.MessageName} - ${p.streetName_1}, ${p.cityName}, ${p.state} (${p.zipCode})`
              }

              let checked = false;
              let Message = this.state.selectedMessages.find(p => p.id === clickResult.id)
              if (Message) {
                checked = true;
              }

              var listItem = (
                <ListItem
                  id={clickResult.object_id}
                  leftCheckbox={<Checkbox checked={checked} />}
                  value={clickResult.object_id}
                  key={clickResult.object_id}
                  primaryText={`${clickResult.name} - Plan: ${clickResult.plan_code} Product: ${clickResult.product_id}`}
                  secondaryText={clickResult.address}
                  rightIcon={<MapsLocalHospital />}
                  onClick={(event) => this.handleMessageClick(event, clickResult, this)}
                />
              )
              return listItem;
            });

            places = places.concat(result);
          }, this);
          this.setState(Object.assign(this.state, { Messages: places }));

          // let places = res.data.Messages.map(p => {
          //   p.MessageText = `${p.MessageName} - ${p.streetName_1}, ${p.cityName}, ${p.state} (${p.zipCode})`
          //   let clickResult = {
          //     id: p.mukId,
          //     address: `${p.streetName_1}, ${p.cityName}, ${p.state} (${p.zipCode})`,
          //     lat: parseFloat(p.latitude),
          //     lng: parseFloat(p.longitude),
          //     name: p.MessageName,
          //     type: "Message",
          //     raw: p
          //   }

          //   let checked = false;
          //   let Message = this.state.selectedMessages.find(p => p.id === clickResult.id)
          //   if (Message) {
          //     checked = true;
          //   }

          //   var listItem = (
          //     <ListItem
          //       leftCheckbox={<Checkbox checked={checked} />}
          //       value={clickResult.id}
          //       key={clickResult.id}
          //       primaryText={clickResult.name}
          //       secondaryText={clickResult.address}
          //       rightIcon={<MapsLocalHospital />}
          //       onClick={(event) => this.handleMessageClick(event, clickResult, this)}
          //     />
          //   )
          //   return listItem;
          // });
          // this.setState(Object.assign(this.state, { Messages: places }));
        }
      }
    });
  };

  geoSuccess = (position) => {
    let geo = {
      lat: position.coords.latitude,
      long: position.coords.longitude
    }

    geo = {
      lat: 41.886406,
      long: -87.624225
    }

    this.setState(Object.assign(this.state, { geolocation: geo }));
  };

  noPosition = () => {
    this.geoSuccess({
      coords: {
        latitude: 41.886406,
        longitude: -87.624225
      }
    });
  };

  componentWillReceiveProps(nextProps) {
    const self = this;
    var objConf = {
      open: false,
      buttonValue: nextProps.buttonValue,
      icon: nextProps.icon,
      floatingLabelText: 'Type the Message name'
    }

    this.setState(Object.assign(this.state, objConf));
  };

  componentDidMount() {
    const self = this;
    var objConf = {
      open: false,
      buttonValue: this.props.buttonValue,
      icon: this.props.icon,
      floatingLabelText: 'Type the Message name'
    }

    this.setState(Object.assign(this.state, objConf));
    navigator.geolocation.getCurrentPosition(this.geoSuccess, this.noPosition);
  };

  render() {
    const self = this;
    let actions = [
      <FlatButton
        label="Cancel"
        primary={true}
        onClick={(e) => this.handleCancel(e, this)}
      />,
      <FlatButton
        label="Submit"
        primary={true}
        keyboardFocused={true}
        onClick={(e) => this.handleClose(e, this)}
      />,
    ];

    let button = (
      <RaisedButton
        label={this.state.buttonValue}
        onClick={(e) => this.handleOpen(e, this)}
        secondary
        icon={this.state.icon}
        fullWidth={true}
      />);

    let selectedMessageList;
    if (this.state.selectedMessages.length > 0) {
      let items = this.state.selectedMessages.map(p => {
        var listItem = (
          <ListItem
            leftCheckbox={<Checkbox checked={true} />}
            value={p.id}
            key={p.id}
            primaryText={`${p.name} - Plan: ${p.plan_code} Product: ${p.product_id}`}
            secondaryText={p.address}
            rightIcon={<MapsLocalHospital />}
            onClick={(event) => this.handleRemoveMessage(event, p, this)}
          />
        )
        return listItem;
      });

      selectedMessageList = (
        <div>
          <List>
            <Subheader>Selected Messages</Subheader>
            {items}
          </List>
          <Divider />
        </div>
      )
    }

    return (
      <div>
        {button}
        <Dialog
          contentStyle={customContentStyle}
          title={this.props.title}
          actions={actions}
          modal={true}
          open={this.state.open}
          onRequestClose={this.handleClose}
        >
          <div className="" id="container">
            <TextField onChange={(e) => this.searchMessage(e)} fullWidth={true} floatingLabelText={this.state.floatingLabelText} value={this.state.value} />
            {selectedMessageList}
            <List>
              {this.state.Messages}
            </List>
          </div>
        </Dialog>
      </div>);
  }
}