import React, { Component, PropTypes } from 'react';
import { Dialog, FlatButton, Paper } from 'material-ui';

import Spacing from 'material-ui/styles/spacing';
import { yellow800 } from 'material-ui/styles/colors';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import UCdefaultTheme from '../../themes/DefaultTheme';

import InputField from './InputField';
import './UCIDLookup.css';

export default class UCIDLookup extends Component {
  constructor() {
    super(...arguments);

    this.clearDialog = this.clearDialog.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
    this.renderSearchResults = this.renderSearchResults.bind(this);
  }

  getChildContext() {
    const theme = getMuiTheme(UCdefaultTheme);
    theme.appBar.textColor = 'black';
    theme.appBar.spacing = Spacing.desktopSubheaderHeight;
    theme.flatButton.secondaryColor = yellow800;
    theme.flatButton.primaryColor = '#e00122';

    return {
      muiTheme: theme,
    };
  }

  clearDialog() {
    this.searchTextField.setValue('');
  }


  handleInputChange(event) {
    if (event.target.value.length === 9) {
      this.props.fetchUCID(event.target.value);
    }
  }

  renderSearchResults() {
    if (this.props.lookupData.status === 'Success') {
      return (
        <Paper zDepth={1}>
          <div className="ih-ucid-lookup-result">
            <div style={{ fontWeight: '800' }}>
              {this.props.lookupData.firstName} {this.props.lookupData.lastName}
            </div>
            <div>{this.props.lookupData.emplid}</div>
          </div>
        </Paper>
      );
    }

    return (
      <div style={{ lineHeight: '2em' }}>
        <div>{this.props.lookupData.description}</div>
      </div>
    );
  }

  render() {
    const ucDialogActions = [
      <FlatButton label="Clear" secondary onTouchTap={this.clearDialog} />,
      <FlatButton label="Close" primary onTouchTap={this.props.closeLookupDialog} />,
    ];

    return (
      <Dialog
        title="Lookup by UCID"
        actions={ucDialogActions}
        fullWidth
        open={this.props.open}
        ref={(c) => { this.lookupDialog = c; }}
      >
        <InputField
          defaultValue=""
          ref={(c) => { this.searchTextField = c; }}
          focus
          hintText="Enter full UCID to search"
          onChange={this.handleInputChange}
          maxLength={9}
        />
        {this.props.lookupData ? this.renderSearchResults() : null}
      </Dialog>
    );
  }
}

UCIDLookup.propTypes = {
  open: PropTypes.bool,
  fetchUCID: PropTypes.func,
  lookupData: PropTypes.object,
  closeLookupDialog: PropTypes.func.isRequired,
};

UCIDLookup.childContextTypes = {
  muiTheme: PropTypes.object,
};
