import React from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import { Switch, Route, BrowserRouter } from 'react-router-dom'
import DatePicker from 'material-ui/DatePicker';
import areIntlLocalesSupported from 'intl-locales-supported';
import RaisedButton from 'material-ui/RaisedButton';
import FlatButton from 'material-ui/FlatButton';
import Dialog from 'material-ui/Dialog';

import TextField from 'material-ui/TextField';

import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';

import { Link } from 'react-router-dom';
import axios from 'axios';
import AutoComplete from 'material-ui/AutoComplete';


let DateTimeFormat;

/**
 * Use the native Intl.DateTimeFormat if available, or a polyfill if not.
 */
if (areIntlLocalesSupported(['fr', 'fa-IR'])) {
  DateTimeFormat = global.Intl.DateTimeFormat;
} else {
  const IntlPolyfill = require('intl');
  DateTimeFormat = IntlPolyfill.DateTimeFormat;
  require('intl/locale-data/jsonp/fr');
  require('intl/locale-data/jsonp/fa-IR');
  require('intl/locale-data/jsonp/ha-Arab.js');
  require('intl/locale-data/jsonp/fr-FR.js');
  require('intl/locale-data/jsonp/ru-RU.js');
  require('intl/locale-data/jsonp/de-DE.js');
  require('intl/locale-data/jsonp/eu-ES.js');
}

const inlineStyles = {
  componentLayout: {
    width: '50%',
},
  componentLayout2: {
    width: '25%',

  },
}

const TextInputColorButton = 'rgb(234, 234, 234)';
const TextInputColor = 'white';

export default class CreateCorrida extends React.Component {

  constructor(props) {
    super(props);
    this.errors = {
      precoError: -1,
      motoristaError: 2,
    }
    this.state = {
      toggleForm: false,
      toggleAlert1: false,
      corridaPreco: -1,
      corridaIdMotorista: -1,
      corridaIdPassageiro: -1,
      listPassageirosNomes: [],
      listMotoristasNomes: [],
      listPassageiros: [],
      listMotoristas: [],
      dataCorrect: false,
    }
  }

  componentDidMount() {

    axios.all([
      axios.get("https://gerencia-corridas.herokuapp.com/api/select-passageiro"),
      axios.get("https://gerencia-corridas.herokuapp.com/api/select-motorista-ativo"),
    ]).then(axios.spread((passageiros, motoristas) => {
      let listPassageirosNomes = [];
      let listMotoristasNomes = [];

      passageiros.data.map((psg) => {
        listPassageirosNomes.push({ nome: psg.Nome + ' CPF: ' + psg.CPF, id: psg.idPassageiro });
      });
      motoristas.data.map((mtr) => {
        listMotoristasNomes.push({ nome: mtr.Nome + ' CPF: ' + mtr.CPF, cpf: mtr.CPF, id: mtr.idMotorista });
      });
      if (motoristas.data.length == 0) {

        this.errors.motoristaError = "Não há motoristas disponíveis no momento, ative algum"
      }

      this.setState({ listPassageirosNomes, listMotoristasNomes, listPassageiros: passageiros.data, listMotoristas: motoristas.data });

    }));
  }

  handlePreco(Preco) {
    let PrecoRegx = new RegExp(/^\d{1,5}(?:\.\d{0,10}){0,1}$/);
    if (PrecoRegx.test(Preco)) {
      this.errors.precoError = 2;
      this.setState({ corridaPreco: parseFloat(Preco) });
    } else {
      this.errors.precoError = "Digite um preco valido";
      this.setState({ dataCorrect: false })
    }
  }

  handleAlert1(fun) {
    if (fun) this.setState({ toggleAlert1: true });
    else this.setState({ toggleAlert1: false });
  }

  handleCadastrar() {

    let keysError = Object.keys(this.errors)
    let allDataIsCorrect = true;
    keysError.map((key) => {
      if (this.errors[key] != 2) {
        allDataIsCorrect = false;
      }
    })

    if (this.state.corridaIdMotorista == -1 || this.state.corridaIdPassageiro == -1) {
      allDataIsCorrect = false;
    }
    if (!allDataIsCorrect) {
      this.handleAlert1(true);
      return;
    }

    //Se todas condições foram prometidas
    let NovaCorrida = {}
    NovaCorrida.preco = parseFloat(this.state.corridaPreco);
    NovaCorrida.idMotorista = this.state.corridaIdMotorista;
    NovaCorrida.idPassageiro = this.state.corridaIdPassageiro;

    //console.log(">>>", NovaCorrida);
    //this.props.Home.props.history.push('/teste');

    axios.post("https://gerencia-corridas.herokuapp.com/api/insert-corrida", { NovaCorrida }).then((response) => {
      if (response.status == 200) {
        this.props.ListCorridas.setState({ listCorridas: response.data });
        this.setState({ toggleForm: !this.state.toggleForm })
      } else {
        console.log("Algum problema no insert do corridas");
      }
    })


  }

