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 ImageEdit from 'material-ui/svg-icons/image/edit';
import EmptyComponent from '../EmptyComponent';
import LoadingDialog from "../LoadingDialog";
import Loader from 'react-loader-advanced';
import {appConfig} from "../../config/app";
import {Link} from 'react-router-dom';
import {LINKS} from "../../routes";
import moment from 'moment';
import {DIALOG} from "../../stores/global_ui";
import DialogCreate from './Dialog';

@inject('appstate')
@observer
export default class StoresListComponent extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      value: 0,
      edit : false,
      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.categoryStore = props.appstate.category;
    this.storeListStore = props.appstate.storeList;
  }

  componentDidMount() {
    this.globalUI.openLoading();
    this.storeListStore.getList().then(res => {
      this.globalUI.closeLoading();
    });
  }

  handleUpdateInput = (searchText) => {
    this.setState({
      searchText: searchText,
    });
  };

  handleNewRequest = () => {
    this.setState({
      searchText: '',
    });
  };

  tabsHandleChange = (value) => {
    this.setState({
      slideIndex: value,
    });
  };

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

  editData = (index)=>{

    // console.log(index);
    this.setState({
      edit : true,
      defaultValue : this.storeListStore.list[index] 
    },()=>{
      this.globalUI.showDialog(DIALOG.STORE_LIST.CREATE);
    })
  }


  handleOpenDialog = () => {
    this.setState({
      edit : false
    })
    this.globalUI.showDialog(DIALOG.STORE_LIST.CREATE);
  }

  handleClickDelete = (id) => {
    this.storeListStore.delete(id).then(res=>{
      this.setState({
        openedDelete: false,
        openSnackbarDelete: true
      });
      this.globalUI.openSnackbar("Successful Deleted Existing Store");
      
    }).catch(err=>{
      console.log(err);
      this.globalUI.openSnackbar(err.message);

    });
  }

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

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

  search = (event)=>{
    if(event.target.value.length == 0){
      this.storeListStore.isSearching = false;
    }
    else{
      this.storeListStore.isSearching = true;
      this.storeListStore.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 Store"
                            style={{fontSize: 14}}
                            hintStyle={{fontSize: 14}}
                            underlineShow={false}
                            onChange={this.search}
                          />
                        </ToolbarGroup>
                        <ToolbarGroup className="ToolbarGroupLast">
                          <ToolbarSeparator/>
                            <RaisedButton className="ToolbarGroupLastButton" icon={<AddIcon/>} label="New Store"
                                          primary={true} onClick={this.handleOpenDialog}/>
                        </ToolbarGroup>
                      </Toolbar>
                      <Divider/>
                      <div style={{paddingBottom: 5}}>
                        <Loader show={this.globalUI.loadingVisibility} message={<LoadingDialog/>}
                                messageStyle={{textAlign: 'center'}} backgroundStyle={{backgroundColor: 'rgba(255,255,255,0.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'}}>Email</TableHeaderColumn>
                                <TableHeaderColumn className="TableHeaderColumnAkun" style={{height: 'auto'}}>Status</TableHeaderColumn>
                                <TableHeaderColumn className="TableHeaderColumnAkun" style={{height: 'auto'}}>Created At</TableHeaderColumn>
                              </TableRow>
                            </TableHeader>
                            <TableBody displayRowCheckbox={false}>
                              {(this.storeListStore.list.length > 0) ? (this.storeListStore.isSearching ? this.storeListStore.filtered : this.storeListStore.list).map((item, index) => {
                                  return (
                                    <TableRow key={item.id}>
                                      <TableRowColumn>
                                        <div>
                                          <Link to={`${LINKS.STORES_LIST}/${item.id}`} key={item.id}>{item.name}</Link>
                                        </div>
                                      </TableRowColumn>
                                      <TableRowColumn>{item.user.email}</TableRowColumn>
                                      <TableRowColumn>{item.is_active ? 'Active' : "Unactive"}</TableRowColumn>
                                      <TableRowColumn>{moment(item.created_at).format('DD MMMM YYYY, HH:mm:ss')}</TableRowColumn>
                                    </TableRow>
                                  );
                                }) :
                                <TableRow>
                                  <TableRowColumn colSpan="4" style={{}}>
                                    <EmptyComponent type="empty" header="" content="There is no data in sight"/>
                                  </TableRowColumn>
                                </TableRow>
                              }
                            </TableBody>
                          </Table>
                        </Loader>
                      </div>
                      <Dialog
                        title="Warning"
                        actions={actionsDelete}
                        modal={true}
                        open={this.state.openedDelete}
                        onRequestClose={() => this.handleCloseDelete()}
                      >
                        Are you sure want to delete this data?
                      </Dialog>
                      {this.state.edit ? <DialogCreate mode="update" defaultValue={Object.assign({},this.state.defaultValue)}/> : <DialogCreate mode="create"/>}
                      
                    </Card>
    )
  }
}
