import React from 'react';
import Dialog from 'material-ui/Dialog';
import { List, ListItem } from 'material-ui/List';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import FlatButton from 'material-ui/FlatButton';
import SelectField from 'material-ui/SelectField';
import AutoComplete from 'material-ui/AutoComplete';
import MenuItem from 'material-ui/MenuItem';
import Instance from '../../../../../../../components/Connection';

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

const dataSourceConfig = {
  text: 'organizationName',
  value: 'organizationValue',
};

export default class OrganizationComponent extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      buttonValue: '',
      openDialog: false,
      title: '',
      modalStyle: {
        width: '100%',
        maxWidth: '600px',
      },
      divStyle: {
        textAlign: 'left',
        textTransform: 'none !important',
        padding: '0px 5px 0px 0px',
        marginTop: -5,
        boxShadow: 'none',
        color: 'rgba(0, 0, 0, 0.3)',
      },
      location: {
        lat: 41.819078,
        long: -87.623129,
      },
      searchValue: '',
      searchProviders: [],
      selectedProvider: {},
      organizationFields: {
        type: {
          key: '',
          name: '',
        },
        name: '',
        desc: '',
        parent: {},
        reference: null,
      },
      searchingOrganizations: false,
      selectedOrganization: {},
      selectedType: {},
      typeList: [],
      geolocation: {
        lat: 41.819078,
        long: -87.623129,
      },
      showFields: true,
      parentAutocomplete: '',
      parentOrganizations: [],
      seachingProvider: false,
    };

    this.handleOpen = this.handleOpen.bind(this);
    this.handleClose = this.handleClose.bind(this);
    this.setProps = this.setProps.bind(this);
    this.handleSave = this.handleSave.bind(this);
    this.handleOrganization = this.handleOrganization.bind(this);
    this.handleType = this.handleType.bind(this);
    this.handleNext = this.handleNext.bind(this);

    this.handleSearchRawProvider = this.handleSearchRawProvider.bind(this);
    this.handleProviderClick = this.handleProviderClick.bind(this);

    this.handleParentAutocomplete = this.handleParentAutocomplete.bind(this);
    this.handleParentSearch = this.handleParentSearch.bind(this);
    this.handleOrganizationName = this.handleOrganizationName.bind(this);
    this.handleOrganizationDesc = this.handleOrganizationDesc.bind(this);
    this.handleButtonSearchRawProvider = this.handleButtonSearchRawProvider.bind(this);
    this.handleReset = this.handleReset.bind(this);
  }

  componentDidMount() {
    const self = this;
    this.setProps(this.props);

    Instance.getRawConn().get('/v1/nemt/organization/type').then(res => {
      const typeList = res.data.map((v, i) => {
        if (v.key === 'provider') {
          self.setState(Object.assign(self.state, { selectedType: v, showFields: false }));
        }
        return (<MenuItem value={v} primaryText={v.name} />);
      });

      self.setState(Object.assign(self.state, { typeList: typeList }));
    }).catch(console.error);
    navigator.geolocation.getCurrentPosition(this.geoSuccess, this.noPosition);
  }

  componentWillReceiveProps(nextProps) {
    this.setProps(nextProps);
  }

  setProps(propsParam) {
    this.setState(Object.assign(this.state, { buttonValue: propsParam.buttonValue, title: propsParam.title }));
  }

  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.886406,
        longitude: -87.624225
      }
    });
  };

  handleOpen() {
    this.setState(Object.assign(this.state, { openDialog: true }));
    this.handleReset();
  }

  handleClose() {
    this.setState(Object.assign(this.state, { openDialog: false }));
    this.handleReset();
  }

  handleSave() {
    const self = this;
    const organizationFields = this.state.organizationFields;
    organizationFields.type = this.state.selectedType;

    Instance.getRawConn().post('/v1/nemt/organization', organizationFields).then(res => {
      this.setState(Object.assign(this.state, { openDialog: false }));
      location.href = '/#/app/organization/' + res.data.id;

      if (this.props.onSelectOrganization) {
        this.props.onSelectOrganization(res.data);
      }
      self.handleReset();
    }).catch(console.error);
  }

  handleType(event, index, value) {
    let showFields = !(value.key === 'provider');
    this.handleReset(event);
    this.setState(Object.assign(this.state, { selectedType: value, showFields: showFields }));
  }

  handleOrganization(e, a) {
    let selectedOrganizations = this.state.selectedOrganizations;
    selectedOrganizations.push(a);
    this.setState(Object.assign(this.state, {
      selectedOrganizations: selectedOrganizations,
      searchValue: a.name,
    }));
  }

  handleParentAutocomplete = (u) => {
    let organizationFields = this.state.organizationFields;
    organizationFields.parent = u.organizationValue;
    this.setState(Object.assign(this.state, { organizationFields: organizationFields, parentAutocomplete: u.name }));
  }

  handleParentFilter = (searchText, key) => {
    if (searchText && key) {
      return (key.toLowerCase().indexOf(searchText.toLowerCase()) !== -1)
    } else {
      return false;
    }
  }

  handleParentSearch = (s) => {
    this.setState(Object.assign(this.state, { parentAutocomplete: s }));
    if (s.length >= 3 && !this.state.searchingOrganizations) {
      this.setState(Object.assign(this.state, { searchingOrganizations: true }));
      let url = '/v1/nemt/organization/name?name=' + encodeURIComponent(s);
      if (this.props.searchType) {
        switch (this.props.searchType) {
          case 'parent':
          case 'child':
            url += '&type=' + encodeURIComponent(this.props.searchType);
            break;
        }
      }

      Instance.getRawConn().get(url).then(res => {
        const list = res.data.map(p => {
          console.log(p);
          return {
            organizationName: p.name,
            organizationValue: p
          };
        });
        this.setState(Object.assign(this.state, { parentOrganizations: list, searchingOrganizations: false }));
      }).catch(console.error);
    }
  }

  handleProviderClick = (e, p) => {
    this.setState(Object.assign(this.state, { searchValue: p.completeText, selectedProvider: p }));
  }

  handleNext = (e) => {
    e.preventDefault();
    const organization = {
      type: this.state.selectedType,
      name: this.state.selectedProvider.name,
      desc: '',
      parent: {},
      reference: this.state.selectedProvider.raw,
    }

    this.setState(Object.assign(this.state, { showFields: true, organizationFields: organization }));
  }

  handleReset = (e) => {
    var self = this;
    let organization = self.state.organizationFields;

    organization.name = '';
    organization.desc = '';
    organization.parent = {};
    organization.reference = null;

    self.setState(Object.assign(self.state, { searchValue: '', searchProviders: [], organizationFields: organization }));
  }

  handleButtonSearchRawProvider = (e) => {
    var self = this;
    self.setState(Object.assign(self.state, { seachingProvider: true }));
    let url = `/v1/nemt/provider?lat=${self.state.geolocation.lat}&long=${self.state.geolocation.long}&limit=50&name=${self.state.searchValue}&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})`,
                completeText: `${p.providerName} - Plan: ${r[0].planCode} Product: ${r[0].productId}`
              }

              var listItem = (
                <ListItem
                  id={clickResult.object_id}
                  value={clickResult.object_id}
                  key={clickResult.object_id}
                  primaryText={`${clickResult.name} - Plan: ${clickResult.plan_code} Product: ${clickResult.product_id}`}
                  secondaryText={clickResult.address}
                  onClick={(event) => self.handleProviderClick(event, clickResult)}
                />
              )
              return listItem;
            });

            places = places.concat(result);
          }, self);
          self.setState(Object.assign(self.state, { searchProviders: places, seachingProvider: false }));
        } else {
          self.setState(Object.assign(self.state, { searchProviders: [], seachingProvider: false }));
        }
      } else {
        console.error(res.data);
        self.setState(Object.assign(self.state, { searchProviders: [], seachingProvider: false }));
      }
    }).catch(err => {
      console.error(err);
      self.setState(Object.assign(self.state, { seachingProvider: false }));
    });
  }

  handleSearchRawProvider = (e) => {
    var self = this;
    self.setState(Object.assign(self.state, { searchValue: e.target.value }));
  };

  handleOrganizationName(e) {
    let organizationDesc = this.state.organizationFields;
    organizationDesc.name = e.target.value;

    this.setState(Object.assign(this.state, { organizationFields: organizationDesc }));
  }

  handleOrganizationDesc(e) {
    let organizationDesc = this.state.organizationFields;
    organizationDesc.desc = e.target.value;

    this.setState(Object.assign(this.state, { organizationFields: organizationDesc }));
  }

  render() {

    let actions = [
      <FlatButton
        label="Cancel"
        primary={true}
        onClick={this.handleClose}
      />,
      <FlatButton
        label="Add Organization"
        primary={true}
        keyboardFocused={true}
        onClick={this.handleSave}
      />,
    ];

    let formOrganization = (<div>
      <TextField onChange={this.handleOrganizationName} fullWidth={true} floatingLabelText={"Organization name"} value={this.state.organizationFields.name} />
      <AutoComplete
        floatingLabelText="Parent Organization"
        filter={this.handleParentFilter}
        maxSearchResults={5}
        dataSource={this.state.parentOrganizations}
        dataSourceConfig={dataSourceConfig}
        onNewRequest={this.handleParentAutocomplete}
        onUpdateInput={this.handleParentSearch}
        searchText={this.state.parentAutocomplete}
        fullWidth={true}
      />
      <TextField onChange={this.handleOrganizationDesc} fullWidth={true} floatingLabelText={"Description"} value={this.state.organizationFields.desc} multiLine={true} rows={5} />
    </div>);

    switch (this.state.selectedType.key) {
      case 'provider':
        if (!this.state.showFields) {
          formOrganization = (
            <div>
              <div className={"row"}>
                <div className={"col-xl-7"}>
                  <TextField onChange={this.handleSearchRawProvider} fullWidth={true} floatingLabelText={"Type the provider name"} value={this.state.searchValue} />
                </div>
                <div className={"col-xl-5"}>
                  <FlatButton
                    label="Search"
                    primary={true}
                    disabled={this.state.seachingProvider}
                    onClick={this.handleButtonSearchRawProvider}
                    style={{ marginTop: '18px' }}
                  />
                  <FlatButton
                    label="Reset"
                    secondary={true}
                    disabled={this.state.seachingProvider}
                    onClick={this.handleReset}
                    style={{ marginTop: '18px' }}
                  />
                </div>
              </div>
              <div className={"row"}>
                <div className={"col-xl-12"}>
                  <List>
                    {this.state.searchProviders}
                  </List>
                </div>
              </div>
            </div>
          )

          actions = [
            <FlatButton
              label="Cancel"
              primary={true}
              onClick={this.handleClose}
            />,
            <FlatButton
              label="Next"
              primary={true}
              keyboardFocused={true}
              onClick={this.handleNext}
            />,
          ];
        } else {
          actions = [
            <FlatButton
              label="Cancel"
              primary={true}
              onClick={this.handleClose}
            />,
            <FlatButton
              label="Back"
              primary={true}
              onClick={this.handleBack}
            />,
            <FlatButton
              label="Add Organization"
              primary={true}
              keyboardFocused={true}
              onClick={this.handleSave}
            />,
          ];
        }
        break;
    }

    return (
      <div style={this.state.divStyle} >
        <RaisedButton
          label={this.state.buttonValue}
          onClick={this.handleOpen}
          secondary
          fullWidth={true}
        />
        <Dialog
          contentStyle={this.state.modalStyle}
          title={this.state.title}
          actions={actions}
          modal={true}
          open={this.state.openDialog}
          onRequestClose={this.handleClose}
          autoScrollBodyContent={true}
        >
          <div className="" id="container">
            <SelectField
              floatingLabelText="Type"
              value={this.state.selectedType}
              onChange={this.handleType}
              fullWidth={true}
            >
              {this.state.typeList}
            </SelectField>
            {formOrganization}
          </div>
        </Dialog>
      </div>);
  }
}