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 ProviderSelection extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      providers: [],
      selectedProviders: [],
      open: false,
      buttonValue: '',
      icon: '',
      floatingLabelText: '',
      value: '',
      geolocation: {
        lat: 0,
        long: 0
      }
    }

    this.handleOpen = this.handleOpen.bind(this);
    this.handleCancel = this.handleCancel.bind(this);
    this.handleClose = this.handleClose.bind(this);
    this.handleRemoveProvider = this.handleRemoveProvider.bind(this);
    this.handleProviderClick = this.handleProviderClick.bind(this);
    this.searchProvider = this.searchProvider.bind(this);
    this.geoSuccess = this.geoSuccess.bind(this);
    this.noPosition = this.noPosition.bind(this);
  }

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

  handleOpen = (e) => {
    this.setState(Object.assign(this.state, { open: true, providers: [], selectedProviders: [], value: '' }));
  };

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

  handleClose = (e) => {
    if (this.state.selectedProviders.length > 0) {
      let params = []

      this.state.selectedProviders.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/provider`;
        Instance.getRawConn().post(url, params).then(res => {
          if (this.props.onProvidersAdded) {
            this.props.onProvidersAdded(res.data);
          }
        });
      }
    }
    this.setState(Object.assign(this.state, { open: false }));
  };

  handleRemoveProvider = (event, provider) => {
    event.preventDefault();
    let selectedProviders = this.state.selectedProviders;
    let result = selectedProviders.find(p => p.object_id === provider.object_id);
    if (result) {
      const index = selectedProviders.indexOf(result);
      if (index > -1) {
        selectedProviders.splice(index, 1);
      }
    }
    this.setState(Object.assign(this.state, { selectedProviders: selectedProviders }));
  }

  handleProviderClick = (event, provider) => {
    event.preventDefault();
    let selectedProviders = this.state.selectedProviders;
    debugger;
    let result = selectedProviders.find(p => p.object_id === provider.object_id);
    if (result) {
      const index = selectedProviders.indexOf(result);
      if (index > -1) {
        selectedProviders.splice(index, 1);
      }
    } else {
      selectedProviders.push(provider);
    }
    this.setState(Object.assign(this.state, { selectedProviders: selectedProviders }));
  }

  searchProvider = (e) => {
    let providerName = e.target.value;
    this.setState(Object.assign(this.state, { value: providerName }));
    let url = `/v1/nemt/provider?lat=${this.state.geolocation.lat}&long=${this.state.geolocation.long}&limit=20&name=${providerName}&sortby=distance`
    Instance.getRawConn().get(encodeURI(url)).then(res => {
      if (res.data.resultStatus === "SUCCESS") {
        if (res.data.providers && res.data.providers.length > 0) {
          var places = [];
          res.data.providers.forEach(p => {
            var result = groupBy(p.fivePartKeyGroups, function (item) {
              return [item.providerNum, item.providerNumSuffix, 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.providerName,
                street: p.streetName_1,
                city: p.cityName,
                state: p.state,
                zip_code: p.zipCode,
                phone_number: p.phoneNumber,
                type: "provider",
                internal_id: r[0].providerNum,
                internal_id_suffix: r[0].providerNumSuffix,
                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].providerNum + '-' + r[0].planCode + '-' + r[0].productId,
                raw: raw,
                text: `${p.providerName} - ${p.streetName_1}, ${p.cityName}, ${p.state} (${p.zipCode})`
              }

              let checked = false;
              let provider = this.state.selectedProviders.find(p => p.id === clickResult.id)
              if (provider) {
                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.handleProviderClick(event, clickResult, this)}
                />
              )
              return listItem;
            });

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

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

    geo = {
      lat: 41.819078,
      long: -87.623129,
    }

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

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

  componentWillReceiveProps(nextProps) {
    const self = this;
    var objConf = {
      open: false,
      buttonValue: nextProps.buttonValue,
      icon: nextProps.icon,
      floatingLabelText: 'Type the provider 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 provider 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 selectedProviderList;
    if (this.state.selectedProviders.length > 0) {
      let items = this.state.selectedProviders.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.handleRemoveProvider(event, p, this)}
          />
        )
        return listItem;
      });

      selectedProviderList = (
        <div>
          <List>
            <Subheader>Selected Providers</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.searchProvider(e)} fullWidth={true} floatingLabelText={this.state.floatingLabelText} value={this.state.value} />
            {selectedProviderList}
            <List>
              {this.state.providers}
            </List>
          </div>
        </Dialog>
      </div>);
  }
}