import React from 'react';
import {observer, inject} from 'mobx-react';
import bind from 'bind-decorator';
import {
  Card,
  CardActions,
  CardHeader,
  CardMedia,
  CardTitle,
  AutoComplete,
  CardText,
  FlatButton,
  Divider,
  RaisedButton,
  Toolbar,
  DatePicker,
  FontIcon,
  SelectField,
  MenuItem,
  ToolbarGroup,
  FloatingActionButton,
  ToolbarSeparator,
  IconButton,
  ToolbarTitle,
  Table,
  TableBody,
  TableHeader,
  TableHeaderColumn,
  TableRow,
  TableRowColumn,
  TextField,
  Paper,
  RadioButton,
  RadioButtonGroup,
  DropDownMenu,
  Dialog,
  Tab, Tabs,
} from 'material-ui';
import {withRouter} from 'react-router';
import {BrowserRouter as Router, Route} from 'react-router-dom';
import StarBorder from 'material-ui/svg-icons/toggle/star-border';
import ContentAdd from 'material-ui/svg-icons/content/add';
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/content/delete-sweep';
import EmptyComponent from '../EmptyComponent';
import {DIALOG} from "../../stores/global_ui";
import DialogCreate from './Dialog';
import {startCase} from 'lodash'
import * as _ from 'lodash';
import '@mdi/font/css/materialdesignicons.min.css';

let DateTimeFormat = global.Intl.DateTimeFormat;

@inject('appstate')
@observer
export default class CustomMenus extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      value: 0,
      iniId:'',
      edit : false,
      mode : "create",
      defaultValue : {}
    };
    this.handleChange = this
      .handleChange
      .bind(this);
    this.defaultState = Object.assign({}, this.state);
    this.http = props.appstate.http;
    this.authStore = props.appstate.auth;
    this.uiStore = props.appstate.uiStore;
    this.globalUI = props.appstate.globalUI;
    this.customMenus = props.appstate.custom_menu;
  }

  componentDidMount() {
    this.globalUI.openLoading();
    this.customMenus.getAll().then(res=>{
      this.globalUI.closeLoading();
    }).catch(err=>{
      this.globalUI.closeLoading();
    });
  }

  deleteClicked = (id) => {
    this.setState({
      id : id,
      openedDelete: true
    });
  };

  handleOpenEdit = (data)=>{
    this.setState({
      defaultValue : data,
      mode : 'update'
    },()=>this.globalUI.showDialog(DIALOG.CUSTOM_MENU.CREATE))
  }


  handleOpenDialog = (mode,Id) => {
    this.setState({
      mode : mode,
      defaultValue : (Id == null) ? {} : {
        id : Id
      }
    },()=>this.globalUI.showDialog(DIALOG.CUSTOM_MENU.CREATE));
  };

  handleClickDelete = (id) => {
    this.customMenus.delete(id).then(res=>{
      this.customMenus.getAll();
      this.setState({
        openedDelete: false,
        openSnackbarDelete: true
      });
      this.globalUI.openSnackbar("Successful Deleted");
    }).catch(err=>{
      console.log(err);
      this.globalUI.openSnackbar("Something Goes Wrong");
    });
  };

  handleCloseDelete = () => {
    this.setState({
      openedDelete: false
    })
  };

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

  search = (event)=>{
    if(event.target.value.length == 0){
      this.customMenus.isSearching = false;
    }
    else{
      this.customMenus.isSearching = true;
      this.customMenus.search(event.target.value);
    }
  }


  render() {
    const actionsDelete = [
      <FlatButton
        label="Cancel"
        primary={true}
        onClick={this.handleCloseDelete}
      />,
      <FlatButton
        label="Delete"
        primary={true}
        onClick={() => this.handleClickDelete(this.state.id)}
      />,
    ];


    return (
                    <Card className="animated fadeIn cardLite">
                      <Toolbar className="toolbarCard" style={{backgroundColor: '#fff'}}>
                        <ToolbarGroup>
                          <SearchIcon style={{marginRight: 8, color: "#999"}}/>
                          <TextField
                            hintText="Search Menu"
                            style={{fontSize: 14}}
                            hintStyle={{fontSize: 14}}
                            underlineShow={false}
                            onChange={this.search}
                          />
                        </ToolbarGroup>
                        <ToolbarGroup className="ToolbarGroupLast">
                          <ToolbarSeparator/>
                          <RaisedButton className="ToolbarGroupLastButton" icon={<AddIcon/>} label="New Menu"
                                        primary={true} onClick={()=>this.handleOpenDialog("create",null)}/>
                        </ToolbarGroup>
                      </Toolbar>
                      <Divider/>
                      <div style={{paddingBottom: 5}}>
                          <Table selectable={false}
                                 fixedHeader={true}
                                 height={'calc(100vh - 280px)'}>
                            <TableHeader displaySelectAll={false}
                                         adjustForCheckbox={false}
                                         enableSelectAll={false}>
                              <TableRow style={{height: 38, background: '#f6f9fc'}}>
                                <TableHeaderColumn className="TableHeaderColumnAkun"
                                                   style={{height: 'auto'}}>Name</TableHeaderColumn>
                                 <TableHeaderColumn className="TableHeaderColumnAkun"
                                                   style={{height: 'auto'}}>Type</TableHeaderColumn>
                                <TableHeaderColumn className="TableHeaderColumnAkun"
                                                   style={{height: 'auto', textAlign: 'right'}}>Action</TableHeaderColumn>
                              </TableRow>
                            </TableHeader>
                            <TableBody displayRowCheckbox={false}>
                              {(!this.customMenus.isEmpty) ? (this.customMenus.isSearching ? this.customMenus.dataFiltered : this.customMenus.data).map((item, index) => {
                                  return (
                                    <TableRow key={item.id}>
                                      <TableRowColumn>
                                      <div style={{color : '#6772e5',cursor : 'pointer'}} onClick={()=>this.handleOpenEdit(item)}>
                                        {item.name}
                                      </div>
                                      </TableRowColumn>
                                      <TableRowColumn>
                                        {startCase(item.type)}
                                      </TableRowColumn>
                                      <TableRowColumn style={{textAlign: "right"}}><IconButton
                                        tooltip="Delete"
                                        className="ToolbarGroupLastButton"
                                        onClick={() => this.deleteClicked(item.id)}><DeleteIcon color="#999999"
                                                                                                   className="iconSmallButton"/></IconButton></TableRowColumn>
                                    </TableRow>
                                  );
                                }) : (<TableRow>
                                <TableRowColumn colSpan="4" style={{}}>
                                  <EmptyComponent type="empty" header="" content="There is no data in sight"/>
                                </TableRowColumn>
                              </TableRow>)
                              }
                            </TableBody>
                          </Table>
                      </div>
                      <Dialog
                        title="Warning"
                        actions={actionsDelete}
                        modal={true}
                        open={this.state.openedDelete}
                        onRequestClose={() => this.handleCloseDelete()}
                      >
                        Are you sure want to delete this?
                      </Dialog>
                      <DialogCreate mode={this.state.mode} defaultValue={this.state.defaultValue}/>
                    </Card>
    )
  }
}
