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 AddIcon from 'material-ui/svg-icons/content/add';
import DeleteIcon from 'material-ui/svg-icons/action/delete';
import ImageEdit from 'material-ui/svg-icons/image/edit';
import EmptyComponent from '../EmptyComponent';
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";
import {get} from 'lodash';
const {Column, ColumnGroup} = Table;


@inject('appstate')
@observer
export default class NotificationAdmin extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.notificationStore = props.appstate.notification;
    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.globalUI.openLoading();
      this.notificationStore.getList().then(res => {
        this.globalUI.closeLoading();
        if(this.notificationStore.unread_notif > 0){
          this.notificationStore.readAll();
        }
      });
      console.log(this.notificationStore.list,'ini list')
    }

  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.state.filter == 'active'){
      return it.order_status_id == constant.ORDER_STATUSES.PREORDER_WAITING_STORE_RESPONSE || it.order_status_id == constant.ORDER_STATUSES.PROCESSING;
    }
    else{
      return true
    }
  }


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

  render() {

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

    filteredInfo = filteredInfo || {};


    const columns = [{
      title: 'Notification',
      dataIndex: 'notification.title',
      key: 'notification.title',
      className: 'recentOrder-noOrder',
      render: (text, data) => {
            return <span>{data.notification.title}</span>
      }

    },
      {
        title: 'Description',
        dataIndex: 'notification.description',
        key: 'notification.description',
        className: 'recentOrder-noOrder',
        render: (text, data) => {
            return <span>{data.notification.description}</span>
        }
      },
      {
        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>
        )
      },
      ];


    /*() => {

    (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">
            <Card className="animated fadeIn  no-shadow" style={{backgroundColor: 'transparent'}}>  
              <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.notificationStore.isSearching ? this.notificationStore.filtered : this.notificationStore.list}
                  onChange={this.handleChangeSorter}
                  columns={columns}
                  onRow={(record) => {
                    return {
                      onClick: () => {
                        if(record.notification.type == 'order_seller' && get(record,'notification.additional_data.user_order_store_id',false) != false){
                          // console.log(get(record,'notification.additional_data.user_order_store_id',false));
                          this.props.historyPush(`${LINKS.ORDER}/${record.notification.additional_data.user_order_store_id}`);
                        }
                        else if(record.notification.type == 'order_seller' && get(record,'notification.additional_data.user_order_store_id',false) == false){
                          // console.log(get(record,'notification.additional_data.user_order_id',false));
                          this.props.historyPush(`${LINKS.ORDER}`);
                        }
                      },
                    };
                  }}
                />

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