import React from 'react';
import {observer, inject} from 'mobx-react';
import bind from 'bind-decorator';

import {
  Card,
  Avatar,
  CardActions,
  CardHeader,
  CardMedia,
  CardTitle,
  AutoComplete,
  CardText,
  FlatButton,
  Divider,
  RaisedButton,
  Toolbar,
  DatePicker,
  FontIcon,
  SelectField,
  MenuItem,
  ToolbarGroup,
  FloatingActionButton,
  ToolbarSeparator,
  IconButton,
  ToolbarTitle,
  RadioButton, RadioButtonGroup,
  Tabs, Tab,
} from 'material-ui';

import {
  Step,
  Stepper,
  StepLabel,
} from 'material-ui/Stepper';

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 NumberFormat from 'react-number-format';
import {Button, Radio, Popover, Icon, Checkbox, Slider} from 'antd';
import '../style.scss';
import {appConfig} from "../../../config/app";
import moment from 'moment';
import EmptyComponent from "../../EmptyComponent/index";
import Loader from 'react-loader-advanced';
import LoadingDialog from "../../LoadingDialog";
import {NavigationArrowForward} from "material-ui/svg-icons/index";
import {LINKS} from '../../../routes';
import get from 'lodash.get';
import DC from 'decimal.js-light';

const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;
const airlinesList = ['Garuda Indonesia', 'Sriwijaya Air', 'Air Asia'];
const defaultCheckedList = ['Garuda Indonesia'];

const marks = {

  100: {
    style: {
      color: '#f50',
    },
    label: <strong>Any</strong>,
  },
};

function formatter(value) {
  return `IDR ${value.toLocaleString()}`;
}

