import React from "react";
import {inject, observer} from "mobx-react";
import {Link} from "react-router-dom";
import {Helmet} from "react-helmet";
import "../../styles/constants.scss";
import "../../styles/style.scss";
import "./style.scss";
import {LINKS} from "../../routes";
import startcase from "lodash.startcase";
import Route from "./routes";
import moment from 'moment';
import {Icon, Button, Modal, notification} from 'antd';
import {
  Divider,
  Drawer,
  List,
  ListItem,
  IconMenu,
  IconButton,
  MenuItem,
  DropDownMenu,
  RaisedButton,
  Paper,
  Dialog,
  Snackbar,
  Toolbar, ToolbarGroup, ToolbarSeparator, ToolbarTitle, Badge
} from 'material-ui';
import IconUserCircle from 'material-ui/svg-icons/action/account-circle';
import ShoppingCart from 'material-ui/svg-icons/action/shopping-cart';
import DepositDialog from './../DepositDialog';
import WithdrawDialog from './../WithdrawDialog';
import IconMenus from 'material-ui/svg-icons/navigation/menu';
import LoadingDialog from '../LoadingDialog/index';
import * as _ from 'lodash'; // TODO: remove this, import only needed module from lodash
import PrintProvider, {Print, NoPrint} from 'react-easy-print';
import {black} from "material-ui/styles/colors";
import cinnamonSugar from 'cinnamon-sugar';
import ButterToast from 'butter-toast';
import 'material-design-icons/iconfont/material-icons.css';
import {grey400, darkBlack, lightBlack} from 'material-ui/styles/colors';
import {getMobileOperatingSystem} from '../../stores/firebase';
import Alert from "../../components/Alert";
import EmptyComponent from '../EmptyComponent';
import NumberFormat from 'react-number-format';
import faker from 'faker';
import { Route as RouteDOM } from 'react-router-dom'
import WalletComponent from "./WalletComponent";
import {APP_TYPE} from "../../config/app";


