import React, { Component, PropTypes } from "react";
import {
  Card,
  Dialog,
  FlatButton,
  Paper,
  RaisedButton,
  MenuItem
} from "material-ui";
import Spacing from "material-ui/styles/spacing";
import Formsy from "formsy-react";
import {
  FormsyRadio,
  FormsyRadioGroup,
  FormsySelect,
  FormsyText
} from "formsy-material-ui";
import getMuiTheme from "material-ui/styles/getMuiTheme";
import UCdefaultTheme from "../../themes/DefaultTheme";

import { PhoneCodes } from "./default_data";

Formsy.addValidationRule("isEmpty", (values, value) => value !== "");

const FormLabel = props => (
  <div style={{ marginBottom: "0", color: "#000", marginTop: "20px" }}>
    {props.children}
  </div>
);

export default class Delegated extends Component {
  constructor(props) {
    super(props);
    const maxDate = new Date();
    const minDate = new Date();

    minDate.setFullYear(minDate.getFullYear() - 100);
    maxDate.setFullYear(maxDate.getFullYear() - 18);

    this.state = {
      maxDate,
      minDate,
      canSubmit: false,
      emailError: "Please enter a valid email address.",
      wordsError: "Please use only letters.",
      numError: "Please use only numbers.",
      requiredError: "Required",
      genError: " ",
      states: props.addressStates,
      countries: props.addressCountries,
      country: "USA",
      isResident: "Y",
      state: "OH",
      errorDialogOpen: props.errorMessage && props.errorMessage !== "",
      errorMessage: props.errorMessage
    };
    this.enableButton = this.enableButton.bind(this);
    this.disableButton = this.disableButton.bind(this);
    this.submitForm = this.submitForm.bind(this);
  }

  getChildContext() {
    const theme = getMuiTheme(UCdefaultTheme);
    return {
      muiTheme: theme
    };
  }

  enableButton() {
    this.setState({
      canSubmit: true
    });
  }

  disableButton() {
    this.setState({
      canSubmit: false
    });
  }

  submitForm(model) {
    // Submit your validated form
    this.props.handleSubmit(model);
  }

  handleCountryChange(country) {
    this.setState({ country });
    this.props.handleCountryChange(country);
  }

  handleResidentChange(isResident) {
    this.setState({ resident: isResident });
  }

  handleStateChange(state) {
    this.setState({ state });
  }

