import React from 'react';
import {observer, inject} from 'mobx-react';
import {
  Card,
  Divider,
  Snackbar,
  Toolbar,
  Table,
  SelectField,
  MenuItem,
  ToolbarGroup,
} from 'material-ui';
import {Table as TableAntd} from 'antd';
import {Link} from 'react-router-dom';
import {LINKS} from "../../routes";
import './style.scss';
import LoadingDialog from "../LoadingDialog";
import Loader from 'react-loader-advanced';
import {startCase} from 'lodash';


@inject('appstate')
@observer
export default class OrderComponent extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    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.orderStore = props.appstate.order;
    this.http = props.appstate.http;
    this.authStore = props.appstate.auth;
    this.globalUI = props.appstate.globalUI;
    this.taskStore = props.appstate.task;
  }

  componentDidMount() {
    // this.orderStore.isSearching = false;
    this.globalUI.openLoading();
    // this.orderStore.getAllOrder().then(res => {
    //   console.log(res)
    //   this.globalUI.closeLoading();
    // });
    this.taskStore.getAll().then(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.taskStore.filterBy === 'withdraw'){
      return it.type === "withdraw";
    }
    else{
      return true
    }
  };


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

  render() {

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

    filteredInfo = filteredInfo || {};


    const columns = [{
      title: 'Id',
      dataIndex: 'id',
      key: 'id',
      className: 'recentOrder-noOrder',
      render: (text) => <Link to={`${LINKS.TASKS}/${text}`} key={text}>{<span>{(text.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: 'Store',
        dataIndex: 'transaction.user.store.name',
        key: 'transaction.user.store.name',
        className: 'recentOrder-noOrder',
        render: (text) => {
            return <span>{text}</span>
        }
      },
      {
        title: 'Type',
        dataIndex: 'type',
        key: 'type',
        className: 'recentOrder-noOrder',
        render: (text) =>  <span>{startCase(text)}</span>
      }];


    /*() => {

    (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">Tasks</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.taskStore.filterBy}
                    onChange={(e,i,v)=>this.taskStore.changeFilterBy(v)}
                    floatingLabelStyle={{color : '#6772e5'}}
                    underlineStyle={{border:0}}
                  >
                    <MenuItem value={'all'} primaryText="All" />
                  </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.taskStore.isSearching ? this.taskStore.dataFiltered : this.taskStore.data.filter(this.filterOrder)}
                  onChange={this.handleChangeSorter}
                  columns={columns}
                  onRow={(record) => {
                    return {
                      onClick: () => {
                        this.props.history.push(`${LINKS.TASKS}/${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>
    )
  }
}
