import React from 'react';
import {observer, inject} from 'mobx-react';
import bind from 'bind-decorator';
import {
  Avatar,
  Card,
  CardActions,
  CardHeader,
  CardMedia,
  CardTitle,
  AutoComplete,
  CardText,
  FlatButton,
  Divider,
  IconMenu,
  RaisedButton,
  Toolbar,
  TextField,
  DatePicker,
  FontIcon,
  SelectField,
  MenuItem,
  ToolbarGroup,
  FloatingActionButton,
  ToolbarSeparator,
  IconButton,
  ToolbarTitle,
  RadioButton, RadioButtonGroup, DropDownMenu,
  Tabs, Tab,
} from 'material-ui';
import moment from 'moment';
import {withRouter} from 'react-router';
import {BrowserRouter as Router, Link, Route} from 'react-router-dom';
import StarBorder from 'material-ui/svg-icons/toggle/star-border';
import ContentAdd from 'material-ui/svg-icons/content/add';
import ContentMin from 'material-ui/svg-icons/content/remove';
import get from 'lodash.get';
import Loader from 'react-loader-advanced';
import LoadingDialog from "../../LoadingDialog";

import '../style.scss';
import {appConfig} from "../../../config/app";

@inject('appstate')
@observer
export default class CheckSchedule extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      maskapai: "",
      returnDateDisabled: true,
      depatureAirport: '',
      destinationAirport: '',
      adult: 1,
      children: 0,
      baby: 0,
      value: 0,
      searchTimeoutId: false
    };
    this.defaultState = Object.assign({}, this.state);
    this.http = props.appstate.http;
    this.authStore = props.appstate.auth;
    this.airlinesDomestic = props.appstate.airlinesDomestic;
    this.airports = props.appstate.airports;
    this.globalUI = props.appstate.globalUI;
  }

  componentDidMount() {

    this.globalUI.openLoading();
    this.airlinesDomestic.getAllAirlines()
    .then(res => {
      return this.authStore.getProfile();
      // return Promise.resolve(true);
    })
    .then(() => {
      this.globalUI.closeLoading();
    });
  }

  handleRadioButton = (event, value) => {
    let a;
    if (value == 'return') {
      a = false;
    }
    else {
      a = true;
    }
    this.setState({
      returnDateDisabled: a
    })
  };

  dateHandler = (date, format) => {
    return moment((date) ? date : new date()).format((format) ? format : "DD-MMM-YYYY");
  };

  handleTypeTrip = (event, index, value) => {
    console.log(value, 'val');
    if (value === 1) {
      this.setState({
        returnDateDisabled: false
      })
    } else {
      this.setState({
        returnDateDisabled: true
      })
    }
    this.setState({value});
  }


  handleAirplaneClass = (event, index, value) => {
    console.log(value, 'val');
  }


  handleDepartureAirport = (event, index, value) => {
    console.log(event, index, value);
    this.airports.setSelectedAirport(event.iata_code, 'departure');
    this.airlinesDomestic.setDepartureAirport(event.iata_code);
  };

  handleSearchAirport = (searctText, dataSource, params) => {
    // console.log(searctText);
  
    if (searctText === '') {
      return;
    }

    if (this.state.searchTimeoutId) {
      clearTimeout(this.state.searchTimeoutId);
    }

    const searchTimeoutId = setTimeout(() => {
      this.airports.searchAirports(searctText);
    }, 322);

    this.setState({searchTimeoutId});
  };

  handleArrivalAirport = (event, index, value) => {
    this.airports.setSelectedAirport(event.iata_code, 'arrival');
    this.airlinesDomestic.setArrivalAirport(event.iata_code);
  };

  handleChange = (event, index, value) => {
    this.airlinesDomestic.setSelectedAirline(value);
  };

  handleAdult = (event, value) => {
    this.airlinesDomestic.setAdult(value);
  };

  handleChild = (event, value) => {
    this.airlinesDomestic.setChild(value);
  };

  handleInfant = (event, value) => {
    this.airlinesDomestic.setInfant(value);
  };

  handleDepartureDate = (event, date) => {
    this.airlinesDomestic.setDepartureDate(this.dateHandler(date, "DD-MMM-YYYY"));
  };

  handleArrivalDate = (event, date) => {
    this.airlinesDomestic.setArrivalDate(this.dateHandler(date, "DD-MMM-YYYY"));
  };

  handleOpenMenu = () => {
    this.setState({
      openMenu: true,
    });
  }

  handleOnRequestChange = (value) => {
    this.setState({
      openMenu: value,
    });
  }

  submit = () => {
    this.airlinesDomestic.searchAirlines();
    this.props.history.push('/app/service/airlines/search');
  }

  render() {

    const styles = {

      radioButton: {
        marginBottom: 16,
      },
    };

    let airlines = [];
    let departureAirports = [];
    let arrivalAirports = [];
    this.airlinesDomestic.lists.map((item) => {
      airlines.push(<MenuItem key={item.id} innerDivStyle={{fontSize: 12}} value={item.code}
                              primaryText={<div className="primaryTextList">
                                <span style={{fontWeight: 600}}>{item.name}</span>
                              </div>}/>);
    });
    this.airports.lists.map((item) => {
      departureAirports.push(<MenuItem key={item.id} innerDivStyle={{fontSize: 12}} value={item.id}
                                       primaryText={<div className="primaryTextList">
                                         <span style={{fontWeight: 600}}>{item.name}</span>
                                       </div>}/>);
      arrivalAirports.push(<MenuItem key={item.id} innerDivStyle={{fontSize: 12}} value={item.id}
                                     primaryText={
                                       <div className="primaryTextList">
                                         <span style={{fontWeight: 600}}>{item.name}</span>
                                       </div>
                                     }/>);


    })

    const count = [
      <MenuItem key={0} value={0} primaryText="0"/>,
      <MenuItem key={1} value={1} primaryText="1"/>,
      <MenuItem key={2} value={2} primaryText="2"/>,
      <MenuItem key={3} value={3} primaryText="3"/>,
      <MenuItem key={4} value={4} primaryText="4"/>,
      <MenuItem key={5} value={5} primaryText="5"/>,
    ];

    return (
      <div className="row">
        <div className="col s12">
          <Card className="animated fadeIn cardLite">
            <CardHeader
              title="Airlines"
              titleColor={"#ffffff"}
              style={{background: 'rgb(43, 57, 145)', borderRadius: '4px 4px 0 0'}}
              subtitleStyle={{fontSize: 12, color: "rgba(255, 255, 255, 0.54)"}}
              subtitle="Domestic & International"
              avatar={<Avatar backgroundColor={"transparent"}
                              style={{borderRadius: 'none', height: 20, width: 20, marginRight: 16, marginTop: 8}}
                              src="/assets/images/icon/service/icon-airport-window.png"/>}
            />
            <Divider/>
            <Loader
              show={this.globalUI.loadingVisibility} message={<LoadingDialog/>}
              messageStyle={{textAlign: 'center'}}
              backgroundStyle={{backgroundColor: 'rgba(255,255,255,0.5)'}}>
              <div style={{padding: '24px 14px 14px 14px'}}>
                <div className="row no-margin">
                  <div className="col s6 l2 m2">
                    <SelectField
                      fullWidth={true}
                      value={this.airlinesDomestic.isReturn}
                      onChange={(event, index, value) => {
                        if (value === 0) {
                          this.airlinesDomestic.setOneway();
                        } else {
                          this.airlinesDomestic.setReturn();
                        }
                      }}
                      underlineStyle={{display: "none"}}
                      style={{
                        fontSize: 12,
                        fontWeight: 500,
                        height: 'auto',
                        padding: '8px 0 0 8px',
                        borderRadius: "2px",
                        backgroundColor: 'rgba(153,153,153,0.2)'
                      }}
                      labelStyle={{height: 'auto', lineHeight: "24px"}}
                      iconStyle={{padding: 0, top: "-10px", fill: '#4b5077'}}
                    >
                      <MenuItem value={0} primaryText="One Way"/>
                      <MenuItem value={1} primaryText="Return"/>
                    </SelectField>
                  </div>

                  <div className="col s6 l2 m2">
                    <IconMenu
                      style={{display: 'block'}}
                      anchorOrigin={{horizontal: 'left', vertical: 'top'}}
                      targetOrigin={{horizontal: 'left', vertical: 'top'}}
                      iconButtonElement={<FlatButton fullWidth={true} style={{height: 32, lineHeight: '32px'}}
                                                    backgroundColor={'rgba(153,153,153,0.2)'}
                                                    label={`${this.airlinesDomestic.totalPassenger} Passenger`}/>}
                      open={this.state.openMenu}
                      onRequestChange={this.handleOnRequestChange}
                    >
                      <div className="row no-margin" style={{minWidth: 200, padding: 8}}>
                        <div className="listAdult">
                          <h3>Adult</h3>
                          <TextField type='number' value={this.airlinesDomestic.queries.adult} onChange={this.handleAdult}
                                    fullWidth={true}/>

                        </div>
                        <div className="listAdult">
                          <h3>Children
                            <p className="helperTextList">Aged 2 - 12</p>
                          </h3>
                          <TextField type='number' value={this.airlinesDomestic.queries.child} onChange={this.handleChild}
                                    fullWidth={true}/>

                        </div>
                        <div className="listAdult">
                          <h3>Infant <p className="helperTextList">Below 2</p></h3>

                          <TextField type='number' value={this.airlinesDomestic.queries.infant}
                                    onChange={this.handleInfant} fullWidth={true}/>
                        </div>

                      </div>
                      <div className="passengerAction">
                        <FlatButton label="Done" labelStyle={{color: "#6772e5"}}
                                    onClick={() => this.setState({openMenu: false})}/>
                        {/*<FlatButton label="Cancel" onClick={() => this.setState({openMenu: false})}/>*/}
                      </div>
                    </IconMenu>


                  </div>
                  <div className="col s12 l3 m3">
                    <SelectField
                      value={this.airlinesDomestic.selectedAirline}
                      onChange={this.handleChange}
                      fullWidth={true}
                      underlineStyle={{display: "none"}}
                      style={{
                        fontSize: 12,
                        fontWeight: 500,
                        height: 'auto',
                        padding: '8px 0 0 8px',
                        borderRadius: "2px",
                        backgroundColor: 'rgba(153,153,153,0.2)'
                      }}
                      labelStyle={{height: 'auto', lineHeight: "24px"}}
                      iconStyle={{padding: 0, top: "-10px", fill: '#4b5077'}}

                    >
                      <MenuItem key={0} value="" primaryText="All Airlines" disabled={false} style={{fontWeight: 600, fontSize: 12}}/>
                      <Divider/>
                      {airlines}
                    </SelectField>
                  </div>
                  <div className="col s12 l3 m3">
                    <SelectField
                      fullWidth={true}
                      value={this.state.value}
                      onChange={this.handleAirplaneClass}
                      underlineStyle={{display: "none"}}
                      style={{
                        fontSize: 12,
                        fontWeight: 500,
                        height: 'auto',
                        padding: '8px 0 0 8px',
                        borderRadius: "2px",
                        backgroundColor: 'rgba(153,153,153,0.2)'
                      }}
                      labelStyle={{height: 'auto', lineHeight: "24px"}}
                      iconStyle={{padding: 0, top: "-10px", fill: '#4b5077'}}
                    >
                      <MenuItem value={0} primaryText="Economy"/>
                      <MenuItem value={1} primaryText="Business"/>
                      <MenuItem value={2} primaryText="VIP"/>
                    </SelectField>
                  </div>

                </div>
                <div className="row" style={{marginTop: 20}}>
                  <div className="col s6 l3 m3">
                    <div style={{marginTop: '12px'}}>
                      <p className="label-form">Departure</p>
                      <AutoComplete
                        hintText="Where from?"
                        maxSearchResults={20}
                        dataSource={this.airports.listForSearch.map(list => {
                          return {
                            iata_code: list.iata_code,
                            key: `${(list.city || {name: ''}).name} (${list.name} - ${list.iata_code})`,
                            text: `${(list.city || {name: ''}).name} (${list.name} - ${list.iata_code})`,
                            value: (<MenuItem anchorOrigin={{horizontal: 'left', vertical: 'center'}}
                                              innerDivStyle={{fontSize: 12}}
                                              primaryText={<div className="primaryTextListMap"><span
                                                style={{fontWeight: 600}}>{`${(list.city || {name: ''}).name} (${list.name} - ${list.iata_code})`}</span>
                                              </div>}/>)
                          }
                        })}
                        filter={AutoComplete.caseInsensitiveFilter}
                        onNewRequest={this.handleDepartureAirport}
                        onUpdateInput={this.handleSearchAirport}
                        openOnFocus={true}
                        menuStyle={{maxHeight: 300, fontSize: 12}}
                        fullWidth={true}
                        popoverProps={{
                          autoWidth: true,
                          style: {width: '600px'},
                          width: 600
                        }}
                      />
                    </div>
                  </div>
                  <div className="col s6 m3 l3">
                    <div style={{marginTop: '12px'}}>
                      <p className="label-form">Destination</p>
                      <AutoComplete
                        hintText="Where to?"
                        maxSearchResults={20}
                        dataSource={this.airports.listForSearch.map(list => {
                          return {
                            iata_code: list.iata_code,
                            key: `${(list.city || {name: ''}).name} (${list.name} - ${list.iata_code})`,
                            text: `${(list.city || {name: ''}).name} (${list.name} - ${list.iata_code})`,
                            value: (<MenuItem anchorOrigin={{horizontal: 'left', vertical: 'center'}}
                                              innerDivStyle={{fontSize: 12}}
                                              primaryText={<div className="primaryTextListMap"><span
                                                style={{fontWeight: 600}}>{`${(list.city || {name: ''}).name} (${list.name} - ${list.iata_code})`}</span>
                                              </div>}/>)
                          }
                        })}
                        filter={AutoComplete.caseInsensitiveFilter}
                        onNewRequest={this.handleArrivalAirport}
                        onUpdateInput={this.handleSearchAirport}
                        openOnFocus={true}
                        menuStyle={{maxHeight: 300, fontSize: 12}}
                        fullWidth={true}
                        popoverProps={{
                          autoWidth: true,
                          style: {width: '600px'},
                          width: 600
                        }}
                      />
                    </div>
                  </div>
                  <div className="col s6 m3 l3">
                    <div style={{marginTop: '12px'}}>
                      <p className="label-form">Departure Date</p>
                      <DatePicker 
                        defaultDate={this.airlinesDomestic.queries.departuredate ? moment(this.airlinesDomestic.queries.departuredate, "DD-MMM-YYYY").toDate() : ""} 
                        fullWidth={true} 
                        style={{width: '100%'}} 
                        hintText="2017-08-17"
                        onChange={this.handleDepartureDate}/>
                    </div>
                  </div>
                  <div className="col s6 m3 l3">
                    <div style={{marginTop: 12}}>
                      <p className="label-form">Return Date</p>
                      <DatePicker 
                        defaultDate={this.airlinesDomestic.queries.arrivaldate ? moment(this.airlinesDomestic.queries.arrivaldate, "DD-MMM-YYYY").toDate() : moment().add(2, 'days').toDate()}
                        underlineDisabledStyle={{
                          borderBottom: '1.5px dotted #0000004d'
                        }} 
                        fullWidth={true} 
                        disabled={this.airlinesDomestic.isReturn !== 1} 
                        style={{width: '100%'}}
                        onChange={this.handleArrivalDate}/>
                    </div>
                  </div>
                </div>
                <div className="row">
                  {/*<div className="col s12 l6">*/}
                  {/*<div>*/}
                  {/*<p className="label-form">Airlines</p>*/}
                  {/*<SelectField*/}
                  {/*value={this.airlinesDomestic.selectedAirline}*/}
                  {/*onChange={this.handleChange}*/}
                  {/*fullWidth={true}*/}
                  {/*>*/}
                  {/*<MenuItem key={0} value="" primaryText="All Airlines" disabled={false}/>*/}
                  {/*<Divider/>*/}
                  {/*{airlines}*/}
                  {/*</SelectField>*/}
                  {/*</div>*/}
                  {/*</div>*/}

                  <div className="col s12 l6">
                    {/*<div>*/}
                    {/*<p className="label-form">Type journey</p>*/}
                    {/*<RadioButtonGroup name="shipSpeed"*/}
                    {/*style={{marginTop: 20, display: 'flex'}}*/}
                    {/*defaultSelected='oneway'*/}
                    {/*onChange={this.handleRadioButton}*/}
                    {/*>*/}
                    {/*<RadioButton*/}
                    {/*value="oneway"*/}
                    {/*label="Oneway"*/}
                    {/*style={{width: 'auto', marginRight: 10}}*/}
                    {/*/>*/}
                    {/*<RadioButton*/}
                    {/*value="return"*/}
                    {/*label="Return"*/}
                    {/*style={{width: 'auto'}}*/}
                    {/*/>*/}
                    {/*</RadioButtonGroup>*/}

                    {/*</div>*/}


                  </div>
                </div>

                {/*<div className="row" style={{marginTop: '-8px'}}>*/}
                {/*<div className="col s12 l4">*/}
                {/*<p className="label-form">Adult</p>*/}
                {/*<SelectField*/}
                {/*value={this.airlinesDomestic.queries.adult}*/}
                {/*onChange={this.handleAdult}*/}
                {/*fullWidth={true}*/}
                {/*>*/}
                {/*{count}*/}
                {/*</SelectField>*/}
                {/*<p className="helperText">Age above 12 years</p>*/}
                {/*</div>*/}
                {/*<div className="col s12 l4">*/}
                {/*<p className="label-form">Child</p>*/}
                {/*<SelectField*/}
                {/*value={this.airlinesDomestic.queries.child}*/}
                {/*onChange={this.handleChild}*/}
                {/*fullWidth={true}*/}
                {/*>*/}
                {/*{count}*/}
                {/*</SelectField>*/}
                {/*<p className="helperText">2 to 12 years</p>*/}
                {/*</div>*/}
                {/*<div className="col s12 l4">*/}
                {/*<p className="label-form">Baby</p>*/}
                {/*<SelectField*/}
                {/*value={this.airlinesDomestic.queries.infant}*/}
                {/*onChange={this.handleInfant}*/}
                {/*fullWidth={true}*/}
                {/*>*/}
                {/*{count}*/}
                {/*</SelectField>*/}
                {/*<p className="helperText">Age below 2 years</p>*/}
                {/*</div>*/}
                {/*</div>*/}

                <div className="row">
                  <div className="col s0 l10"></div>
                  <div className="col s0 l2">
                    <RaisedButton 
                      onClick={this.submit} 
                      label="Find Schedule" 
                      primary={true}
                      icon={<FontIcon className="material-icons">search</FontIcon>}/>
                  </div>
                </div>

              </div>
            </Loader>
          </Card>
        </div>
      </div>
    )
  }
}