  render() {
    const {
      wordsError,
      numError,
      emailError,
      requiredError,
      genError
    } = this.state;

    const hintStyle = { color: "rgba(6, 0, 0, 0.55)" };

    const actions = [
      <FlatButton label="Ok" primary onTouchTap={this.props.handleErrorClick} />
    ];

    const states = this.props.addressStates.map((state, index) => (
      <MenuItem
        key={`states-${index}`}
        value={state.abbreviation}
        primaryText={state.name}
      />
    ));

    const countries = this.props.addressCountries.map((country, index) => (
      <MenuItem
        key={`countries-${index}`}
        value={country.abbreviation}
        primaryText={country.name}
      />
    ));

    const phoneCodes = PhoneCodes.map((phone, index) => (
      <MenuItem
        key={`phone-${index}`}
        value={phone.dial_code}
        primaryText={`${phone.name} (${phone.dial_code})`}
      />
    ));

    return (
      <Card>
        <Paper style={this.props.isLoading ? { opacity: 0.3 } : null}>
          {this.props.isSubmitted ? (
            <div className="container" style={{ padding: 20 }}>
              <h1>Submitted</h1>
              <p>
                Your identity was submitted to Catalyst. You will receive an
                email with next steps.
              </p>
            </div>
          ) : (
            <div className="container" style={{ padding: 20 }}>
              <Formsy.Form
                onValid={this.enableButton}
                onInvalid={this.disableButton}
                onValidSubmit={this.props.handleSubmit}
              >
                <div className="row">
                  <div className="col-sm-12 col-xs-12">
                    <FormLabel>Legal Name *</FormLabel>
                    <FormsyText
                      aria-label="First Name"
                      name="FirstName"
                      hintText="First"
                      validations={{
                        isWords: true,
                        isEmpty: true,
                        isExisty: true
                      }}
                      hintStyle={hintStyle}
                      validationErrors={{
                        isWords: wordsError,
                        isEmpty: requiredError
                      }}
                      style={{
                        verticalAlign: "top",
                        width: "100px",
                        marginRight: "10px"
                      }}
                    />
                    <FormsyText
                      aria-label="Middle Name"
                      name="MiddleName"
                      hintText="Middle"
                      hintStyle={hintStyle}
                      validations="isWords"
                      validationError={wordsError}
                      style={{
                        verticalAlign: "top",
                        width: "100px",
                        marginRight: "10px"
                      }}
                    />
                    <FormsyText
                      name="LastName"
                      aria-label="Last Name"
                      hintText="Last"
                      hintStyle={hintStyle}
                      validations={{
                        isWords: true,
                        isEmpty: true,
                        isExisty: true
                      }}
                      validationErrors={{
                        isWords: wordsError,
                        isEmpty: requiredError
                      }}
                      style={{
                        verticalAlign: "top",
                        width: "200px",
                        marginRight: "10px"
                      }}
                    />
                  </div>
                </div>
                <div className="row">
                  <div className="col-sm-4">
                    <FormLabel>Former Last Name</FormLabel>
                    <FormsyText
                      name="FormerName"
                      aria-label={"Former Name"}
                      hintText="Former Last Name"
                      hintStyle={hintStyle}
                      validations={{
                        isWords: true
                      }}
                      validationErrors={{
                        isWords: wordsError
                      }}
                      style={{
                        verticalAlign: "top",
                        width: "200px",
                        marginRight: "10px"
                      }}
                    />
                  </div>
                </div>
                <div className="row">
                  <div className="col-sm-4">
                    <FormLabel>Date of Birth *</FormLabel>
                    <FormsyText
                      name="Month"
                      aria-label={"Month"}
                      validations={{
                        isNumeric: true,
                        isEmpty: true,
                        isExisty: true
                      }}
                      validationErrors={{
                        isNumeric: genError,
                        isEmpty: genError
                      }}
                      maxLength="2"
                      hintText="MM"
                      hintStyle={hintStyle}
                      type="tel"
                      style={{
                        verticalAlign: "top",
                        width: "30px",
                        marginRight: "10px"
                      }}
                    />
                    <FormsyText
                      name="Day"
                      aria-label="Day"
                      validations={{
                        isNumeric: true,
                        isEmpty: true,
                        isExisty: true
                      }}
                      validationErrors={{
                        isNumeric: genError,
                        isEmpty: genError
                      }}
                      maxLength="2"
                      hintText="DD"
                      hintStyle={hintStyle}
                      type="tel"
                      style={{
                        verticalAlign: "top",
                        width: "30px",
                        marginRight: "10px"
                      }}
                    />
                    <FormsyText
                      name="Year"
                      aria-label="Year"
                      validations={{
                        isNumeric: true,
                        isEmpty: true,
                        isExisty: true
                      }}
                      validationErrors={{
                        isNumeric: genError,
                        isEmpty: genError
                      }}
                      maxLength="4"
                      hintText="YYYY"
                      hintStyle={hintStyle}
                      type="tel"
                      style={{ verticalAlign: "top", width: "50px" }}
                    />
                  </div>
                  <div className="col-sm-4">
                    <FormLabel>Email Address *</FormLabel>
                    <FormsyText
                      name="Email_Address"
                      aria-label="Email Address"
                      validations={{
                        isEmail: true,
                        isEmpty: true,
                        isExisty: true
                      }}
                      validationErrors={{
                        isEmail: emailError,
                        isEmpty: requiredError
                      }}
                      type="email"
                      hintText="username@email.com"
                      hintStyle={hintStyle}
                      style={{ verticalAlign: "top" }}
                    />
                  </div>
                </div>
                <div className="row">
                  <div className="col-xs-4">
                    <FormLabel>US citizen or permanent resident? *</FormLabel>
                    <FormsyRadioGroup
                      name="Resident"
                      aria-label="Resident"
                      required
                      onChange={(event, index) =>
                        this.handleResidentChange(index)
                      }
                    >
                      <FormsyRadio value="Y" label="Yes" aria-label="Yes" />
                      <FormsyRadio value="N" label="No" aria-label="No" />
                    </FormsyRadioGroup>
                  </div>
                  <div className="col-xs-4">
                    <FormLabel>
                      Social Security Number{" "}
                      {this.state.resident === "Y" ? "*" : null}
                    </FormLabel>
                    <FormsyText
                      aria-label="Social Security Number"
                      name="SSN"
                      validations="isNumeric"
                      required={this.state.resident === "Y"}
                      validationError={numError}
                      maxLength="9"
                      hintText="XXXXXXXXX"
                      hintStyle={hintStyle}
                      type="tel"
                      style={{ verticalAlign: "top", width: "100px" }}
                    />
                  </div>
                </div>
                <FormLabel>Country *</FormLabel>
                <FormsySelect
                  name="Address_Country"
                  aria-label="Country"
                  value={this.state.country}
                  required
                  style={{ verticalAlign: "top" }}
                  hintText="Country"
                  hintStyle={hintStyle}
                  onChange={(event, index) => this.handleCountryChange(index)}
                >
                  {countries}
                </FormsySelect>
                <FormLabel>Street Address *</FormLabel>
                <FormsyText
                  name="Address1"
                  aria-label="Address 1"
                  validations={{
                    isEmpty: true,
                    isExisty: true
                  }}
                  validationErrors={{
                    isEmpty: requiredError
                  }}
                  hintText="Address 1"
                  hintStyle={hintStyle}
                  style={{
                    verticalAlign: "top",
                    marginRight: "10px",
                    width: "50%"
                  }}
                />
                <br />
                <FormsyText
                  name="Address2"
                  aria-label="Address 2"
                  hintText="Address 2"
                  hintStyle={hintStyle}
                  style={{
                    verticalAlign: "top",
                    marginRight: "10px",
                    width: "50%"
                  }}
                />
                <br />
                <FormsyText
                  name="City"
                  aria-label="City"
                  validations={{
                    isWords: true,
                    isEmpty: true,
                    isExisty: true
                  }}
                  validationErrors={{
                    isWords: wordsError,
                    isEmpty: requiredError
                  }}
                  hintText="City"
                  hintStyle={hintStyle}
                  style={{ verticalAlign: "top", marginRight: "10px" }}
                />
                {this.state.country === "USA" ? (
                  <FormsySelect
                    name="State"
                    aria-label="State"
                    value={this.state.state}
                    hintText="State"
                    hintStyle={hintStyle}
                    maxHeight={300}
                    style={{ verticalAlign: "top" }}
                    onChange={(event, index) => this.handleStateChange(index)}
                  >
                    {states}
                  </FormsySelect>
                ) : (
                  <FormsySelect
                    name="province"
                    aria-label="Province"
                    hintText="Province"
                    hintStyle={hintStyle}
                    style={{ verticalAlign: "top", marginLeft: 5 }}
                  >
                    {states}
                  </FormsySelect>
                )}
                <br />
                <FormsyText
                  name="Postal"
                  aria-label="Zip Postal Code"
                  validations={{
                    isEmpty: true,
                    isExisty: true
                  }}
                  validationErrors={{
                    isEmpty: requiredError
                  }}
                  hintText="Zip/Postal Code"
                  hintStyle={hintStyle}
                  type="tel"
                  style={{ verticalAlign: "top" }}
                />
                {this.state.country === "USA" ? (
                  <div>
                    <FormLabel>Phone (Primary) *</FormLabel>
                    <FormsySelect
                      required
                      name="Phone_Cntry_Cd_01"
                      aria-label="Phone Country Code"
                      key="Phone_Cntry_Cd_01"
                      className="text-nowrap"
                      style={{ verticalAlign: "bottom", marginRight: "10px" }}
                      hintText="Country Code"
                      hintStyle={hintStyle}
                      value={"+1"}
                    >
                      {phoneCodes}
                    </FormsySelect>
                    <br />
                    <FormsyText
                      name="Phone_Home"
                      aria-label="Phone Home"
                      maxLength="10"
                      type="tel"
                      validations={{
                        isNumeric: true,
                        isEmpty: true,
                        isExisty: true
                      }}
                      validationErrors={{
                        isNumeric: numError,
                        isEmpty: requiredError
                      }}
                      hintText="5555555555"
                      hintStyle={hintStyle}
                      style={{
                        verticalAlign: "bottom",
                        marginRight: "10px",
                        width: "180px"
                      }}
                    />
                    <FormsyText
                      name="Phone_Ext"
                      aria-label="Phone Extension"
                      validations="isNumeric"
                      maxLength="6"
                      validationError={numError}
                      type="tel"
                      hintText="Ext"
                      hintStyle={hintStyle}
                      style={{ width: "66px", verticalAlign: "bottom" }}
                    />
                  </div>
                ) : (
                  <div>
                    <FormLabel>Phone (International)</FormLabel>
                    <FormsySelect
                      name="Phone_Cntry_Cd_02"
                      aria-label="Phone Country Code"
                      style={{ verticalAlign: "bottom", marginRight: "10px" }}
                      hintText="Country Code"
                      hintStyle={hintStyle}
                    >
                      {phoneCodes}
                    </FormsySelect>
                    <FormsyText
                      name="Phone_International"
                      aria-label="Phone International"
                      validations="isNumeric"
                      validationError={numError}
                      hintText="5555555555"
                      hintStyle={hintStyle}
                      type="tel"
                      style={{
                        verticalAlign: "top",
                        marginRight: "10px",
                        width: "180px"
                      }}
                    />
                    <FormsyText
                      name="Phone_International_Ext"
                      aria-label="Phone International Extension"
                      validations="isNumeric"
                      maxLength="6"
                      validationError={numError}
                      type="tel"
                      hintText="Ext"
                      hintStyle={hintStyle}
                      style={{ verticalAlign: "top", width: "66px" }}
                    />
                  </div>
                )}

                <FormLabel>Gender *</FormLabel>
                <FormsyRadioGroup
                  name="Gender"
                  aria-label="Gender"
                  required
                  style={{ margin: "10px" }}
                >
                  <FormsyRadio value="M" label="Male" aria-label="Male" />
                  <FormsyRadio value="F" label="Female" aria-label="Female" />
                </FormsyRadioGroup>
                {/* }
                            <FormLabel>Phone (Mobile)</FormLabel>
                            <FormsyText
                              name="Phone_Mobile"
                              validations="isNumeric"
                              maxLength="10"
                              type="tel"
                              validationError={numError}
                              hintText="5555555555"
                              style={{ verticalAlign: 'bottom', marginRight: '10px' }}
                            />  */}

                <p style={{ color: "rgb(231, 16, 0)" }}>
                  * denotes required field
                </p>
                <RaisedButton
                  type="submit"
                  label="Submit"
                  disabled={!this.state.canSubmit || this.props.isSubmitting}
                />
              </Formsy.Form>
              <Dialog
                title="Error"
                actions={actions}
                modal={false}
                open={this.props.errorMessage !== ""}
                onRequestClose={() => {
                  this.props.handleErrorClick();
                }}
              >
                {this.props.errorMessage}
              </Dialog>
            </div>
          )}
        </Paper>
      </Card>
    );
  }
}

Delegated.childContextTypes = {
  muiTheme: PropTypes.object
};

Delegated.propTypes = {
  addressStates: PropTypes.array,
  addressCountries: PropTypes.array,
  handleSubmit: PropTypes.func,
  handleCountryChange: PropTypes.func,
  isLoading: PropTypes.bool,
  isSubmitted: PropTypes.bool,
  isSubmitting: PropTypes.bool,
  handleErrorClick: PropTypes.func,
  errorMessage: PropTypes.string,
  children: PropTypes.node
};