  render() {

    const { Home } = this.props;
    return (
      <MuiThemeProvider >
        <div className="container">
          <div className="row col-md-12 col-md-offset-3">
            <RaisedButton
              style={{ width: '50%' }}
              backgroundColor={!this.state.toggleForm ? TextInputColor : 'rgb(255, 109, 109)'}
              onClick={(evt) => {
                this.setState({ toggleForm: !this.state.toggleForm })
              }}
            >{this.state.toggleForm ? "Cancelar" : "Registrar Corrida"}</RaisedButton>
          </div>
          {!this.state.toggleForm ? null :
            <div>
              <div className="row col-md-12 col-md-offset-3 " style={inlineStyles.componentLayout}>
                <AutoComplete
                  floatingLabelText="Nome do Passageiro"
                  filter={AutoComplete.fuzzyFilter}
                  dataSourceConfig={{ text: 'nome', value: 'id' }}
                  dataSource={this.state.listPassageirosNomes}
                  maxSearchResults={5}
                  openOnFocus={true}
                  onUpdateInput={(input, dataSource, params) => {
                    this.setState({ corridaIdPassageiro: -1 })
                  }}
                  onNewRequest={(chosenRequest, index) => {
                    this.setState({ corridaIdPassageiro: chosenRequest.id })
                  }}
                  fullWidth={true}
                  floatingLabelStyle={{ color: TextInputColor }}
                  inputStyle={{ color: TextInputColor }}
                />
              </div>
              <div className="row col-md-12 col-md-offset-3" style={inlineStyles.componentLayout}>
                <AutoComplete
                  floatingLabelText="Nome do Motorista"
                  filter={AutoComplete.fuzzyFilter}
                  dataSource={this.state.listMotoristasNomes}
                  dataSourceConfig={{ text: 'nome', value: 'id' }}
                  maxSearchResults={5}
                  openOnFocus={true}
                  fullWidth={true}
                  onUpdateInput={(input, dataSource, params) => {
                    this.setState({ corridaIdMotorista: -1 })
                  }}
                  onNewRequest={(chosenRequest, index) => {
                    this.setState({ corridaIdMotorista: chosenRequest.id })
                  }}
                  errorText={this.errors.motoristaError == -1 || this.errors.motoristaError == 2 ? null : this.errors.motoristaError}
                  floatingLabelStyle={{ color: TextInputColor }}
                  inputStyle={{ color: TextInputColor }}
                />
              </div>
              <div className="row col-md-12 col-md-offset-3">
                <TextField
                  key={'corrida-preco'}
                  onChange={(evt, value) => {
                    this.handlePreco(value)
                  }}
                  floatingLabelText="Preço da corrida i.g. (12.34)"
                  errorText={this.errors.precoError == -1 || this.errors.precoError == 2 ? null : this.errors.precoError}
                  floatingLabelStyle={{ color: TextInputColor }}
                  underlineStyle={{ color: TextInputColor }}
                  inputStyle={{ color: TextInputColor }}
                  style={inlineStyles.componentLayout2}
                />
              </div>
              <div className="row col-md-12 col-md-offset-3">
                <RaisedButton backgroundColor="rgb(187, 255, 135)"
                  style={inlineStyles.componentLayout}
                  onClick={this.handleCadastrar.bind(this)}> Cadastrar
                </RaisedButton>
                <Dialog
                  actions={<FlatButton label="Ok" primary={true} onClick={(evt) => {
                    this.handleAlert1(false)
                  }} />}
                  modal={false}
                  open={this.state.toggleAlert1}
                  onRequestClose={() => { this.handleAlert1(false) }}
                >
                  Faltam campos ou preenchimento com dados incorretos.
                </Dialog>
              </div>
            </div>}
        </div>

      </MuiThemeProvider>
    )
  }
}