import React from 'react';
import {observer, inject} from 'mobx-react';
import bind from 'bind-decorator';
import {
  Card,
  CardActions,
  CardHeader,
  CardMedia,
  CardTitle,
  AutoComplete,
  CardText,
  FlatButton,
  Divider,
  RaisedButton,
  Toolbar,
  DatePicker,
  FontIcon,
  SelectField,
  MenuItem,
  ToolbarGroup,
  FloatingActionButton,
  ToolbarSeparator,
  IconButton,
  ToolbarTitle,
  TextField,
  RadioButton, RadioButtonGroup, DropDownMenu,
  Tabs,
  Tab,
  Step,
  Stepper,
  StepLabel,
} from 'material-ui';
import {withRouter} from 'react-router';
import {BrowserRouter as Router, 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 '../style.scss';
import {InputNumber} from 'antd';
import {appConfig} from "../../../config/app";
import AdultForm from './AdultForm';
import ChildForm from './ChildForm';
import BabyForm from './BabyForm';
import get from 'lodash.get';
import {LINKS} from '../../../routes';

@inject('appstate')
@observer
export default class FormBook extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      c_name: '',
      c_email: '',
      c_phone: '',
    };
    this.defaultState = Object.assign({}, this.state);
    this.http = props.appstate.http;
    this.authStore = props.appstate.auth;
    this.airlinesDomestic = props.appstate.airlinesDomestic;
    this.customerStore = props.appstate.customer;
    this.data = this.airlinesDomestic.selectedDepartureFlight;
    this.globalUI = props.appstate.globalUI;
  }

  componentDidMount() {
    console.log('Profile loaded!');
    // this.airlinesDomestic.setDepartureItem(this.airlinesDomestic.selectedDepartureFlight);
    window.scrollTo(0, 0);
  }

  handleCustomerName = (event, value) => {
    this.setState({
      c_name: value
    })
  };

  handleCustomerPhone = (event, value) => {
    this.setState({
      c_phone: value
    })
  };

  handleCustomerName = (event, value) => {
    this.setState({
      c_email: value
    })
  };

  firstName = (event, value) => {
    this.setState({
      firstNameCustomer: value
    })
  };

  lastName = (event, value) => {
    this.setState({
      lastNameCustomer: value
    })
  };

  email = (event, value) => {
    this.setState({
      emailCustomer: value
    })
  }

  getAirlineImage(airlineCode) {
    if (airlineCode !== 'multi') {
      return (this.airlinesDomestic.lists.find((value, index) => {
        if (airlineCode == value.code) {
          return true;
        }
      }) || {}).image_path
    } else {
      return '/assets/images/airlines/multi.png';
    }
  }

  getAirlineName(airlineCode) {
    return (this.airlinesDomestic.lists.find((value, index) => {
      if (airlineCode == value.code) {
        return true;
      }
    }) || {}).name
  }

  book() {
    this.airlinesDomestic.book()
      .then(res => {
        console.log(res);
        this.props.history.push(LINKS.SERVICE_AIRLINES_REVIEW + '/' + res.id);
      })
      .catch(err => {
        this.globalUI.openSnackbar(err.message);
      })
  }

  render() {
    var adult = [];
    for (var x = 0; x < this.airlinesDomestic.queries.adult; x++) {
      adult.push(x + 1);
    }

    var child = [];
    for (var y = 0; y < this.airlinesDomestic.queries.child; y++) {
      child.push(y + 1);
    }

    var baby = [];
    for (var z = 0; z < this.airlinesDomestic.queries.infant; z++) {
      baby.push(z + 1);
    }

    let priceOrder = (this.airlinesDomestic.totalForAdult) ? this.airlinesDomestic.totalForAdult.toLocaleString('en') : "0.00";
    let childTotal = (this.airlinesDomestic.totalForChild) ? this.airlinesDomestic.totalForChild.toLocaleString('en') : "0.00";
    let infantTotal = (this.airlinesDomestic.totalForInfant) ? this.airlinesDomestic.totalForInfant.toLocaleString('en') : "0.00";
    let totalForAll = (this.airlinesDomestic.totalForAll) ? this.airlinesDomestic.totalForAll.toLocaleString('en') : "0.00";
    let totalForAllWithServiceCharge = (this.airlinesDomestic.totalForAllWithServiceCharge) ? this.airlinesDomestic.totalForAllWithServiceCharge.toLocaleString('en') : "0.00";

    const {isReturn} = this.airlinesDomestic;

    // const isReturn = get(this.data, 'flights.length', 0) > 0;
    const data = get(this.data, 'flights[0]', {});
    const arrivalFlight = this.airlinesDomestic.selectedReturningFlight;

    return (
      <div className="row">
        <div className="col l12 m12 s12">
          <Card className="cardLite" style={{background: 'rgb(43, 57, 145)', marginBottom: 20}}>
            <div style={{width: '100%', margin: 'auto'}}>
              {(this.airlinesDomestic.isReturn) ? (<Stepper activeStep={1}>
                <Step>
                  <StepLabel style={{color: "white"}}>Select Departure Flight Schedule</StepLabel>
                </Step>
                <Step>
                  <StepLabel style={{color: "white"}}>Select Return Flight Schedule</StepLabel>
                </Step>
                <Step>
                  <StepLabel style={{color: "white"}}>Passengers Information & Booking</StepLabel>
                </Step>
                <Step>
                  <StepLabel style={{color: "white"}}>Payment & Issued Ticket</StepLabel>
                </Step>
              </Stepper>) : (<Stepper activeStep={1}>
                <Step>
                  <StepLabel style={{color: "white"}}>Select Departure Flight Schedule</StepLabel>
                </Step>
                <Step>
                  <StepLabel style={{color: "white"}}>Passengers Information & Booking</StepLabel>
                </Step>
                <Step>
                  <StepLabel style={{color: "white"}}>Payment & Issued Ticket</StepLabel>
                </Step>
              </Stepper>)}
            </div>
          </Card>
        </div>

        <div className="col s12 l12">
          <Card className="animated fadeIn cardLite" style={{marginBottom: 10}}>
            <Toolbar className="toolbarCard" style={{backgroundColor: '#fff', paddingLeft: 0}}>
              <ToolbarGroup>
                <IconButton
                  iconClassName="material-icons"
                  tooltip="Back"
                  style={{marginLeft: '0px'}}
                  onClick={() => this.props.history.goBack()}>
                  arrow_back
                </IconButton>
                <ToolbarTitle style={{fontSize: 14, fontWeight: 500, color: '#32325d'}} text={
                  <div>
                    {(this.airlinesDomestic.isReturn) ? (
                      <h3 className="no-margin" style={{lineHeight: "20px"}}>Select Return Flight Schedule</h3>
                    ) : (
                      <h3 className="no-margin" style={{lineHeight: "20px"}}>Select Departure Flight Schedule</h3>
                    )}
                    <p className="no-margin"
                       style={{lineHeight: "20px"}}>{(this.airlinesDomestic.isReturn) ? `${this.airlinesDomestic.queries.departuredate} - ${this.airlinesDomestic.queries.arrivaldate}` : this.airlinesDomestic.queries.departuredate}</p>
                  </div>
                }/>
              </ToolbarGroup>
            </Toolbar>

            <Divider/>
          </Card>
        </div>


        <div className="col s12 l12">
          <Card className="cardLite" style={{position: "relative"}}>
            <Card className="no-shadow" style={{position: "relative"}}>
              <div className="row row-departure">
                <div className="col s12 l12 mt-20">
                    <span
                      className="trip-time">Total Time: {this.data.durationhour}h {this.data.durationminute}m </span>
                  <div className="leg-type clearfix">
                    <span className="review-title gray">Departure</span>
                  </div>
                  <div className="sector-details">

                    {!!isReturn && ([
                      <section className="layover-seprator"></section>
                    ])}

                    {this.data.flights
                      .map(f => {
                        return (
                          [
                            ('layover_hour' in f && (
                              <div className="text-center row ">
                                <div className="col m2 l2"></div>
                                <div className="box-condensed pr col m10 l8 padd-none">
                                  <div className="block fs-sm msg-bar">
                                    <FontIcon className="material-icons"
                                              style={{
                                                top: "2px",
                                                marginRight: "2px",
                                                fontSize: 14
                                              }}>info_outline</FontIcon>Change
                                    planes at
                                    <span className="font-bold"> {f.fromcity_long} ({f.fromcity})</span>, Connecting
                                    Time:
                                    <span className="font-bold"> {f.layover_hour}h {f.layover_minute}m </span> |
                                    Flight
                                    may depart from a different terminal
                                  </div>
                                </div>
                              </div>
                            )),
                            <article className="row review-article">
                              <div className="align-center col s2 l2 text-xs-left sm-gutter-bottom">
                                <div>
                                  <img
                                    size="35"
                                    src={(this.data.no_of_flight - 1 === 0) ? this.getAirlineImage(this.data.airlinecode) : this.getAirlineImage('multi')}
                                    className="img-airlinesbook"/><br className="hidden-xs-down"/>
                                  <span className="ib fs-12 gray">
                                  {f.airline}
                                    <br/>
                                  <span className="fs-xs gray-light">{f.flightno}</span>
                                  <p className="font-12 gray-dark block font-bold">{f.classes[0].baggagekilos} kg</p>
                                  </span>

                                </div>
                              </div>
                              <div className="col s10 l10 bdr bdr-left">
                                <div className="row">
                                  <div className="col s6 m3 l3" style={{marginTop: 20}}>
                                    <p className="fs-base">{f.fromcity_long}</p>
                                    <h3 className="fs-24 lh28 bold gray-dark">{f.departtime}</h3>
                                    <p className="fs-sm gray">
                                      <span
                                        className="font-bold">{moment(f.departdate, 'DD-MMM-YYYY').format("ddd, DD MMMM YYYY")}</span>
                                      <br/>
                                      <span className="gray-light">
                                        {f.fromcity_airport}
                                      </span>
                                    </p>
                                  </div>

                                  <div className="col s12 text-center m6 l6 sm-gutter-top tab-posn-align">
                                    <div className="fs-13 flex" style={{justifyContent: "center"}}>
                                      <FontIcon className="material-icons"
                                                style={{fontSize: '18px', lineHeight: "14px"}}>schedule</FontIcon>
                                      &nbsp; {f.durationhour}h {f.durationminute}m &nbsp;
                                    </div>
                                    <div className="hide-on-small-only two-dots">
                                      <FontIcon className="material-icons rotate-right"
                                                style={{color: '#B7B7B7', top: '-12px'}}>flight</FontIcon>
                                    </div>
                                    <div className="fs-13">
                                      <SelectField
                                        className="select-seat"
                                        floatingLabelText={"Choose seat"}
                                        style={{fontSize: 14, marginTop: "-10px"}}
                                        floatingLabelStyle={{left: "170px", fontSize: "18px", color: '#000'}}
                                        value={f.selected_class}
                                        menuItemStyle={{paddingRight: 0}}
                                        fullWidth={true}
                                        onChange={(event, index, value) => this.airlinesDomestic.setSelectedClassForFlightCode(f.flightno, value, 'departure')}>
                                        {f.classes.map(classes => {
                                          return (
                                            <MenuItem
                                              value={classes.code}
                                              primaryText={`${classes.code} - ${(classes.fare) ? classes.fare.toLocaleString('en') : "0.00"} - ${classes.cabin}`}/>);
                                        })}
                                      </SelectField>
                                    </div>
                                  </div>

                                  <div className="col s6 m3 l3 sm-border-left" style={{marginTop: 20}}>
                                    <p className="fs-base">{f.tocity_long}</p>
                                    <h3 className="fs-24 lh28 bold gray-dark">{f.arrivetime}</h3>
                                    <p className="fs-sm gray">
                                      <span
                                        className="font-bold">{moment(f.arrivaldate, 'DD-MMM-YYYY').format("ddd, DD MMMM YYYY")}</span>
                                      <br/>
                                      <span className="gray-light">
                                        {f.tocity_airport}
                                      </span>
                                    </p>
                                  </div>


                                </div>
                              </div>
                            </article>
                          ]

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

            {!!isReturn && (
              <Card className="cardLite" style={{position: "relative"}}>
                <div className="row mb-10">
                  <div className="col s12 l12">
                    <span
                      className="trip-time">Total Time: {arrivalFlight.durationhour}h {arrivalFlight.durationminute}m </span>
                    <div className="leg-type clearfix">
                      <span className="review-title gray">Returning</span>
                    </div>
                    <div className="sector-details">

                      {!!isReturn && ([
                        <section className="layover-seprator"></section>
                      ])}

                      {arrivalFlight.flights
                        .map(f => {
                          return (
                            [
                              ('layover_hour' in f && (
                                <div className="text-center row ">
                                  <div className="col m2 l2"></div>
                                  <div className="box-condensed pr col m10 l8 padd-none">
                                    <div className="block fs-sm msg-bar">
                                      <FontIcon className="material-icons"
                                                style={{
                                                  top: "2px",
                                                  marginRight: "2px",
                                                  fontSize: 14,
                                                  color: '#000'
                                                }}>info_outline</FontIcon>Change
                                      planes at
                                      <span className="font-bold"> {f.fromcity_long} ({f.fromcity})</span>, Connecting
                                      Time:
                                      <span className="font-bold"> {f.layover_hour}h {f.layover_minute}m </span> |
                                      Flight may depart from a different terminal
                                    </div>
                                  </div>
                                </div>
                              )),
                              <article className="row review-article">
                                <div className="align-center col s2 l2 text-xs-left sm-gutter-bottom">
                                  <div>
                                    <img
                                      size="35"
                                      src={(arrivalFlight.no_of_flight - 1 === 0) ? this.getAirlineImage(f.airlinecode) : this.getAirlineImage('multi')}
                                      className="img-airlinesbook"/><br className="hidden-xs-down"/>
                                    <span className="ib fs-12 gray">{f.airline}
                                      <br/>
                                      <span className="fs-xs gray-light">{f.flightno}</span>
                                       <p
                                         className="font-12 gray-dark block font-bold">{f.classes[0].baggagekilos}
                                         kg</p>

                                    </span>

                                  </div>
                                </div>
                                <div className="col s10 l10 bdr bdr-left">
                                  <div className="row">
                                    <div className="col s6 m3 l3" style={{marginTop: 20}}>
                                      <p className="fs-base">{f.fromcity_long}</p>
                                      <h3 className="fs-24 lh28 bold gray-dark">{f.departtime}</h3>
                                      <p className="fs-sm gray">
                                        <span
                                          className="font-bold">{moment(f.departdate, 'DD-MMM-YYYY').format("ddd, DD MMMM YYYY")}</span>
                                        <br/>
                                        <span className="gray-light">
                                          {f.fromcity_airport} 
                                        </span>
                                      </p>
                                    </div>

                                    <div className="col s12 text-center m6 l6 sm-gutter-top tab-posn-align">
                                      <div className="fs-13 flex" style={{justifyContent: "center"}}>
                                        <FontIcon className="material-icons"
                                                  style={{fontSize: '18px', lineHeight: "14px"}}>schedule</FontIcon>
                                        &nbsp; {f.durationhour}h {f.durationminute}m &nbsp;
                                      </div>
                                      <div className="hide-on-small-only two-dots">
                                        <FontIcon className="material-icons rotate-right"
                                                  style={{color: '#B7B7B7', top: '-12px'}}>flight</FontIcon>
                                      </div>
                                      <div className="fs-13">
                                        <SelectField
                                          floatingLabelText={"Choose seat"}
                                          className="select-seat"
                                          fullWidth={true}
                                          style={{fontSize: 14, marginTop: "-10px"}}
                                          floatingLabelStyle={{left: "170px", fontSize: "18px", color: '#000'}}
                                          value={f.selected_class}
                                          onChange={(event, index, value) => this.airlinesDomestic.setSelectedClassForFlightCode(f.flightno, value, 'returning')}>
                                          {f.classes.map(classes => {
                                            return (
                                              <MenuItem
                                                value={classes.code}
                                                primaryText={`${classes.code} - ${(classes.fare) ? classes.fare.toLocaleString('en') : "0.00"} - ${classes.cabin}`}/>);
                                          })}
                                        </SelectField>
                                      </div>
                                    </div>

                                    <div className="col s6 m3 l3 sm-border-left" style={{marginTop: 20}}>
                                      <p className="fs-base">{f.tocity_long}</p>
                                      <h3 className="fs-24 lh28 bold gray-dark">{f.arrivetime}</h3>
                                      <p className="fs-sm gray">
                                        <span
                                          className="font-bold">{moment(f.arrivaldate, 'DD-MMM-YYYY').format("ddd, DD MMMM YYYY")}</span>
                                        <br/>
                                        <span className="gray-light">
                                          {f.tocity_airport}
                                        </span>
                                      </p>
                                    </div>


                                  </div>
                                </div>
                              </article>
                            ]

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

          </Card>


        </div>


        <div className="col s12 l12">
          <Card className="animated fadeIn cardLite" style={{marginBottom: 10}}>
            <Toolbar className="toolbarCard" style={{backgroundColor: '#fff'}}>
              <ToolbarGroup>
                <ToolbarTitle style={{fontSize: 14, fontWeight: 500, color: '#32325d'}}
                              text={'Contact Passenger Information'}/>
              </ToolbarGroup>
            </Toolbar>


            <div style={{padding: '14px'}}>
              <div className="row">
                <div className="col s12 l2">
                  <p className="label-form">Title</p>
                  <TextField hintText="Your name here" fullWidth={true} value={"MR."} disabled={true}
                             underlineDisabledStyle={{borderBottom: "1px dotted #ddd"}}/>
                </div>
                <div className="col s12 l5">
                  <div>

                    <p className="label-form">Autocomplete Form</p>
                    <AutoComplete
                      hintText="Search Customer, Input Name/ID Number"
                      maxSearchResults={20}
                      dataSource={this.customerStore.searchResultsPic}
                      dataSourceConfig={{
                        text: 'search_text',
                        value: 'id'
                      }}
                      filter={AutoComplete.noFilter}
                      searchText={this.customerStore.searchQueryPic}
                      onUpdateInput={(searchText) => {
                        this.customerStore.setSearchQueryPic(searchText);
                      }}
                      onNewRequest={(choosenRequest, index) => {
                        if (index === -1) {
                          return;
                        }
                        this.airlinesDomestic.setPicInfo(choosenRequest);
                      }}
                      openOnFocus={true}
                      menuStyle={{maxHeight: 300}}
                      fullWidth={true}
                    />

                  </div>
                </div>
                <div className="col s12 l5">
                  <div>
                    <p className="label-form">ID Number</p>
                    <TextField hintText="E.g 081167930404" fullWidth={true}
                               value={this.airlinesDomestic.picInfo.id_number} disabled={true}
                               underlineDisabledStyle={{borderBottom: "1px dotted #ddd"}}/>
                  </div>
                </div>
              </div>


            </div>

            <Divider/>
            <Card className="no-shadow">
              <Toolbar className="toolbarCard" style={{backgroundColor: '#fff'}}>
                <ToolbarGroup>
                  <ToolbarTitle style={{fontSize: 14, fontWeight: 500, color: '#32325d'}} text={'Passengers Detail'}/>
                </ToolbarGroup>
              </Toolbar>
              {this.airlinesDomestic.passengerData.map((passengerData, index) => {
                if (passengerData.type === 'adult') {
                  return (<AdultForm key={index} passengerData={passengerData}/>)
                }
                if (passengerData.type === 'child') {
                  return (<ChildForm key={index} passengerData={passengerData}/>)
                }
                if (passengerData.type === 'infant') {
                  return (<BabyForm key={index} passengerData={passengerData}/>)
                }
              })}
            </Card>

          </Card>
        </div>

        <div className="col s12 l12">
          <Card>
            <Toolbar className="toolbarCard" style={{backgroundColor: '#fff'}}>
              <ToolbarGroup>
                <ToolbarTitle style={{fontSize: 14, fontWeight: 500, color: '#32325d'}} text={'Price Detail'}/>
              </ToolbarGroup>
            </Toolbar>


            <div style={{padding: '14px', marginTop: 20}}>
              <div className="row no-margin">
                <div className="col l3">
                  <p className="passive">Adult (x{this.airlinesDomestic.queries.adult})</p>
                </div>
                <div className="col l9" style={{textAlign: 'right'}}>
                  <p>IDR {priceOrder}</p>
                </div>
              </div>
              <div className="row no-margin">
                <div className="col l3">
                  <p className="passive">Child (x{this.airlinesDomestic.queries.child})</p>
                </div>
                <div className="col l9" style={{textAlign: 'right'}}>
                  <p>IDR {childTotal}</p>
                </div>
              </div>
              <div className="row no-margin">
                <div className="col l3">
                  <p className="passive">Infant (x{this.airlinesDomestic.queries.infant})</p>
                </div>
                <div className="col l9" style={{textAlign: 'right'}}>
                  <p>IDR {infantTotal}</p>
                </div>
              </div>

              <div className="row">
                <div className="col l12">
                  <Divider/>
                </div>
              </div>

              <div className="row">
                <div className="col l3">
                  <p className="passive">Subtotal</p>
                </div>
                <div className="col l9" style={{textAlign: 'right'}}>
                  <p>IDR {totalForAll}</p>
                </div>
              </div>

              <div className="row no-margin">
                <div className="col l3">
                  <p className="" style={{marginTop: '-5px'}}>Service Charge</p>
                </div>
                <div className="col l9" style={{textAlign: 'right'}}>
                  <InputNumber
                    style={{top: '-13px', width: '25%'}}
                    defaultValue={0}
                    value={this.airlinesDomestic.serviceCharge}
                    formatter={value => `IDR ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                    parser={value => value.replace(/\IDR\s?|(,*)/g, '')}
                    onChange={(value) => {
                      this.airlinesDomestic.setServiceCharge(value);
                    }}
                  />
                </div>
              </div>

              <div className="row">
                <div className="col l12">
                  <Divider/>
                </div>
              </div>


              <div className="row">
                <div className="col l3">
                  <h1 className="">Customer Pay</h1>
                </div>
                <div className="col l9" style={{textAlign: 'right'}}>
                  <h1>
                    <strong>IDR {totalForAllWithServiceCharge}</strong>
                  </h1>
                </div>

              </div>

              <div className="row no-margin">
                <div className="col l3">
                  <p className="">Agent Pay</p>
                </div>
                <div className="col l9" style={{textAlign: 'right'}}>
                  <p>IDR {totalForAll}</p>
                </div>
              </div>

              <div className="row">
                <div className="col l3">
                  <p className="">Commission</p>
                </div>
                <div className="col l9" style={{textAlign: 'right'}}>
                  <p>IDR 0.00</p>
                </div>
              </div>
              <div className="row no-margin">
                <blockquote>
                  <p className="no-margin"><strong><FontIcon className="material-icons"
                                                             style={{
                                                               verticalAlign: "sub",
                                                               marginRight: "2px",
                                                               fontSize: 14,
                                                               color: '#000'
                                                             }}>info_outline</FontIcon> Booking Process</strong><br/>Make
                    sure you are already
                    understand terms and conditions before continue the booking process.</p>
                  <p className="no-margin"><strong><FontIcon className="material-icons"
                                                             style={{
                                                               verticalAlign: "sub",
                                                               marginRight: "2px",
                                                               fontSize: 14,
                                                               color: '#000'
                                                             }}>info_outline</FontIcon> Important Note</strong></p>
                  <ol style={{listStyleType: 'decimal', margin: 0}}>
                    <li>Passenger data must be same as data in domestic ID or international password</li>
                    <li>Any kind of data mistake is not our responsibility</li>
                  </ol>
                </blockquote>
              </div>
              <div className="row" style={{textAlign: "right", marginBottom: 0}}>
                <RaisedButton
                  label="Book Now & Continue to Payment"
                  icon={<FontIcon className="material-icons">forward</FontIcon>}
                  onClick={() => this.book()}
                  primary={true}/>
              </div>
            </div>

          </Card>
        </div>
      </div>


    )
  }
}
