import React from 'react';
import {observer, inject} from 'mobx-react';
import {
  Card, CardTitle, CardText,
  Divider,
  MenuItem,
  FlatButton,
  RaisedButton,
  Table,
  TableBody,
  TableHeader,
  TableHeaderColumn,
  TableRow,
  TableRowColumn,
  TextField,
  Toolbar,
  ToolbarGroup,
  ToolbarSeparator, ToolbarTitle, CardHeader, Dialog,
} from 'material-ui';
import {Link} from 'react-router-dom';
import {LINKS} from "../../../routes";
import {DIALOG} from "../../../stores/global_ui";
import AddIcon from 'material-ui/svg-icons/content/add';
import RemoveIcon from 'material-ui/svg-icons/content/remove';
import NavigationArrowBack from 'material-ui/svg-icons/navigation/arrow-back';

import MakePaymentDialog from './MakePaymentDialog/index';
import CancelPaymentDialog from './CancelPaymentDialog/index';
import moment from "moment";
import get from 'lodash.get';
import DC from 'decimal.js-light';
import NumberFormat from 'react-number-format';

@inject('appstate')
@observer
export default class OrderDetailComponent extends React.Component {

  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      value: 1,
      searchText: '',
      slideIndex: 0,
      tabSelected: 'gi',
      openModal: false
    };
    this.defaultState = Object.assign({}, this.state);
    this.http = props.appstate.http;
    this.authStore = props.appstate.auth;
    this.globalUI = props.appstate.globalUI;
    this.order = props.appstate.order;
  }

  componentDidMount() {
    this.order.getDetail(this.props.match.params.id);
  }

  handleUpdateInput = (searchText) => {
    this.setState({
      searchText: searchText,
    });
  };

  handleNewRequest = () => {
    this.setState({
      searchText: '',
    });
  };

  tabsHandleChange = (value) => {
    this.setState({
      slideIndex: value,
    });
  };


  handleChange = (tabSelected) => {
    this.setState({
      tabSelected: tabSelected,
    });
    // this.props.history.push(tabSelected);
  };

  handleCloseModal = () => {
    this.setState({
      openModal: false
    })
  };

  handleOpenModal = () => {
    this.setState({
      openModal: true
    })
  }

  render() {
    const customer = {
      name: 'Ridwan Abadi',
      identity_number: '98261536156313561',
      email: 'welove6215@einrot.com',
      address: 'Jalan Pramuka No. 81, Marga Jaya, Bekasi Selatan, Marga Jaya, Bekasi Sel., Kota Bks, Jawa Barat 17141',
      handphone: '081190876',
      phone: '0',
      place_birth: 'Jakarta',
      birth_date: moment().format('DD MMM YYYY'),
      gender: 'Male',
      tax_id: '98261536156313561',
      martial_status: 'Married'
    }

    const order = {
      id: '467d6b50-ade0-4dd0-98ca-35cd083e16e0',
      order_id: 'book_461a1df5',
      package: 'The Exoticsm Of Minang',
      description: 'Feel the joy of wonderful world of exotic, culture, and outstanding view that will amaze you to the bone. Enjoy your holiday in very nice and peaceful place to clear your mind. With great hotel and profesional tour guide, we ensure you that you will have a unforgetable memories and happiness.\n',
      registered: moment(),
      detail_package: [
        {
          name: 'Destination',
          value: 'Bukittinggi, Minangkabau'
        },
        {
          name: 'Transport',
          value: 'Custom'
        },
        {
          name: 'Duration',
          value: '4 day 3 night'
        }
      ],
      payment_type: 'Instalment',
      status: 'active'
    }

    const totalPaid = get(this.order.selectedOrder, 'payments', [])
      .map(pay => (pay.type == 'cancel_payment') ? pay.amount = 0 : pay.amount)
      .reduce((total, v) => total.add(v), new DC(0));

    const priceAfterDisc = get(this.order.selectedOrder, 'price_after_discount', 0);
    const disc = new DC(get(this.order.selectedOrder, 'price') || 0).minus(priceAfterDisc || 0);

    const amountDue = new DC(priceAfterDisc || 0).minus(totalPaid);
    // const amountDue = new DC(0);

    const actionsModals = [
      <FlatButton
        label="Cancel"
        primary={true}
        onClick={this.handleCloseModal}
      />,
      <FlatButton
        label="Ok"
        primary={true}
        onClick={() => {
          this.order.payAirlineTicket().then((airlineTicket) => {
            this.order.setOrderStatus('ticketed');
            this.globalUI.openSnackbar('Payment success');
          });
        }}
      />,
    ];

    return (
      <div className="customerDetail containerMiddle animated fadeIn">
        <Dialog
          title="Are you sure that all data is correct?"
          actions={actionsModals}
          modal={true}
          open={this.state.openModal}
        >
          You will be charged
        </Dialog>

        <div style={{marginBottom: '10px', marginLeft: '-15px'}}>
          <FlatButton
            className="headerMenu"
            inkBarStyle={{background: 'transparent'}}
            hoverColor="#f1f5f9"
            style={{background: '#ffffff00'}}
            onClick={() => this.props.history.goBack()}
            label="Back"
            primary={true}
            icon={<NavigationArrowBack />}
          />
        </div>

        <MakePaymentDialog/>

        <CancelPaymentDialog/>

        <Card className="row">

          <div className="flexSpaceBetween" style={{padding: 16}}>
            <div className="">
              <CardTitle style={{padding: 0, fontSize: 22}}
                         titleStyle={{fontSize: 22}}
                         title="Order Form"
              />
              <div className="listCustDetail">
                <div className="listHeaderCustDetailItem flex">
                  <p className="listHeaderCustomerDetailItemKey">Order Id</p>
                  <p className="listHeaderCustomerDetailItemValue"><code>{this.order.selectedOrder.id}</code></p>
                </div>
                <div className="listHeaderCustDetailItem flex">
                  <p className="listHeaderCustomerDetailItemKey">Order Date</p>
                  <p className="listHeaderCustomerDetailItemValue">{moment(this.order.selectedOrder.created_at).format("DD MMMM YYYY, HH:mm:ss")}</p>
                </div>
                <div className="listHeaderCustDetailItem flex">
                  <p className="listHeaderCustomerDetailItemKey">Payment Method</p>
                  <p className="listHeaderCustomerDetailItemValue">{get(this.order.selectedOrder, 'paymentMethod.name', '-')}</p>
                </div>
              </div>
            </div>
            <ToolbarGroup>
              {
                this.order.orderDetail.type === 'packages' && this.order.orderDetail.status != 'canceled' && (<RaisedButton icon={<AddIcon/>} label="Make Payment" primary={true}
                                                                             onClick={() => this.globalUI.showDialog(DIALOG.ORDER.MAKE_PAYMENT)}/>)
              }
              {
                this.order.orderDetail.type === 'packages' && this.order.orderDetail.status != 'canceled' && (<RaisedButton icon={<RemoveIcon/>} label="Cancel Booking" primary={false}
                                                                             onClick={() => this.globalUI.showDialog(DIALOG.ORDER.CANCEL_PAYMENT)}/>)
              }
              {
                this.order.orderDetail.type === 'airline' && this.order.orderDetail.status === 'booked' &&
                (<RaisedButton icon={<AddIcon/>} label="Pay" primary={true}
                                                         onClick={() => this.handleOpenModal()}/>)
              }
              {
                this.order.orderDetail.type === 'airline' && this.order.orderDetail.status === 'ticketed' &&
                (<RaisedButton icon={<AddIcon/>} label="Print Ticket" primary={true} onClick={() => this.globalUI.showDialog(DIALOG.ORDER.MAKE_PAYMENT)}/>)
              }{
                this.order.orderDetail.type === 'packages' && this.order.orderDetail.status == 'canceled' && (<p>This order is already Cancelled</p>)
              }
            </ToolbarGroup>
          </div>
          <Divider/>
          <CardHeader actAsExpander={true}
                      showExpandableButton={false} style={{paddingBottom: 0}}
                      subtitle={<a style={{fontSize: 12}}>CUSTOMER INFORMATION</a>}/>
          <CardText expandable={true} style={{paddingBottom: 0}}>
            <div className="row no-margin">
              <div className="col s12 m12 l6">
                <div className="listCustDetail">
                  <div className="listCustDetailItem flex">
                    <p className="listCustomerDetailItemKey">Name</p>
                    <p className="listCustomerDetailItemValue">{get(this.order.selectedOrder, 'customer.name', '-')}</p>
                  </div>
                  <div className="listCustDetailItem flex">
                    <p className="listCustomerDetailItemKey">Identity Number</p>
                    <p className="listCustomerDetailItemValue">{get(this.order.selectedOrder, 'customer.passport_number', '-')}</p>
                  </div>
                  <div className="listCustDetailItem flex">
                    <p className="listCustomerDetailItemKey">Email</p>
                    <p className="listCustomerDetailItemValue">{get(this.order.selectedOrder, 'customer.email', '-')}</p>
                  </div>
                  <div className="listCustDetailItem flex">
                    <p className="listCustomerDetailItemKey">Address</p>
                    <p className="listCustomerDetailItemValue">{get(this.order.selectedOrder, 'customer.address', '-')}</p>
                  </div>
                  <div className="listCustDetailItem flex">
                    <p className="listCustomerDetailItemKey">Phone</p>
                    <p
                      className="listCustomerDetailItemValue">{get(this.order.selectedOrder, 'customer.phone_number', '-')}</p>
                  </div>
                  <div className="listCustDetailItem flex">
                    <p className="listCustomerDetailItemKey">Handphone</p>
                    <p className="listCustomerDetailItemValue">-</p>
                  </div>

                </div>

              </div>

              <div className="col s12 m12 l6">
                <div className="listCustDetail">
                  <div className="listCustDetailItem flex">
                    <p className="listCustomerDetailItemKey">Place & Birth Date</p>
                    <p className="listCustomerDetailItemValue">{customer.place_birth}, {moment(get(this.order.selectedOrder, 'customer.date_of_birth', moment())).format("DD MMMM YYYY")}</p>
                  </div>
                  <div className="listCustDetailItem flex">
                    <p className="listCustomerDetailItemKey">Gender</p>
                    <p className="listCustomerDetailItemValue">{get(this.order.selectedOrder, 'customer.gender', '-')}</p>
                  </div>
                  <div className="listCustDetailItem flex">
                    <p className="listCustomerDetailItemKey">Tax Id</p>
                    <p className="listCustomerDetailItemValue">-</p>
                  </div>
                  <div className="listCustDetailItem flex">
                    <p className="listCustomerDetailItemKey">Martial Status</p>
                    <p className="listCustomerDetailItemValue">-</p>
                  </div>
                </div>

              </div>

            </div>
          </CardText>


          <div style={{marginTop: 18}}>
            <Table selectable={false} className="TableOrder">
              <TableHeader displaySelectAll={false}
                           adjustForCheckbox={false}
                           enableSelectAll={false}>
                <TableRow style={{height: 38, background: '#f6f9fc'}}>

                  <TableHeaderColumn className="TableHeaderColumnAkun"
                                     style={{height: 'auto'}}>Package</TableHeaderColumn>
                  <TableHeaderColumn className="TableHeaderColumnAkun"
                                     style={{height: 'auto'}}>Description</TableHeaderColumn>
                  <TableHeaderColumn className="TableHeaderColumnAkun"
                                     style={{height: 'auto'}}>Price</TableHeaderColumn>
                  <TableHeaderColumn className="TableHeaderColumnAkun"
                                     style={{height: 'auto'}}>Amount</TableHeaderColumn>
                </TableRow>
              </TableHeader>
              <TableBody displayRowCheckbox={false}>
                <TableRow>
                  <TableRowColumn>
                    {get(this.order.selectedOrder, 'packageSchedule.package.name', '-')}
                    <p style={{margin: '2px 0', fontSize: 10}}>
                      Detail: <Link to={LINKS.SERVICE} target="_blank">View details</Link>
                    </p>
                  </TableRowColumn>
                  <TableRowColumn>{get(this.order.selectedOrder, 'packageSchedule.package.description', '-')}</TableRowColumn>
                  <TableRowColumn><NumberFormat value={get(this.order.selectedOrder, 'price', '0')} displayType={'text'} thousandSeparator={true} prefix={'IDR '}/></TableRowColumn>
                  <TableRowColumn><NumberFormat value={get(this.order.selectedOrder, 'price_after_discount', '0')} displayType={'text'} thousandSeparator={true} prefix={'IDR '}/></TableRowColumn>
                </TableRow>

                <TableRow displayBorder={false} className="TableRowCondensed TableRowCondensedFirst">
                  <TableRowColumn colSpan={2} className="TableRowColumnCondensed TableRowColumnCondensedFirst"></TableRowColumn>
                  <TableRowColumn className="align-right font-500 TableRowColumnCondensed TableRowColumnCondensedFirst">Subtotal</TableRowColumn>
                  <TableRowColumn className="TableRowColumnCondensed TableRowColumnCondensedFirst"><NumberFormat value={get(this.order.selectedOrder, 'price_after_discount', '0')} displayType={'text'} thousandSeparator={true} prefix={'IDR '}/></TableRowColumn>
                </TableRow>
                <TableRow displayBorder={false} className="TableRowCondensed">
                  <TableRowColumn colSpan={2} className="TableRowColumnCondensed"></TableRowColumn>
                  <TableRowColumn className="align-right font-500 TableRowColumnCondensed">Discount</TableRowColumn>
                  <TableRowColumn className="TableRowColumnCondensed"><NumberFormat value={disc.toString()} displayType={'text'} thousandSeparator={true} prefix={'IDR '}/></TableRowColumn>
                </TableRow>
                <TableRow displayBorder={false} className="TableRowCondensed">
                  <TableRowColumn colSpan={2} className="TableRowColumnCondensed"></TableRowColumn>
                  <TableRowColumn className="align-right font-500 TableRowColumnCondensed">Total</TableRowColumn>
                  <TableRowColumn className="TableRowColumnCondensed"><NumberFormat value={get(this.order.selectedOrder, 'price_after_discount', '0')} displayType={'text'} thousandSeparator={true} prefix={'IDR '}/></TableRowColumn>
                </TableRow>
                <TableRow displayBorder={false} className="TableRowCondensed">
                  <TableRowColumn colSpan={2} className="TableRowColumnCondensed"></TableRowColumn>
                  <TableRowColumn className="align-right font-500 TableRowColumnCondensed">Total Paid</TableRowColumn>
                  <TableRowColumn className="TableRowColumnCondensed"><NumberFormat value={totalPaid.toString()} displayType={'text'} thousandSeparator={true} prefix={'IDR '}/></TableRowColumn>
                </TableRow>
                <TableRow displayBorder={false} className="TableRowCondensed TableRowCondensedLast">
                  <TableRowColumn colSpan={2} className="TableRowColumnCondensed TableRowColumnCondensedLast"></TableRowColumn>
                  <TableRowColumn className="align-right font-500 TableRowColumnCondensed TableRowColumnCondensedLast">Amount
                    Due </TableRowColumn>
                  <TableRowColumn className="TableRowColumnCondensed TableRowColumnCondensedLast"><NumberFormat value={amountDue.toString()} displayType={'text'} thousandSeparator={true} prefix={'IDR '}/></TableRowColumn>
                </TableRow>
              </TableBody>
            </Table>
            <Divider/>
          </div>
        </Card>
        <Card>
          {/*<Toolbar className="toolbarCard" style={{backgroundColor: '#fff'}}>*/}
          {/*<ToolbarGroup>*/}
          {/*<ToolbarTitle actAsExpander={true}*/}
          {/*showExpandableButton={false} style={{fontSize: 14, fontWeight: 500, color: '#32325d', textTransform: 'capitalize'}}*/}
          {/*text={'Payments'}/>*/}
          {/*</ToolbarGroup>*/}

          {/*</Toolbar>*/}

          <CardHeader actAsExpander={true}
                      showExpandableButton={false} style={{paddingBottom: 16}}
                      subtitle={<a style={{fontSize: 12, paddingLeft: 10}}>Payments History</a>}/>
          <Divider/>

          <CardText className="no-padding" expandable={true}>
            <Table selectable={false}>
              <TableHeader displaySelectAll={false}
                           adjustForCheckbox={false}
                           enableSelectAll={false}>
                <TableRow style={{height: 38, background: '#f6f9fc'}}>

                  <TableHeaderColumn className="TableHeaderColumnAkun"
                                     style={{height: 'auto'}}>Date</TableHeaderColumn>
                  <TableHeaderColumn className="TableHeaderColumnAkun"
                                     style={{height: 'auto'}}>Description</TableHeaderColumn>
                  <TableHeaderColumn className="TableHeaderColumnAkun"
                                     style={{height: 'auto'}}>Amount</TableHeaderColumn>
                  <TableHeaderColumn className="TableHeaderColumnAkun"
                                     style={{height: 'auto'}}>Status</TableHeaderColumn>
                </TableRow>
              </TableHeader>
              <TableBody displayRowCheckbox={false}>
                {get(this.order.selectedOrder, 'payments', []).map(pay => {
                  return (
                    <TableRow>
                      <TableRowColumn>{moment(pay.created_at).format("DD MMMM YYYY, HH:mm:ss")}</TableRowColumn>
                      <TableRowColumn>{pay.name}</TableRowColumn>
                      <TableRowColumn><NumberFormat value={pay.amount} displayType={'text'} thousandSeparator={true} prefix={'IDR '}/></TableRowColumn>
                      <TableRowColumn>{pay.status}</TableRowColumn>
                    </TableRow>
                  )
                })}
              </TableBody>
            </Table>
          </CardText>
        </Card>

      </div>
    )
  }
}
