import React, { Component } from 'react';
import QueueAnim from 'rc-queue-anim';
import APPCONFIG from 'constants/Config';
import TextField from 'material-ui/TextField';
import AutoComplete from 'material-ui/AutoComplete';
import MenuItem from 'material-ui/MenuItem';
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 Toggle from 'material-ui/Toggle';
import Snackbar from 'material-ui/Snackbar';
import RaisedButton from 'material-ui/RaisedButton';
import SelectField from 'material-ui/SelectField';
import Checkbox from 'material-ui/Checkbox';
import Instance from '../../../../../../../components/Connection';
import ValidationErrorsInfoDialog from '../../../../../../../components/Shared/ValidationErrorsInfoDialog';

class SignUp extends React.Component {
  constructor(props) {
    super(props);
  }

  state = {
    brand: APPCONFIG.brand,
    open: false,
    fullname: "",
    first: "",
    middle: "",
    last: "",
    email: "",
    phonenumber: "",
    member: "",
    birthdate: null,
    gender: null,
    agreedTerms: false,
    validated: false,
    memberType:"S",
    showValidationErrors: false,
    validationErrors:[]
  }

  componentDidMount = () => {
    let user = localStorage.getItem("userData")
    if (user && user !== null && user !== '') {
      user = JSON.parse(user);
      user.birthdate = new Date(user.birthdate);
      this.setState(Object.assign(this.state, user));
    }
  }

  clickEvent = (event) => {
    event.preventDefault();
    const state = this;
    state.handleRequestOpen();

    let user = {
      "first": this.state.first,
      "last": this.state.last,
      "gender": this.state.gender,
      "member": this.state.member,
      "email": this.state.email,
      "phonenumber": this.state.phonenumber,
      "birthdate": this.state.birthdate.toISOString(),
      "consent" : this.state.agreedTerms,
      "type": this.state.memberType

      // "eligibility": {
      //   "tracking_id": "1234567",
      //   "payer": {
      //     "payer_id": "621",
      //     "payer_name": "blue_cross_blue_shield_il"
      //   },
      //   "provider": {
      //     "provider_npi": "1699849786",
      //     "provider_name": "LITHOLINK CORPORATION"
      //   },
      //   "subscriber": {
      //     "subscriber_id": this.state.member,
      //     "patient_type": "S",
      //     "name": {
      //       "first": this.state.first,
      //       "last": this.state.last,
      //       "middle": ""
      //     },
      //     "demographic_info": {
      //       "date_of_birth": this.state.birthdate.toISOString(),
      //       "gender": this.state.gender
      //     }
      //   },
      //   "service_info": {
      //     "date_of_service": new Date().toISOString(),
      //     "service_type_codes": ["30"]
      //   }
      // }
    }

    Instance.getRawConn().post('/v1/nemt/users/member', user).then(function (res) {
      state.handleRequestClose();

      const eligibility = res.data;
      // if (eligibility.results.summary.benefits_found) {
      window.location.href = `/#/app/form/steppers/${eligibility.useruuid}`;
      // } else {
      //   alert('NO benefits found for this member');
      // }
    }).catch(function (err) {
      if (err.response.status === 422){
        //Unprocessable Entity (validation failed)
        state.setState(Object.assign(state.state, {showValidationErrors:true, validationErrors:err.response.data.data}))
      }else{
        console.log('Error to get eligibility: ', err);
        alert('NO benefits found for this member');
        this.handleRequestClose();
      }
    });
  }

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

  handleRequestOpen = () => {
    this.setState(Object.assign(this.state, { open: true }));
  };

  handleChecked = (event, checked) => {
    this.setState(Object.assign(this.state, { agreedTerms: checked }));
    this.buttonValidated();
  };

  handleDate = (event, date) => {
    this.setState(Object.assign(this.state, { birthdate: date }));
    this.buttonValidated();
  };

  handleMember = (event) => {
    this.setState(Object.assign(this.state, { member: event.target.value }));
  };

  handleChange = (event, index, value) => {
    this.setState(Object.assign(this.state, { gender: value }));
    this.buttonValidated();
  };

  handleMemberType = (event, index, value) => {
    this.setState(Object.assign(this.state, { meberType: value }));
    this.buttonValidated();
  };

  handleFirstName = (event) => {
    this.setState(Object.assign(this.state, { first: event.target.value }));
  };

  handleEmail = (event) => {
    this.setState(Object.assign(this.state, { email: event.target.value }));
  };

  handleLastName = (event) => {
    this.setState(Object.assign(this.state, { last: event.target.value }));
  };

