import React from "react";
import {inject, observer} from "mobx-react";
import QueueAnim from 'rc-queue-anim';
import "./style.scss";
import NumberFormat from 'react-number-format';
import {LINKS} from './../../routes'
import {Link} from 'react-router-dom';
import CardAdmin from './CardAdmin';
import CardAgent from './CardAgent';
import moment from 'moment';
import {Icon, Button, notification, Table, Tooltip as TooltipAntd} from 'antd';
import DC from 'decimal.js-light';
import {
  Paper,
  Card,
  CardActions,
  CardHeader,
  CardMedia,
  CardTitle,
  CardText,
  FlatButton,
  GridList,
  GridTile,
  Divider, ListItem, List
} from 'material-ui';
import EmptyComponent from '../EmptyComponent';
import * as _ from 'lodash';
import {grey400, darkBlack, lightBlack, black} from 'material-ui/styles/colors';
import './style.scss';
import {Carousel} from 'react-responsive-carousel'
import {ActionGrade, ContentDrafts, ContentInbox, ContentSend} from "material-ui/svg-icons/index";
import {constant} from "../../config/const";

const {
  LineChart,
  AreaChart,
  BarChart,
  Bar,
  Line,
  XAxis,
  YAxis,
  ReferenceLine,
  CartesianGrid,
  Tooltip,
  Legend,
  Area,
  ResponsiveContainer
} = require('recharts/umd/Recharts.min');

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

  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      list: [],
      my_item: 0,
    };
    this.defaultState = Object.assign({}, this.state);
    this.globalUI = props.appstate.globalUI;
    this
      .globalUI
      .changeBackgroundColor("#f7f7f7");
    // .changeBackgroundColor("#208166");
    this.dashboardStore = props.appstate.dashboard;
    this.http = props.appstate.http;
    this.packageStore = props.appstate.packages;
    this.user = props.appstate.user;
    this.userData = props.appstate.userData;
    this.transactionStore = props.appstate.transaction;
    this.taskStore = props.appstate.task;
    this.myStoreItem = props.appstate.myStoreItem;
    this.orderStore = props.appstate.order;
    this.globalUI = props.appstate.globalUI;
  }

  componentDidMount() {
    this.transactionStore.getAmount();
    this.dashboardStore.getData();
    this.packageStore.getAllPackages();
    if (this.userData.role === 'admin') {
      this.taskStore.getAllDeposit();
    } else {
      this.transactionStore.getAll();
      this.checkStatus();
    }
    this.myStoreItem.getAll().then(res => {
      this.setState({
        my_item: res.max
      });
    });
    this.globalUI.openLoading();
    this.orderStore.getAllOrder().then(res => {
      this.globalUI.closeLoading();
    });
  }

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

  checkStatus = () => {
    this.transactionStore.list.map((item, index) => {
      if (item.status !== 'created') {
        this.state.list.push(item);
      } else {
        // return this.state.list;
      }
    });
  };

  iniUntukstatus = (text) => {
    if(text == '') {
      <div><span className='status-pill smaller process'/><span>No Status</span></div>
    }
    else if(text == 'Finished'){
      return (<div><span className='status-pill smaller process'/><span>Finished</span></div>)
    }
    else if(text == 'Pending Payment'){
      return (<div><span className='status-pill smaller pending'/><span>Pending Payment</span></div>)
    }
    else{
      return (<div><span className='status-pill smaller'/><span>No Status</span></div>)
    }
  };

  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{
      return true
    }
  }

  render() {
    const undeposit_fund = <NumberFormat value={new DC(this.transactionStore.wallet.pending_payment_to_wallet || 0).toFixed(2)} displayType={'text'} thousandSeparator={true} prefix={'Rp '}/>;
    const balance = <NumberFormat value={new DC(this.transactionStore.wallet.balance || 0).toFixed(2)} displayType={'text'} thousandSeparator={true} prefix={'Rp '}/>;
    const dataSource = [
      // this.orderStore.orderList.map((item, index) => (
      //   {
      //     key: item.order_id,
      //     noOrder: item.order_id,
      //     customer: item.user_orders.user.email,
      //     date: item.order_id,
      //     hours: '12:00',
      //     items: item.order_id,
      //     status: item.order_id,
      //     total: item.order_id,
      //   }
      // ))
      {
        key: '1',
        noOrder: '180801061774YSV',
        customer: 'Mike',
        date: 'Yesterday',
        hours: '13:00',
        items: 'Hannah dress',
        status: 'Processing',
        total: 'Rp200.000',
      }
     , {
      key: '2',
      noOrder: '180801061774YSV',
      customer: 'Mike',
      date: 'Yesterday',
      hours: '13:00',
      items: 'Hannah dress',
      status: 'Processing',
      total: 'Rp200.000',
    }, {
      key: '3',
      noOrder: '190801061774YSV',
      customer: 'Mike',
      date: 'Feb 16, 2018',
      hours: '10:00',
      items: '10 Downing',
      status: 'Processing',
      total: 'Rp200.000',
    }, {
      key: '4',
      noOrder: '200801061774YSV',
      customer: 'Mike',
      date: 'Feb 15, 2018',
      hours: '20:00',
      items: '10 Downing Street',
      status: 'Processing',
      total: 'Rp200.000',
    }
  ]

    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}>{(data.id.split("-")[0])}</Link>,

    },{
      title: 'Customer',
      dataIndex: 'user_orders.user.email',
      key: 'user_orders.user.email',
      className: 'recentOrder-noOrder',
      render: (text, data) => <span>{text}</span>
    }, {
      title: 'Date',
      key: 'created_at',
      className: 'recentOrder-date',
      render: (text) => (
        <div>
          <span>{moment(text.created_at).format('MMM DD, YYYY')}</span> <span className='smaller lighter'>{moment(text.created_at).format('hh:mm')}</span>
        </div>
      )
    }, {
      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={((data.order_status.name) === 'Preorder Buyer Decline') ? 'status-pill smaller red' : (data.order_status.name === 'Processing') ? 'status-pill smaller process' : ' status-pill smaller pending'}/><span>{(data.order_status.name).split('Preorder')}</span>
        </div>


    }, {
      title: 'Total',
      dataIndex: 'user_orders.total',
      key: 'user_orders.total',
      className: 'recentOrder-customer',
      render: (text, data, value) => {
        return <NumberFormat style={{color: ((data.order_status.name) === 'Preorder Buyer Decline') ? 'red' : '#000'}} value={data.user_orders.total} displayType={'text'} thousandSeparator={true} prefix={'Rp. '} />
      }
    }
  ];

    return (
      <div className="dashboard animated fadeIn">
        <div className="row ">
          <div className="col s12 m9 l9 col-leftDashboard" style={{marginBottom: 0}}>
            <div className="row element-wrapper no-margin">
              <div className='element-header'>
                <h3>Sales Dashboard</h3>
              </div>
              <div className="col s12 m4 l4" style={{marginBottom: 0}}>
                <Card className="cardLite cardDashboard">
                  <h3 style={{
                    display: 'block',
                    fontSize: '.63rem',
                    textTransform: 'uppercase',
                    color: '#0006',
                    letterSpacing: 1
                  }}> Items Sold</h3>
                  <div className="value">{this.dashboardStore.data.item_sold}</div>
                  <div>
                    <Link to={LINKS.ITEMS} className="btnFlatUnderline ">
                      <span>View Detail</span>
                      <Icon className="ml-8" type="right"/>
                    </Link>
                  </div>
                </Card>
              </div>

              <div className="col s12 m4 l4" style={{marginBottom: 0}}>
                <Card className="cardLite cardDashboard">
                  <h3 style={{
                    display: 'block',
                    fontSize: '.63rem',
                    textTransform: 'uppercase',
                    color: '#0006',
                    letterSpacing: 1
                  }}> Items</h3>
                  <div className="value">{this.dashboardStore.data.item}</div>
                  <div>
                    <Link to={LINKS.ITEMS} className="btnFlatUnderline ">
                      <span>View Items</span>
                      <Icon className="ml-8" type="right"/>
                    </Link>
                  </div>
                </Card>
              </div>

              <div className="col s12 m4 l4" style={{marginBottom: 0}}>
                <Card className="cardLite cardDashboard">
                  <h3 style={{
                    display: 'block',
                    fontSize: '.63rem',
                    textTransform: 'uppercase',
                    color: '#0006',
                    letterSpacing: 1
                  }}> Process Order</h3>
                  <div className="value oldGreeen">{this.dashboardStore.data.order}</div>
                  <div>
                    <Link to={LINKS.ORDER} className="btnFlatUnderline green">
                      <span>View Order</span>
                      <Icon className="ml-8" type="right"/>
                    </Link>
                  </div>
                </Card>
              </div>
            </div>

            <div className="row element-wrapper">

              <div className='element-header'>
                <h3>Recent Order</h3>
              </div>
              <div className="col s12 m12 l12" style={{marginBottom: 0}}>
                <Table
                pagination={false}
                className='table-padded'
                dataSource={this.orderStore.orderList.filter(this.filterOrder).slice(0, 5)}
                columns={columns}
                onRow={(record) => {
                    return {
                      onClick: () => {
                        this.props.history.push(`${LINKS.ORDER}/${record.id}`);
                      },       // click row
                    };
                  }}
                />
              </div>
            </div>

            {/*<Card  className="cardLite" style={{marginBottom: (window.innerWidth < 600) ? 10 : 10, height: "auto"}}>*/}
            {/*<CardHeader*/}
            {/*title={<h1 style={{fontSize: 22, fontWeight: '400'}}>Revenue by services</h1>}/>*/}
            {/*<div style={{height: (this.userData.role === 'admin') ? "355px" : "237px", maxWidth: '100%'}}>*/}
            {/*<SimpleAreaChart/>*/}
            {/*</div>*/}
            {/*</Card>*/}
          </div>


          <div className="col s12 m3 l3 col-rightDashboard">
            <section className='row element-wrapper'>
              <div className='element-header'>
                <h3>Quick Links</h3>
              </div>
              <div className="col s12 m12 l12">
                <Button icon={"plus-circle-o"} className={'fullWidthButton btnSmCustom btnSmCustomWhite'}
                        style={{marginBottom: '0.5rem'}} onClick={() => this.props.history.push(`${LINKS.FORM_UPLOAD}`)}>Create New Item</Button>
                <Button icon={"exception"} className={'fullWidthButton btnSmCustom btnSmCustomWhite'}
                        style={{marginBottom: '0.5rem'}} onClick={() => this.props.history.push(`${LINKS.INBOX}`)}>Chat Inbox</Button>
                {this.props.appstate.userData.role === 'store' && <Button  icon={"home"} className={'fullWidthButton btnSmCustom btnSmCustomWhite'}
                        style={{marginBottom: '0.5rem'}} onClick={() => this.props.history.push(`${LINKS.STORES}`)}>Store Setting</Button>}
              </div>
            </section>
            <section>
              <div className='element-header'>
                <h3>Financial Overview</h3>
              </div>
              <div className="col s12 m12 l12">
                <Card className="cardLite cardDashboard">
                  <h3 style={{
                    display: 'block',
                    fontSize: '.63rem',
                    textTransform: 'uppercase',
                    color: '#0006',
                    letterSpacing: 1
                  }}> Undeposited Funds <TooltipAntd title="Your store pending payment"><Icon
                    style={{color: '#6772e5', fontSize: '.7rem'}} type="info-circle"/></TooltipAntd></h3>
                  <div>
                    <a className=" btnFlatUnderlineSingleBlack" style={{color:'#3E4B5B'}}>
                      <span>{undeposit_fund}</span>
                      {/*<Icon className="ml-8" type="right"/>*/}
                    </a>
                  </div>
                  <Divider className='divider-financial'/>
                  <h3 style={{
                    display: 'block',
                    fontSize: '.63rem',
                    textTransform: 'uppercase',
                    color: '#0006',
                    letterSpacing: 1
                  }}> Total Balance <TooltipAntd title="Your store total balance"><Icon
                    style={{color: '#6772e5', fontSize: '.7rem'}} type="info-circle"/></TooltipAntd></h3>
                  <div>
                    <a className=" btnFlatUnderlineSingle">
                      <span>{balance}</span>
                      {/*<Icon className="ml-8" type="right"/>*/}
                    </a>
                  </div>
                </Card>
              </div>
            </section>

          </div>


          {/*{(this.userData.role === 'admin') ? <CardAdmin/> : <CardAgent/>}*/}
        </div>


        {/*<div className="row">*/}
        {/*<div className="col s12 m8 l8">*/}
        {/*<Card className="cardLite" style={{maxHeight: 400}}>*/}
        {/*{(!this.packageStore.isPackageEmpty) ?*/}
        {/*<Carousel showThumbs={true}*/}
        {/*autoPlay={true}*/}
        {/*dynamicHeight={true}*/}
        {/*infiniteLoop={true}*/}
        {/*showStatus={false}*/}
        {/*stopOnHover={true}*/}
        {/*showIndicators={false}>*/}
        {/*{this.packageStore.packagesList.map((tile, index) => (*/}
        {/*<Link key={index} to={{pathname: `${LINKS.SERVICE_PACKAGES}/${tile.id}`, query: {data: tile}}}>*/}
        {/*<CardMedia>*/}
        {/*<img src={this.http.appendImagePath(tile.banner)} style={{objectFit: "cover", height: 330}}/>*/}
        {/*<div className="legend">*/}
        {/*<h1>{tile.name} </h1>*/}
        {/*<p><NumberFormat value={tile.price} displayType={'text'} thousandSeparator={true}*/}
        {/*prefix={'IDR '}/></p>*/}
        {/*</div>*/}
        {/*</CardMedia>*/}
        {/*</Link>*/}
        {/*))}*/}
        {/*</Carousel>*/}
        {/*: <div></div>*/}
        {/*}*/}
        {/*</Card>*/}
        {/*</div>*/}
        {/*<div className="col s12 m4 l4">*/}
        {/*<Card className="cardLite" style={{marginBottom: (window.innerWidth < 600) ? 10 : 10, height: "auto"}}>*/}
        {/*<CardHeader*/}
        {/*title={<h1 style={{fontSize: 22, fontWeight: '400'}}>Latest News</h1>}/>*/}
        {/*<List>*/}
        {/*<Divider/>*/}
        {/*{*/}
        {/*(this.userData.role === 'admin') ?*/}
        {/*(!this.taskStore.isEmpty) ?*/}
        {/*this.taskStore.tasks.slice(0, 5).map((item, index) => {*/}
        {/*return (item.type == 'deposit' || item.type == 'withdraw') ? (*/}
        {/*<Link to={`${LINKS.TASKS}/${item.transaction_id}`}>*/}
        {/*<ListItem*/}
        {/*// leftAvatar={<Avatar src="images/ok-128.jpg" />}*/}
        {/*primaryText={_.capitalize(item.type) + " Request"}*/}
        {/*secondaryText={*/}
        {/*<div>*/}
        {/*<p>*/}
        {/*<span style={{color: darkBlack}}>{item.user.username}</span> --*/}
        {/*<NumberFormat value={item.amount} displayType={'text'} thousandSeparator={true}*/}
        {/*prefix={'IDR '}/>*/}
        {/*</p>*/}
        {/*<p style={{fontSize: 10, color: black}}>{moment(item.created_at).fromNow()}</p>*/}
        {/*</div>*/}
        {/*}*/}
        {/*secondaryTextLines={2}*/}
        {/*/>*/}
        {/*</Link>*/}
        {/*) :*/}
        {/*(*/}
        {/*<Link to={`${LINKS.SERVICE_AIRLINES_REVIEW}/${item.id}`}>*/}
        {/*<ListItem*/}
        {/*// leftAvatar={<Avatar src="images/ok-128.jpg" />}*/}
        {/*primaryText={_.capitalize(item.type) + " Request"}*/}
        {/*secondaryText={*/}
        {/*<div>*/}
        {/*<p>*/}
        {/*<span style={{color: darkBlack}}>{item.customer.name}</span>*/}
        {/*-- {item.request_data.selectedDepartureFlight.fromcity}*/}
        {/*TO {item.request_data.selectedDepartureFlight.tocity}*/}
        {/*</p>*/}
        {/*<p style={{fontSize: 10, color: black}}>{moment(item.created_at).fromNow()}</p>*/}
        {/*</div>*/}
        {/*}*/}
        {/*secondaryTextLines={2}*/}
        {/*/>*/}
        {/*</Link>*/}
        {/*);*/}
        {/*}) : <EmptyComponent width="" image="default4" type="empty" header="" content="No News yet."/>*/}
        {/*:*/}
        {/*(this.state.list.length > 0) ?*/}
        {/*this.state.list.slice(0, 5).map((item, index) => {*/}
        {/*return (*/}
        {/*<ListItem*/}
        {/*primaryText={`Your ${_.capitalize(item.type.name)} Request Has Been ${_.capitalize(item.status)}`}*/}
        {/*secondaryText={*/}
        {/*<Link*/}
        {/*to={`${LINKS.WALLET}/${item.id}`}*/}
        {/*>*/}
        {/*<p>*/}
        {/*<span style={{color: darkBlack}}>{_.capitalize(item.type.name)}</span> --*/}
        {/*<NumberFormat value={item.amount} displayType={'text'} thousandSeparator={true}*/}
        {/*prefix={'IDR '}/>*/}
        {/*</p>*/}
        {/*<p style={{fontSize: 10, color: black}}>{moment(item.updated_at).fromNow()}</p>*/}
        {/*</Link>*/}
        {/*}*/}
        {/*/>*/}
        {/*);*/}
        {/*}) : <EmptyComponent width="" image="default4" type="empty" header="" content="No News yet."/>*/}
        {/*}*/}
        {/*</List>*/}
        {/*<Divider/>*/}
        {/*</Card>*/}
        {/*</div>*/}
        {/*</div>*/}
      </div>
    )
  }
}