faker.locale = 'id_ID';
@inject("appstate")
@observer
export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      scriptTawkto: false,
      redirect: false,
      open: (window.innerWidth < 600) ? false : true,
      openSecondary: false,
      value: '',
      additionalData: {},
      valueMultiple: [''],
      valueSingle: '',
      visible: false,
      selectedMenu: this.props.location.pathname,
      projectId: 'project-id',
      breadcrumbs: this
        .props
        .location
        .pathname
        .split('/')
        .map(path => startcase(path)),
    };
    this.defaultState = Object.assign({}, this.state);
    this.user = props.appstate.user;
    this.authStore = props.appstate.auth;
    this.globalUI = props.appstate.globalUI;
    this.http = props.appstate.http;
    this.appstate = props.appstate;
    this.settingStore = props.appstate.setting;
    this.transactionStore = props.appstate.transaction;
    this.dashboardStore = props.appstate.dashboard;
    this.taskStore = props.appstate.task;
    this.appStore = props.appstate.app;
    this.profileStore = props.appstate.profile;
    this.notificationStore = props.appstate.notification;
    //
    // if (getMobileOperatingSystem() !== 'iOS') {
    //   this.messaging = firebase.messaging();
    //   this.notification();
    // }
  }

  openNotification(type, title, content, icon) {
    if (type) {
      notification[type]({
        message: (title) ? title : 'Title',
        description: (content) ? content :
          <p style={{color: "black"}}>This is the content of the notification. This is the content of the notification.
            This is the content of the notification.</p>,
        icon: <Icon type={(icon) ? icon : "smile-circle"} style={{color: 'black'}}/>
      });
      notification.open();

    } else {
      notification.open({
        message: (title) ? title : 'Title',
        description: (content) ? <p style={{color: "black"}}>{content}</p> :
          <p style={{color: "black"}}>This is the content of the notification. This is the content of the notification.
            This is the content of the notification.</p>,
        icon: <Icon type={(icon) ? icon : "smile-circle"} style={{color: '#108ee9'}}/>
      });
    }
  };

  notification = () => {
    console.log('called again?');
    this.messaging.onMessage((payload) => {
      console.log("Message received cok.", payload);
      // alert(payload.notification.body);
      const toast = cinnamonSugar({
        kind: 'crisp',
        theme: 'info',
        // picture: 'http://lorempixel.com/150/150/people',
        title: <a href={payload.notification.click_action}>{payload.notification.title}</a>, // you can also add jsx code here!
        // message: JSON.stringify(payload), // you can also add jsx code here!
        message: payload.notification.body, // you can also add jsx code here!
        toastTimeout: 4000,
        icon: 'bell' // literally any font awesome 4.7 icon
        // you may also add here regular butter-toast options, such as toastTimeout,
        // name, sticky, etc..
      });
      ButterToast.raise(toast)
    });
  };

  showModal = () => {
    this.setState({
      visible: true,
    });
  };

  handleOk = (e) => {
    console.log(e);
    this.setState({
      visible: false,
    });
  };

  handleCancel = (e) => {
    console.log(e);
    this.setState({
      visible: false,
    });
  };

  componentDidMount() {
    // this.checkIsLogin();
    // this.settingStore.getAll();
    this.authStore.getProfile();

    setTimeout(() => {
      console.log(this.authStore.userProfile, 'this.authStore.userProfile this.authStore.userProfile');
    }, 2500)
    // this.user.getUserGeolocation();
    // this.appStore.getAppType();
    // this.profileStore.getProfile();
    // this.notificationStore.getList()

    notification.config({
      placement: 'bottomRight',
      duration: 10,
      style: {
        width: 350,
        color: "black"
      },
    });
  }

  componentWillMount() {
  }

  componentWillReceiveProps(nextProps) {
    // will be true
    // const locationChanged = nextProps.location !== this.props.location;
    //
    // this.checkIsLogin();
  }

  checkIsLogin() {
    // if (!this.authStore.isLoggedIn  ) {   console.log(this.props.history);
    // this.props.history.replace(LINKS.LOGIN); }
  }

  willLogout() {
    // Modal.confirm({
    //   title: 'Log out the system?',
    //   content: 'Are sure sure you want to log out the system?',
    //   okText: 'Confirm',
    //   cancelText: 'Cancel',
    //   visible: this.state.visible,
    //   zIndex: 3000,
    //   onOk: () => {
    //     this.authStore.logout();
    //     this.setState({
    //       visible: false,
    //       redirect: true
    //     });
    //   },
    //   onCancel: () => {
    //     this.setState({
    //       visible: false,
    //     });
    //   }
    // });
  }

  openCreateProjectDialog() {

  }

  handleToggleIcon = () => this.setState({open: !this.state.open});
  handleToggleIconSecondary = () => this.setState({openSecondary: !this.state.openSecondary});
  handleClose = () => this.setState({open: false});


  handleChangeSingle = (event, value) => {
    this.setState({
      valueSingle: value,
    });
  };

  handleChangeMultiple = (event, value) => {
    this.setState({
      valueMultiple: value,
    });
  };

  handleOpenMenu = () => {
    this.setState({
      openMenu: true,
    });
  }

  handleOnRequestChange = (value) => {
    this.setState({
      openMenu: value,
    });
  }

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

  changeRoute = (path) => {
    this.setState({selectedMenu: path});
    if (window.innerWidth < 600) {
      this.handleClose()
    }
  }

  toggle = () => {
    this.setState({
      collapsed: !this.state.collapsed
    });
  };

  toggleDrawer = () => {
    this.setState({
      open: !this.state.open
    });
  };

  render() {

    const {redirect} = this.state;
    if (redirect) {
      this.props.history.replace(LINKS.LOGIN);
      // return <Redirect to={{
      //   pathname: '/login',
      //   state: {from: this.props.location}
      // }}/>
    }
    const styles = {
      Paper: {
        height: 38,
        width: 38,
        background: '#fff',
        marginRight: 16,
        padding: 4
      },
      ImageRounded: {
        display: 'block',
        borderRadius: '50%',
        maxWidth: '100%',
        marginTop: '0px'
      }
    };

    // ROLE dan Menu
    // agent, ga ada setting, member, task
    // if (window && !window.Tawk_API) {
    //   const script = document.createElement("script");
    //   (this.settingStore.setting.tawkto_siteid && !this.state.scriptTawkto && this.appstate.userData.role === 'agent') ? (() => {
    //     const scriptText = document.createTextNode(`
    //   var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
    //   (function(){
    //   var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
    //   s1.async=true;
    //   s1.src='https://embed.tawk.to/${this.settingStore.setting.tawkto_siteid}/default';
    //   s1.charset='UTF-8';
    //   s1.setAttribute('crossorigin','*');
    //   s0.parentNode.insertBefore(s1,s0);
    // })();`);
    //     script.appendChild(scriptText);
    //     script.async = true;
    //     document.body.appendChild(script);
    //     this.setState({scriptTawkto: true})
    //   })() : '';
    // }

    const {userData} = this.appstate;
    // const applicationIcon = (this.settingStore.isIconEmpty) ? "/assets/images/bankbtn.png" : this.http.appendImagePath(this.settingStore.setting.icon);
    // let applicationIcon =  "http://giift.asacreative.com/giift_logo_wide.4d15de72.png";
    let applicationIcon = require('../../../../assets/images/logo_new.png');
    let applicationName = 'Giift';
    if(APP_TYPE === 'btn') {
      applicationIcon = "http://btn-redemption-2.bangun-kreatif.com/dr6u0fppdi4xy.cloudfront.net/FilesDirectory/Albilad/ImgIconImage/logo-btn.png";
      applicationName = "BTN";
    }

    let onNotifRowClick = (record) => {
      // if(record.notification.type == 'order_seller' && _.get(record,'notification.additional_data.user_order_store_id',false) != false){
      //   return `${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){
      //   return `${LINKS.ORDER}`;
      // }
      return `${LINKS.ORDER}`;
    }
    return (
      <PrintProvider>
        <NoPrint>
          <div className="app-container">
            <Helmet>
              <meta charSet="utf-8"/>
              <title>{applicationName}</title>
              <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
              <link rel="icon" type="image/png" href={applicationIcon} sizes="96x96"/>
            </Helmet>

            <ButterToast trayPosition="bottom-right"/>
            <Snackbar
              open={this.globalUI.snackbarVisibility}
              message={this.globalUI.snackbarMessage}
              autoHideDuration={3000}/>

            <Dialog
              style={{margin: 'auto'}}
              open={this.globalUI.loadingVisibility}>
              <div style={{textAlign: 'center'}}>
                <LoadingDialog/>
              </div>
            </Dialog>
            <DepositDialog/>
            <WithdrawDialog/>
           


            <Toolbar className="toolbarAkunTiket">
              <ToolbarGroup>
                <IconButton className="hide-on-med-and-up" onClick={() => this.toggleDrawer()}><IconMenus/></IconButton>

                {/* <ToolbarTitle className="show-on-small marketplace-toolbarTitle" style={{color: '#424770'}}
                          text={"Store Admin"}/> */}

                <Link onClick={this
                  .changeRoute
                  .bind(this, '/app/dashboard')} to={LINKS.DASHBOARD}>
                  <img
                    style={{
                      width: 100,
                      height: 30
                    }}
                       src={applicationIcon}/>
                </Link>

                <ToolbarSeparator className="hide-on-small-only" style={{marginLeft: 30, marginRight: 30}}/>
                {/*<IconButton className="hide-on-small-only" style={{marginRight: 10}}*/}
                            {/*onClick={() => this.toggleDrawer()}>*/}
                  {/*<IconMenus/>*/}
                {/*</IconButton>*/}
                {/* <Button className="toolbar-button-sysinfo hide-on-small-only" size="small" type="dashed"
                    style={{marginRight: (window.innerWidth < 600) ? 2 : 10}}
                    onClick={() => this.openNotification(null, "System Information", "This is your computer locale timezone", "clock-circle")}>
              <Icon type="clock-circle"/> <span className="hide-on-small-only">{moment().format('h:mm:ss A')}</span>
            </Button>

            <Button className="toolbar-button-sysinfo hide-on-small-only" size="small" type="dashed"
                    style={{marginRight: (window.innerWidth < 600) ? 2 : 10}}
                    onClick={() => this.openNotification(null, "System Information", "This is your computer locale timezone", "environment")}>
              <Icon type="environment"/><span className="hide-on-small-only">{this.user.userGeolocation.ip}</span>
            </Button> */}

                <Link onClick={this
                  .changeRoute
                  .bind(this, '/app/dashboard')} to={LINKS.DASHBOARD}><MenuItem
                  className={(this.state.selectedMenu === '/app/dashboard') ? "menuAkunItem active" : 'menuAkunItem'}><span
                  className="menuAkun">Home</span></MenuItem></Link>

                {/* <Link onClick={this
                  .changeRoute
                  .bind(this, '/app/dashboard')} to={LINKS.DASHBOARD}><MenuItem
                  className={(this.state.selectedMenu === '/app/flight') ? "menuAkunItem active" : 'menuAkunItem'}><span
                  className="menuAkun">Flight</span></MenuItem></Link>

                <Link onClick={this
                  .changeRoute
                  .bind(this, '/app/hotel')} to={LINKS.HOTEL}><MenuItem
                  className={(this.state.selectedMenu === '/app/hotel') ? "menuAkunItem active" : 'menuAkunItem'}><span
                  className="menuAkun">Hotel</span></MenuItem></Link>

                <Link onClick={this
                  .changeRoute
                  .bind(this, '/app/car')} to={LINKS.CAR}><MenuItem
                  className={(this.state.selectedMenu === '/app/car') ? "menuAkunItem active" : 'menuAkunItem'}><span
                  className="menuAkun">Car</span></MenuItem></Link>

                <Link onClick={this
                  .changeRoute
                  .bind(this, '/app/shop')} to={LINKS.ITEMS}><MenuItem
                  className={(this.state.selectedMenu === '/app/shop') ? "menuAkunItem active" : 'menuAkunItem'}><span
                  className="menuAkun">Shop</span></MenuItem></Link> */}

                {/* <Link onClick={this
                  .changeRoute
                  .bind(this, '/app/vouchers')}
                   to={LINKS.VOUCHERS}
                   ><MenuItem
                  className={(this.state.selectedMenu === '/app/vouchers') ? "menuAkunItem active" : 'menuAkunItem'}><span
                  className="menuAkun">Vouchers</span></MenuItem></Link> */}

                {/* <Button className="toolbar-button-sysinfo hide-on-small-only" size="small" type="dashed"
                    style={{marginRight: (window.innerWidth < 600) ? 2 : 10}}
                    onClick={() => this.openNotification(null, "System Information", "This is your computer locale timezone", "calendar")}>
              <Icon type="calendar"/><span className="hide-on-small-only">{this.user.userGeolocation.time_zone}</span>
            </Button>

             <Button className="toolbar-button-sysinfo hide-on-small-only" size="small" type="dashed"
                    style={{marginRight: (window.innerWidth < 600) ? 2 : 10}}
                    onClick={() => this.openNotification(null, "System Information", "This is your computer locale timezone", "home")}>
              <Icon type="home"/> <span
              className="hide-on-small-only">{this.user.userGeolocation.latitude}, {this.user.userGeolocation.longitude}</span>
            </Button>  */}

              </ToolbarGroup>
              <ToolbarGroup>
                <WalletComponent/>

                {window.location.pathname.split("/")[2] == "shop" ? (
                  <IconMenu
                  anchorOrigin={{vertical: 'bottom', horizontal: 'right'}}
                  targetOrigin={{vertical: 'top', horizontal: 'right'}}
                  onClick={() => this.notificationStore.readAll()}
                  iconButtonElement={
                    <div>
                            <IconButton className="menuAkunItem" tooltip="Cart center"
                                        tooltipPosition="bottom-center">
                              <ShoppingCart/>
                            </IconButton>
                    </div>
                  }
                >
                  <List>
                    {
                      (this.notificationStore.list.length) ?
                        this.notificationStore.list.slice(0, 5).map((item, index) => {
                          return (
                            <Link to={onNotifRowClick(item)}>
                              <ListItem
                                // leftAvatar={<Avatar src="images/ok-128.jpg" />}
                                primaryText={item.notification.title}
                                secondaryText={
                                  <div>
                                    <p>
                                      <span
                                        style={{color: darkBlack}}>{item.notification.description.substr(0, 40)}{(item.notification.description.length > 40) ? '...' : ""}</span>
                                    </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 notification yet! "/>
                    }
                    <Link to={`${LINKS.CART_DETAIL}`}>
                      <ListItem
                        primaryText={
                          <div style={{textAlign: 'center'}}>
                            <p>View All</p>
                          </div>
                        }
                      />
                    </Link>
                  </List>
                </IconMenu>
                ) : (<div/>)}


                <IconMenu
                  anchorOrigin={{vertical: 'bottom', horizontal: 'right'}}
                  targetOrigin={{vertical: 'top', horizontal: 'right'}}
                  onClick={() => this.notificationStore.readAll()}
                  iconButtonElement={
                    <div>
                      {userData.role === 'admin' ? (
                        <div>
                          {this.notificationStore.unread_notif === 0 ?
                            <IconButton className="menuAkunItem" tooltip="Notification center"
                                        tooltipPosition="bottom-center">
                              <img className="img-responsive" src="/assets/images/icon/toa.png" alt=""/>
                            </IconButton> :
                            <Badge
                              badgeContent={this.notificationStore.unread_notif}
                              primary={true}
                              badgeStyle={{top: 15, right: 12}}
                            >
                              <IconButton className="menuAkunItem" tooltip="Notification center"
                                          tooltipPosition="bottom-center">
                                <img className="img-responsive" src="/assets/images/icon/toa.png" alt=""/>
                              </IconButton>
                            </Badge>
                          }
                        </div>
                      ) : (
                        <div>
                          {this.notificationStore.unread_notif === 0 ?
                            <IconButton className="menuAkunItem" tooltip="Notification center"
                                        tooltipPosition="bottom-center">
                              <img className="img-responsive" src="/assets/images/icon/toa.png" alt=""/>
                            </IconButton> :
                            <Badge
                              badgeContent={this.notificationStore.unread_notif}
                              primary={true}
                              badgeStyle={{top: 15, right: 12}}
                            >
                              <IconButton className="menuAkunItem" tooltip="Notification center"
                                          tooltipPosition="bottom-center">
                                <img className="img-responsive" src="/assets/images/icon/toa.png" alt=""/>
                              </IconButton>
                            </Badge>
                          }
                        </div>
                      )}

                    </div>
                  }
                >
                  <List>
                    {
                      (this.notificationStore.list.length) ?
                        this.notificationStore.list.slice(0, 5).map((item, index) => {
                          return (
                            <Link to={onNotifRowClick(item)}>
                              <ListItem
                                // leftAvatar={<Avatar src="images/ok-128.jpg" />}
                                primaryText={item.notification.title}
                                secondaryText={
                                  <div>
                                    <p>
                                      <span
                                        style={{color: darkBlack}}>{item.notification.description.substr(0, 40)}{(item.notification.description.length > 40) ? '...' : ""}</span>
                                    </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 item yet! "/>
                    }
                    <Link to={`${LINKS.CART_DETAIL}`}>
                      <ListItem
                        primaryText={
                          <div style={{textAlign: 'center'}}>
                            <p>View All</p>
                          </div>
                        }
                      />
                    </Link>
                  </List>
                </IconMenu>

                <IconMenu
                  anchorOrigin={{vertical: 'bottom', horizontal: 'right'}}
                  targetOrigin={{vertical: 'top', horizontal: 'right'}}
                  iconButtonElement={
                    <IconButton style={{width: 'auto', height: 'auto'}}
                                iconStyle={{width: 35, height: 'auto', borderRadius: '45%'}}>
                      {!!this.profileStore.userProfile.photo ?
                        <img src={this.http.appendImagePath(this.profileStore.userProfile.photo)}/> : <IconUserCircle/>
                      }

                    </IconButton>
                  }
                ><List>
                  <ListItem
                    style={{padding: '0px 16px 0px', fontSize: 14}}
                    disabled={true}
                    primaryText={<span
                      style={{fontWeight: 500}}>{this.authStore.userProfile.username || 'Username'}</span>}
                    secondaryText={<p
                      style={{fontWeight: 400}}>{_.capitalize(this.authStore.userProfile.role) || 'role'}</p>}
                  />
                </List>
                  <Divider/>
                  <Link onClick={this
                    .changeRoute
                    .bind(this, '/app/transaction')} to={LINKS.TRANSACTION}> <MenuItem style={{fontSize: 14}}
                                                                                       primaryText="Transaction"/></Link>
                  <Link onClick={this
                    .changeRoute
                    .bind(this, '/app/profile')} to={LINKS.PROFILE}> <MenuItem style={{fontSize: 14}}
                                                                               primaryText="Profile"/></Link>
                  <Link onClick={this
                    .changeRoute
                    .bind(this, '/login')} to={LINKS.LOGIN}>
                    <MenuItem onClick={() => {}} style={{fontSize: 14}} primaryText="Sign out"/>
                  </Link>
                </IconMenu>
              </ToolbarGroup>
            </Toolbar>

            <div className="mainContent" style={{
              // paddingLeft: (window.innerWidth < 600) ? '0px' : '50px',
              // marginLeft: (window.innerWidth < 600) ? 'auto' : '50px',
              // marginRight: (window.innerWidth < 600) ? '0' : '50px',
            }}>
              <div className="try"/>
              <Route/>
            </div>

          </div>
        </NoPrint>
      </PrintProvider>
    );
  }
}