  handlePhone = (event) => {
    let phone = event.target.value;
    if (phone.indexOf("+1") < 0 && phone.length == 10) {
      phone = "+1" + phone;
      phone = phone.substring(0, 12);
    }

    this.setState(Object.assign(this.state, { phonenumber: phone }));
  };

  buttonValidated = () => {
    let validated = true;
    if (!this.state.first || this.state.first === null || this.state.first === "") validated = false;
    if (!this.state.last || this.state.last === null || this.state.last === "") validated = false;
    if (!this.state.gender || this.state.gender === null || this.state.gender === "") validated = false;
    if (!this.state.member || this.state.member === null || this.state.member === "") validated = false;
    if (!this.state.birthdate || this.state.birthdate === null || isNaN(this.state.birthdate.getTime())) validated = false;
    if (!this.state.phonenumber || this.state.phonenumber === null || this.state.phonenumber === "") validated = false;
    //if (!this.state.email || this.state.email === null || this.state.email === "") validated = false;
    if (!this.state.agreedTerms) validated = false;

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

  handleValidationErrosDialogDismiss(){
    this.setState(Object.assign(this.state, {showValidationErrors:false}));
  }

  render() {
    return (
      <form className="">
        <fieldset>
          <ValidationErrorsInfoDialog open = {this.state.showValidationErrors} errorMessages = {this.state.validationErrors} modal={true} onDismiss={this.handleValidationErrosDialogDismiss.bind(this)}/>         
          <div className="form-group">
            <TextField
              floatingLabelText="First Name"
              value={this.state.first}
              onChange={this.handleFirstName}
              onBlur={this.buttonValidated}
            />
          </div>
          <div className="form-group">
            <TextField
              floatingLabelText="Last Name"
              value={this.state.last}
              onChange={this.handleLastName}
              onBlur={this.buttonValidated}
            />
          </div>
          <div className="form-group">
            <TextField
              floatingLabelText="Email"
              type="email"
              value={this.state.email}
              onChange={this.handleEmail}
              onBlur={this.buttonValidated}
            />
          </div>
          <div className="form-group">
            <SelectField
              floatingLabelText="Gender"
              value={this.state.gender}
              onChange={this.handleChange}
              style={{ maxWidth: 165 }}
            >
              <MenuItem value={null} primaryText="" />
              <MenuItem value={"M"} primaryText="Male" />
              <MenuItem value={"F"} primaryText="Female" />
              <MenuItem value={"U"} primaryText="Unknown" />
            </SelectField>
          </div>
          <div className="form-group">
            <SelectField
              style={{ maxWidth: 165 }}
              floatingLabelText="Member Type"
              value={this.state.memberType}
              onChange={this.handleMemberType}
            >
              <MenuItem value={null} primaryText="" />
              <MenuItem value={"S"} primaryText="Subscriber" />
              <MenuItem value={"D"} primaryText="Dependant" />
              <MenuItem value={"U"} primaryText="Unknown" />
            </SelectField>
          </div>
          <div className="form-group">
            <TextField
              style={{ maxWidth: 165 }}
              floatingLabelText="Member #"
              value={this.state.member}
              onChange={this.handleMember}
              onBlur={this.buttonValidated}
            />
          </div>
          <div className="form-group" style={{ maxWidth: 115 }} >
            <DatePicker width = "115" hintText="Birth Date" container="inline" style={{ width: 115 }}
              value={this.state.birthdate} onChange={this.handleDate} />
          </div>
          <div className="form-group">
            <TextField
              style={{ maxWidth: 115 }}
              floatingLabelText="Mobile Phone"
              type="telephone"
              value={this.state.phonenumber}
              onChange={this.handlePhone}
              onBlur={this.buttonValidated}
            />
          </div>
          <div className="form-group">
            <Checkbox
              label="Member has consented to terms of use"
              checked={this.state.agreedTerms}
              onCheck={this.handleChecked}
            />
          </div>
          <RaisedButton
            label="Check Eligibility"
            primary={true}
            onClick={this.clickEvent}
            disabled={!this.state.validated}
          />
        </fieldset>
        <div>
          <Snackbar
            open={this.state.open}
            message="Checking Eligibililty"
            autoHideDuration={1900}
            onRequestClose={this.handleRequestClose}
          />
        </div>
      </form>
    );
  }
}

const Page = () => (
  <section className="container-fluid with-maxwidth chapter">
    <article className="article padding-xs">
      <h2 className="article-title" style={{ paddingTop: 15 }}>Verify Eligibility</h2>
      <div className="box box-default">
        <div className="box-body">
          <SignUp />
        </div>
      </div>
    </article>
  </section>
);

module.exports = Page;