import React from 'react';
import {observer, inject} from 'mobx-react';
import bind from 'bind-decorator';
import {
  Card,
  CardActions,
  CardHeader,
  CardMedia,
  CardTitle,
  AutoComplete,
  CardText,
  FlatButton,
  List,
  ListItem,
  Divider,
  Snackbar,
  Tabs, Tab,
  RaisedButton,
  Toolbar,
  DatePicker,
  FontIcon,
  Table,
  TableBody,
  TableHeader,
  TableHeaderColumn,
  TableRow,
  SelectField,
  TableRowColumn,
  MenuItem,
  Toggle,
  ToolbarGroup,
  FloatingActionButton,
  ToolbarSeparator,
  IconButton,
  ToolbarTitle,
  RadioButton,
  TextField,
  Paper,
  RadioButtonGroup
} from 'material-ui';
import {Row, Icon, Button, notification, Table as TableAntd, Tooltip as TooltipAntd} from 'antd';
import {yellow500} from 'material-ui/styles/colors';
import StarBorder from 'material-ui/svg-icons/toggle/star-border';
import SwipeableViews from 'react-swipeable-views';
import SearchIcon from 'material-ui/svg-icons/action/search';
import DC from 'decimal.js-light';
import {Link} from 'react-router-dom';
import {LINKS} from "../../routes";
import './style.scss';
import {appConfig} from "../../config/app";
import NumberFormat from 'react-number-format';
import LoadingDialog from "../LoadingDialog";
import Loader from 'react-loader-advanced';
import {constant} from "../../config/const";

const {Column, ColumnGroup} = Table;