@inject('appstate')
@observer
export default class ListAirlines extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      expanded: false,
      flight_detail: null,
      price_detail: null,
      flight: null,
      expandedCard: {
        "0": false
      },
      checkedList: defaultCheckedList,
      indeterminate: true,
      checkAll: false,
      isReturn: false,
      haveRole: false,
      value: 1,
    };
    this.defaultState = Object.assign({}, this.state);
    this.http = props.appstate.http;
    this.authStore = props.appstate.auth;
    this.airlinesDomestic = props.appstate.airlinesDomestic;
    this.globalUI = props.appstate.globalUI;

    if (this.authStore.userProfile.role_id) {
      this.state.haveRole = true;
    }
  }

  componentDidMount() {
    window.scrollTo(0, 0);
  }

  handleFlightDetail = (key) => {
    if (key == this.state.flight_detail) {
      this.setState({
        flight_detail: 'x-0!',
        price_detail: '',
      })
    }
    else if (this.state.flight_detail == null) {
      this.setState({
        flight_detail: key,
        price_detail: '',
      })
    }
    else {

      this.setState({
        flight_detail: key,
        price_detail: '',
      })
    }
  };

  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
  }

  handlePriceDetail = (key) => {


    if (key == this.state.price_detail) {
      this.setState({
        price_detail: 'x-0!',
        flight_detail: '',
      })
    }
    else if (this.state.price_detail == null) {
      this.setState({
        price_detail: key,
        flight_detail: '',
      })
    }
    else {

      this.setState({
        price_detail: key,
        flight_detail: '',
      })
    }
  };

  onChangeStop = (e) => {
    console.log('radio checked', e.target.value);
    this.setState({
      value: e.target.value,
    });
  }

  onChangeSort = (e) => {
    console.log('radio checked', e.target.value);
    this.setState({
      value: e.target.value,
    });
  }

  onChange = (checkedList) => {
    this.setState({
      checkedList,
      indeterminate: !!checkedList.length && (checkedList.length < airlinesList.length),
      checkAll: checkedList.length === airlinesList.length,
    });
  }
  onCheckAllChange = (e) => {
    this.setState({
      checkedList: e.target.checked ? airlinesList : [],
      indeterminate: false,
      checkAll: e.target.checked,
    });
  }

  getOrderButton(state, index) {
    this.setState({
      expandedCard: Object.assign({}, this.state.expandedCard, {
        [index]: state
      })
    })

  }

  submit = (key) => {
    this.props.onClickSubmit(key);
  }

  orderFlight = (data) => {
    // console.log(data.index, data, "Flight Ordered");
    this.props.history.push('/app/service/airlines/book/' + data.index, {index: data.id, data: data.item});
  }


  render() {
    let searchResults = [];

    // empy state
    if (this.airlinesDomestic.queries.results.departure.length === 0 && !this.airlinesDomestic.isLoadingSearch) {
      return <div className="row">
        <div className="col s12 l12">
          <Card className="animated fadeIn cardLite">
            <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>
                    <h3 className="no-margin"
                        style={{lineHeight: "20px"}}>{((this.props.match.path.split('/')[this.props.match.path.split('/').length - 1] === 'search_return')) ? "Select Departure Schedule" : "Select Schedule"}</h3>
                    <p className="no-margin"
                       style={{lineHeight: "20px"}}>{(this.props.match.path.split('/')[this.props.match.path.split('/').length - 1] === 'search_return') ? this.airlinesDomestic.queries.arrivaldate : this.airlinesDomestic.queries.departuredate}</p>
                  </div>
                }/>
              </ToolbarGroup>
            </Toolbar>
            <Divider/>
            <EmptyComponent type="default3" header="No Flight Available"
                            content="Nothing match your criteria. Try other date"/>
          </Card>
        </div>
      </div>
    }

    const maxPrice = get(this.authStore.userProfile, 'role_data.airline_settings[0].max_amount_per_flight', 0);

    console.log(maxPrice, this.authStore.userProfile);

    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={(this.props.match.path.split('/')[this.props.match.path.split('/').length - 1] === 'search_return') ? 1 : 0}>
                <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={0}>
                <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">

            <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>
                    <h3 className="no-margin"
                        style={{lineHeight: "20px"}}>{((this.props.match.path.split('/')[this.props.match.path.split('/').length - 1] === 'search_return')) ? "Select Departure Schedule" : "Select Schedule"}</h3>
                    <p className="no-margin"
                       style={{lineHeight: "20px"}}>{(this.props.match.path.split('/')[this.props.match.path.split('/').length - 1] === 'search_return') ? this.airlinesDomestic.queries.arrivaldate : this.airlinesDomestic.queries.departuredate}</p>
                  </div>
                }/>
              </ToolbarGroup>
              <ToolbarGroup>

                <Popover placement="bottom"
                         content={<div><RadioGroup className="flex flex-column flex-wrap" onChange={(e) => {
                           this.airlinesDomestic.setSortBy(e.target.value);
                         }} value={this.airlinesDomestic.sortBy}>
                           <Radio value={'price_low_to_high'}>Price (low to high)</Radio>
                           <Radio value={'price_high_to_low'}>Price (high to low)</Radio>
                           <Radio value={'duration'}>Duration</Radio>
                           <Radio value={'departure_time'}>Departure time</Radio>
                         </RadioGroup></div>} title="Sort by" trigger="click">
                  <Button className="mr-10">Sort by <Icon type="down"/></Button>
                </Popover>

                <Popover placement="bottom"
                         content={<div><RadioGroup  onChange={(e) => {
                           this.airlinesDomestic.setStopFilter(e.target.value);
                         }} value={this.airlinesDomestic.stopFilter}>
                           <Radio value={'any'}>Any</Radio>
                           <Radio value={'no_stop'}>No Stop</Radio>
                           <Radio value={'one_or_less'}>One or less</Radio>
                           <Radio value={'two_or_less'}>Two or less</Radio>
                         </RadioGroup></div>} title="Stops" trigger="click">
                  <Button className="mr-10">Stops <Icon type="down"/></Button>
                </Popover>

                <Popover placement="bottom"
                         content={<div>
                           <Slider min={this.airlinesDomestic.priceMin}
                                   max={this.airlinesDomestic.priceMax}
                                   defaultValue={this.airlinesDomestic.priceMax}
                                   tipFormatter={formatter}
                                   onChange={(value) => {
                                     console.log('vau', value);
                                     this.airlinesDomestic.setPriceMaxFilter(value);
                                   }}
                                   value={this.airlinesDomestic.priceMaxFilter}/>
                         </div>}
                         title="Price" trigger="click">
                  <Button className="mr-10">Price <Icon type="down"/></Button>
                </Popover>

                <Popover placement="bottom" content={<div>
                  <CheckboxGroup className="flex flex-column flex-wrap" options={this.airlinesDomestic.airlineFilterList}
                                 value={this.airlinesDomestic.selectedAirlinesFilter} onChange={(value) => {
                    this.airlinesDomestic.setSelectedAirlinesFilter(value);
                  }}/>
                </div>} title={<div className="flexSpaceBetween">Airlines <Checkbox
                  indeterminate={this.airlinesDomestic.isSelectedAirlinesFilterIndeterminate}
                  onChange={(e) => {
                    this.airlinesDomestic.setSelectedAirlinesFilter(e.target.checked ? this.airlinesDomestic.airlineFilterList.slice() : []);
                  }}
                  checked={this.airlinesDomestic.isAllSelectedAirlinesChecked}
                >
                  Check all
                </Checkbox></div>} trigger="click">
                  <Button>Airlines <Icon type="down"/></Button>
                </Popover>

              </ToolbarGroup>
            </Toolbar>
            <Divider/>
            <Loader show={this.airlinesDomestic.isLoadingSearch} message={<LoadingDialog/>}
                    messageStyle={{textAlign: 'center'}} style={{overflow: 'hidden'}}
                    backgroundStyle={{backgroundColor: 'rgba(255,255,255,0.5)'}}>

              <Card style={{maxHeight: 'calc(100vh - 310px)', minHeight: 'calc(100vh - 310px)', overflow: 'auto'}}>
                {(() => {
                  let lists = (this.props.match.path.split('/')[this.props.match.path.split('/').length - 1] === 'search_return') ? this.airlinesDomestic.queries.results.returning : this.airlinesDomestic.departureLists;

                  // console.log('lists', lists.length);

                  return (this.airlinesDomestic.lists.length > 0 && lists.length > 0) ?
                    (lists
                        .filter(item => this.state.haveRole ? new DC(item.price_range_start || 0).lt(maxPrice) : true)
                        .map((item, index) => {
                          let priceOrder = (item.price_range_start) ? item.price_range_start.toLocaleString('en') : "0.00";
                          return (
                            <Card
                              className="airlines-list-card"
                              key={index}
                              onExpandChange={(state, icard) => {
                                // console.log(state, index)
                                this.getOrderButton(state, index);
                              }}
                              style={{
                                padding: "0px 0px 0px 0px",
                                cursor: 'pointer',
                                borderBottom: '1px solid #f1f1f1',
                                borderRadius: 0,
                                boxShadow: 'none'
                              }}>
                              <CardHeader
                                actAsExpander={true}
                                iconStyle={{right: 10, top: "-10px"}}
                                showExpandableButton={true}
                                children={
                                  <div className="row no-margin">
                                    <div className="col l1 m1 s1 align-left">
                                      <Avatar size={35} style={{borderRadius: 0,}}
                                              backgroundColor="transparent"
                                              src={(item.no_of_flight - 1 === 0) ? this.getAirlineImage(item.airlinecode) : this.getAirlineImage('multi')}/>
                                    </div>
                                    <div className="col l4 m4 s4 align-left">
                                      <h4>{item.departtime} - {item.arrivetime}</h4>
                                      <h4 style={{fontWeight: 300}}>
                                        {/*{item.flightno}*/}
                                        {item.airline}</h4>
                                    </div>
                                    <div className="col l2 m2 s2 align-left">
                                      <h4>{item.durationhour}h {item.durationminute}m</h4>
                                      <h4 style={{fontWeight: 300}}>{item.fromcity} - {item.tocity}</h4>
                                    </div>
                                    <div className="col l2 m2 s2 align-left">
                                      <h4
                                        style={{fontWeight: 300}}>{(item.no_of_flight - 1 > 0) ? item.no_of_flight - 1 + ' Stop' : 'Non stop'}</h4>
                                    </div>
                                    <div className="col l2 m2 s2 align-left">
                                      {(this.state.expandedCard[index]) ? (
                                        <h4 style={{fontWeight: 500}}>
                                          <Button
                                            style={{marginTop: 0}}
                                            type="default"
                                            size="default"
                                            className=""
                                            onClick={() => {
                                              let isSelectReturn = (this.props.match.path.split('/')[this.props.match.path.split('/').length - 1] === 'search_return');
                                              if (isSelectReturn) {
                                                this.airlinesDomestic.setReturningItem(item);
                                              } else {
                                                this.airlinesDomestic.setDepartureItem(item);
                                              }
                                              if (this.airlinesDomestic.isReturn === 1 && !isSelectReturn) {
                                                this.props.history.push(LINKS.SERVICE_AIRLINES_SEARCH_RETURN);
                                                // this.props.history.push('/app/service/airlines/book');
                                              } else {
                                                this.props.history.push('/app/service/airlines/book');
                                              }
                                            }}
                                            htmlType="button">
                                            <span style={{fontWeight: 300}}>Choose </span>
                                            <span style={{color: "green"}}>IDR {priceOrder}</span><Icon type="right"/>
                                          </Button>
                                        </h4>
                                      ) : (<h4 style={{fontWeight: 500}}>
                                        <span style={{fontWeight: 300}}>From </span>
                                        <span style={{color: "green"}}>IDR {priceOrder}</span>
                                      </h4>)}
                                    </div>
                                  </div>
                                }
                              />
                              <CardText
                                expandable={true}
                                style={{borderTop: '1px solid #f1f1f1', cursor: 'default', padding: 0}}>
                                <div style={{position: 'relative'}} className="shadow-inside">
                                  {/*<RaisedButton label="Select Flight" className="buttonSelectFlight"/>*/}
                                  {item.flights.map((item_flight, index_item) => {
                                    return (
                                      <div key={index_item} style={{background: "#f0f0f0"}}>
                                        {(index_item > 0) ? (
                                          <div className="flightDetailResultDetailItenaryStopper">
                                            <div
                                              className="flightDetailResultDetailItenaryStopperDetail">{(item_flight.layover_hour) ? `${item_flight.layover_hour}h` : ''} {item_flight.layover_minute}m
                                              <div className="flightDetailResultDetailItenarySeparator"/>
                                              Layover
                                              <div className="flightDetailResultDetailItenarySeparator "/>
                                              <div>{item_flight.fromcity_long}</div>
                                              <div className="flightDetailResultDetailItenarySeparator"/>
                                              <div>{item_flight.fromcity_airport}</div>
                                              <div className="flightDetailResultDetailItenarySeparator "/>
                                              <div>({item_flight.fromcity})</div>
                                            </div>
                                          </div>) : (<div></div>)}
                                        <div className="flightDetail">
                                          <div className="flightDetailResult">
                                            <div className="flightDetailResultDetail">
                                              <div className="flightDetailResultDetailItenary">
                                                <div className="flightDetailResultDetailItenaryImg"/>
                                                <div className="flightDetailResultDetailItenaryDeparture">
                                                  <div>{item_flight.departtime}</div>
                                                  <div className="flightDetailResultDetailItenarySeparator"/>
                                                  <div>{item_flight.fromcity_long}</div>
                                                  <div className="flightDetailResultDetailItenarySeparator"/>
                                                  <div>{item_flight.fromcity_airport}</div>
                                                  <div className="flightDetailResultDetailItenarySeparator"/>
                                                  <div>({item_flight.fromcity})</div>
                                                </div>
                                                <div className="flightDetailResultDetailItenaryDuration">
                                                  <div>
                                                    Travel
                                                    time:
                                                    <span> {item_flight.durationhour}h {item_flight.durationminute}m</span>
                                                  </div>
                                                </div>
                                                <div className="flightDetailResultDetailItenaryArrival">
                                                  <div>{item_flight.arrivetime}</div>
                                                  <div className="flightDetailResultDetailItenarySeparator"></div>
                                                  <div>{item_flight.tocity_long}</div>
                                                  <div className="flightDetailResultDetailItenarySeparator"></div>
                                                  <div>{item_flight.tocity_airport}</div>
                                                  <div className="flightDetailResultDetailItenarySeparator"></div>
                                                  <div>({item_flight.tocity})</div>

                                                </div>
                                              </div>
                                              <div className="flightDetailResultDetailItenaryAirlines">
                                                <div>{item_flight.airline}</div>
                                                <div className="flightDetailResultDetailItenarySeparator"></div>
                                                <div>{item_flight.flightno}</div>
                                              </div>
                                            </div>
                                          </div>
                                        </div>

                                      </div>
                                    )
                                  })}

                                </div>
                              </CardText>
                            </Card>
                          )
                        })
                    ) : <div></div>
                })()}

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