@inject('appstate')
@observer
export default class OrderComponent extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.orderStore = props.appstate.order;
    this.state = {
      expanded: false,
      value: 1,
      snackbarOpen: false,
      snackbarMessage: '',
      filteredInfo: null,
      searchText: '',
      filter : 'active',
      sortedInfo: null,
      filtered: false,
      data: []
    };
    this.defaultState = Object.assign({}, this.state);
    this.http = props.appstate.http;
    this.authStore = props.appstate.auth;
    this.globalUI = props.appstate.globalUI;
  }

  componentDidMount() {
    this.orderStore.isSearching = false;
    this.globalUI.openLoading();
    this.orderStore.getAllOrder().then(res => {
      console.log(res)
      this.globalUI.closeLoading();
    });
  }

  componentWillUnmount() {
    this
      .globalUI
      .changeBackgroundColor("#fff");
  }

  onInputChange = (e) => {
    this.setState({searchText: e.target.value});
  }

  search = (event) => {
    console.log("dataSearch", event.target.value);
    if (event.target.value.length === 0) {
      this.orderStore.isSearching = false;
    }
    else {
      this.orderStore.isSearching = true;
      this.orderStore.search(event.target.value);
    }
  }


  handleExpandChange = (expanded) => {
    this.setState({expanded: expanded});
  };

  handleClickItem = (key) => {
    if (key === this.state.expanded) {
      this.setState({
        expanded: 'x!0-2#',
      })
    }
    else {
      this.setState({
        expanded: key,
      })
    }

  };

  handleChangeSorter = (pagination, filters, sorter) => {
    console.log('Various parameters', pagination, filters, sorter);
    this.setState({
      filteredInfo: filters,
      sortedInfo: sorter,
    });
  };

  clearFilters = () => {
    this.setState({filteredInfo: null});
  };
  clearAll = () => {
    this.setState({
      filteredInfo: null,
      sortedInfo: null,
    });
  };

  handleAccept = (task) => {
    this.setState({
      expanded: 'x!0-2#',
      snackbarMessage: task + ' Accepted',
      snackbarOpen: true,
    })
  };

  handleDecline = (task) => {
    this.setState({
      expanded: 'x!0-2#',
      snackbarMessage: task + ' Declined',
      snackbarOpen: true,
    })
  };

  handleClose = () => {
    this.setState({
      snackbarOpen: false
    })
  };


  setCustomerSort = () => {
    this.setState({
      sortedInfo: {
        order: 'descend',
        columnKey: ['user_orders.user.email'],
      },
    });
  };

  filterOrder =(it)=>{
    if(this.orderStore.filterBy === 'active'){
      return it.order_status_id == constant.ORDER_STATUSES.PREORDER_WAITING_STORE_RESPONSE || it.order_status_id == constant.ORDER_STATUSES.PROCESSING || it.order_status_id == constant.ORDER_STATUSES.ON_SHIPPING_RETRY;
    }
    else if(this.orderStore.filterBy === 'completed'){
      return it.order_status_id === constant.ORDER_STATUSES.COMPLETED || it.order_status_id === constant.ORDER_STATUSES.SHIPPING_COMPLETE
    }
    else{
      return true
    }
  }

  getOrderColor = (statusId) =>{
    const {ORDER_STATUSES} = constant;
    // {(this.order.selectedOrder.order_status.name === "Preorder Buyer Decline") ? 'status red' : (this.order.selectedOrder.order_status.name === 'Processing') ? 'status process' : 'status pending'}
    if(statusId == ORDER_STATUSES.CANCELLED || statusId == ORDER_STATUSES.FAILED || statusId == ORDER_STATUSES.CANCELLED_BY_STORE || statusId == ORDER_STATUSES.PREORDER_BUYER_DECLINE){
      return 'status red'
    }
    else if(  statusId == ORDER_STATUSES.ON_SHIPPING_RETRY ||
      statusId == ORDER_STATUSES.WAITING_STORE_RESPONSE  || statusId == ORDER_STATUSES.PROCESSING ||
      statusId == ORDER_STATUSES.ON_HOLD || statusId == ORDER_STATUSES.PREORDER_WAITING_STORE_RESPONSE|| statusId ==  ORDER_STATUSES.PENDING_PAYMENT || statusId == ORDER_STATUSES.PREORDER_WAITING_PAYMENT || statusId == ORDER_STATUSES.WAITING_PAYMENT_APPROVAL || statusId == ORDER_STATUSES.PREORDER_WAITING_BUYER_CONFIRMATION

    ) {
      return 'status pending';
    }
    else if(statusId == ORDER_STATUSES.COMPLETED  || statusId == ORDER_STATUSES.SHIPPING_COMPLETE
      ||statusId == ORDER_STATUSES.ON_SHIPPING  ){
      return 'status process'
    }

  }


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

  render() {

    let {sortedInfo, filteredInfo} = this.state;
    sortedInfo = sortedInfo || {};

    filteredInfo = filteredInfo || {};


    const columns = [{
      title: 'Id',
      dataIndex: 'this.orderStore.orderList.id',
      key: 'this.orderStore.orderList.id',
      className: 'recentOrder-noOrder',
      render: (text, data) => <Link to={`${LINKS.ORDER}/${data.id}`}
                                    key={data.order_id}>{<span>{(data.id.split("-")[0])}</span>}</Link>,

    },
      {
        title: 'Date',
        dataIndex: 'created_at',
        key: 'created_at',
        className: 'recentOrder-noOrder',
        render: (text) => (
          <div>
            <span>{moment(text).format('MMM DD, YYYY')}</span> <span className='smaller lighter'>{moment(text).format('hh:mm')}</span>
          </div>
        )
      },
      {
        title: 'Customer',
        dataIndex: 'user_orders.user.profile',
        key: 'user_orders.user.profile',
        className: 'recentOrder-noOrder',
        sorter: (a, b) => (a.user_orders.user.profile && a.user_orders.user.profile.firstname) - (b.user_orders.user.profile && b.user_orders.user.profile.firstname),
        sortOrder: sortedInfo.columnKey === 'user_orders.user.profile.firstname' && sortedInfo.order,
        render: (text, data) => {
            if(data.user_orders && data.user_orders.user && data.user_orders.user.profile && data.user_orders.user.profile.firstname) {
                return (<span>{data.user_orders.user.profile.firstname+' '+data.user_orders.user.profile.lastname}</span>);
            }
            
            return <span>{data.user_orders.user.email}</span>
        }
      },
      {
        title: 'Type',
        dataIndex: 'is_preorder',
        key: 'is_preorder',
        className: 'recentOrder-noOrder',
        render: (text, data) => (data.is_preorder === true) ? "Pre Order" : <span>Order</span>
      },

      {
        title: 'Status',
        dataIndex: 'this.orderStore.orderList.order_status.name',
        key: 'this.orderStore.orderList.order_status.name',
        className: 'recentOrder-status',
        render: (text, data) =>
          (data.order_status === null) ? "No Status" : <div><span
            className={this.getOrderColor(data.order_status_id)}/><span>{(data.order_status.name).split('Preorder')}</span>
          </div>


      },
      {
        title: 'Total',
        dataIndex: 'this.orderStore.orderList.subtotal',
        key: 'this.orderStore.orderList.subtotal',
        className: 'recentOrder-customer bolder green',
        render: (text, data, value) => {
          return <NumberFormat
            style={{color: ((data.order_status.name) === 'Preorder Buyer Decline') ? 'red' : '#000'}}
            value={new DC(data.subtotal).add(data.shipping_price).toNumber()} displayType={'text'}
            thousandSeparator={true} prefix={'Rp. '}/>

        }

      }];


    /*() => {

    (this.orderStore.orderList.length > 0) ? (this.orderStore.isSearching ? this.orderStore.dataFiltered : this.orderStore.orderList).map((item, index) => (

    )) : <EmptyComponent type="empty" header="" content="There is no data in sight"/>

  };*/

    return (
      <div className="order containerMiddle">
        <div className="row">
          <div className="col l12 m12 s12">
            <div style={{marginBottom: '16px'}}>
              <h3 className="headerMenu">Order</h3>
            </div>
            <Card className="animated fadeIn  no-shadow" style={{backgroundColor: 'transparent'}}>
              <Toolbar className="toolbarCard" style={{backgroundColor: '#fff'}}>
                <ToolbarGroup>
                  <SearchIcon style={{marginRight: 8, color: "#999"}}/>
                  <TextField
                    hintText="Search Order ID"
                    style={{fontSize: 14}}
                    hintStyle={{fontSize: 14}}
                    underlineShow={false}
                    onChange={this.search}
                  />
                </ToolbarGroup>
              </Toolbar>
              <Divider/>
              <div className="row">
                <div className="col l12 m12 s12">
                  <SelectField
                    floatingLabelText="Filter"
                    value={this.orderStore.filterBy}
                    onChange={(e,i,v)=>this.orderStore.changeFilterBy(v)}
                    floatingLabelStyle={{color : '#6772e5'}}
                    underlineStyle={{border:0}}
                  >
                    <MenuItem value={'active'} primaryText="Only Active Order" />
                    <MenuItem value={'completed'} primaryText="Completed" />
                    <MenuItem value={'all'} primaryText="All Order" />
                  </SelectField>
                </div>
              </div>


              <Loader show={this.globalUI.loadingVisibility} message={<LoadingDialog/>}
                      messageStyle={{textAlign: 'center'}}
                      backgroundStyle={{backgroundColor: 'rgba(255,255,255,0.5)'}}>


                <TableAntd
                  pagination={true}
                  className='table-padded'
                  dataSource={this.orderStore.isSearching ? this.orderStore.dataFiltered : this.orderStore.orderList.filter(this.filterOrder)}
                  onChange={this.handleChangeSorter}
                  columns={columns}
                  onRow={(record) => {
                    return {
                      onClick: () => {
                        this.props.history.push(`${LINKS.ORDER}/${record.id}`);
                      },       // click row
                    };
                  }}
                />

              </Loader>
            </Card>
            <Snackbar
              open={this.state.snackbarOpen}
              message={this.state.snackbarMessage}
              action="OK"
              autoHideDuration={4000}
              onActionClick={this.handleClose}
              onRequestClose={this.handleClose}
            />
          </div>
        </div>
      </div>
    )
  }
}
