import React from 'react'
import { connect } from "react-redux"
import { Link } from 'react-router'
import RaisedButton from 'material-ui/RaisedButton';
import {orange800, lightGreen500} from 'material-ui/styles/colors';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import TextField from 'material-ui/TextField';
import Paper from 'material-ui/Paper';
import {List, ListItem} from 'material-ui/List';
import Divider from 'material-ui/Divider';
import Menu from 'material-ui/Menu';
import MenuItem from 'material-ui/MenuItem';
import IconButton from 'material-ui/IconButton';
import MenuIcon from 'material-ui/svg-icons/navigation/menu';
import ShoppingBasket from 'material-ui/svg-icons/action/shopping-basket';
import Popover from 'material-ui/Popover';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import ContentAdd from 'material-ui/svg-icons/content/add';
import Done from 'material-ui/svg-icons/action/done';
import Clear from 'material-ui/svg-icons/content/clear';
import FlatButton from 'material-ui/FlatButton';
import Dialog from 'material-ui/Dialog';
import FontIcon from 'material-ui/FontIcon';
import Checkbox from 'material-ui/Checkbox';
import Delete from 'material-ui/svg-icons/action/delete'

import { logMeIn } from '../actions/loginActions'
import { fetchVersion } from '../actions/randomActions'
import { addToList,
         removeItemFromList,
         purchasedItem,
         removeAllFromList,
         bulkAddToList } from "../actions/shoppingListsActions"
import { meFromToken, logMeOut } from '../actions/loginActions'
import { pullBasket } from '../actions/syncActions'


export const muiTheme = getMuiTheme({
  palette: {
    primary1Color: orange800,
    accent1Color: lightGreen500,
  },
});

const styles = {
  container: {
    padding:5,
  },
  paper: {
  display: "block",
  maxWidth: 800,
  padding: 15,
  marginLeft:"auto",
  marginRight:"auto",
  // textAlign: 'center',

  },
  menu: {
    display: 'inline-block',
    margin: 5,
  }
};


class ShoppingListsMenu extends React.Component {

    render(){
      return (
      <IconMenu
        iconButtonElement={
          <IconButton>
            <Menu />
          </IconButton>
        }
        targetOrigin={{horizontal: 'right', vertical: 'top'}}
        anchorOrigin={{horizontal: 'right', vertical: 'top'}}
      >


          <MenuItem primaryText="Home" />


          <MenuItem primaryText="About" />



      </IconMenu>
      )
    }

}

class ListStatus extends React.Component {



  render(){

    const {
      status,
      purchasedItem,
      primaryText,
      value,
      removeItem,
    } = this.props

    // const {status, ...listItemProps} = this.props

    if (status === "active"){
      return (
        <ListItem
          leftCheckbox={<Checkbox />}
          // rightIcon={<Trash name={value} removeItem={removeItem} />}
          rightIcon={<Delete onClick={this.props.removeItem.bind(this, value)} />}
          primaryText={primaryText}
          onChange={this.props.purchasedItem.bind(this, value, true)}
          // secondaryText="Allow notifications"
        />

      )
    }else if (status === "inactive"){
      return (
        <ListItem
          style={{
            textDecoration: "line-through"
          }}
          onChange={this.props.purchasedItem.bind(this, value, false)}
          leftCheckbox={<Checkbox defaultChecked/>}
          rightIcon={<Delete onClick={this.props.removeItem.bind(this, value)} />}
          primaryText={primaryText}
          // secondaryText="Allow notifications"
        />

      )
    }else {
      return <div />
    }
  }
}

class Trash extends React.PureComponent{
  render(){
    return(
      <FontIcon
        // style={{cursor:"pointer"}}
        key="delete"
        onClick={this.props.removeItem}
        id={this.props.name}
      >
        <Delete />
      </FontIcon>
    )
  }
}


@connect((store) => {
  return {
    //authenticated: store.login.authenticated
    authenticated: store.login.authenticated,
    shoppingLists: store.shoppingLists,
    notSynced: store.sync.notSynced
  }
})
export default class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      listName: 'default',
      itemToAdd: '',
      popupItem: '',
      open: false,
      dialogOpen: false,
      askToSync: true,
      firstPull: false,
      askToSyncDialogOpen: false
    }
    this.handleChange = this.handleChange.bind(this);
  }

  componentWillMount() {
    const listName = this.state.listName

    if (this.props.authenticated) {
      this.props.dispatch(meFromToken())
      this.props.dispatch(
        pullBasket({[listName] : this.props.shoppingLists[listName]})
      )
    }
    else if (this.props.notSynced.length > 0) {
      this.props.dispatch(
        pullBasket({[listName] : this.props.shoppingLists[listName]})
      )
    }
  }

  componentDidMount() {
    this.setState({firstPull: true})
  }

  handleChange(event) {
    const id = event.target.id
    this.setState({[id]: event.target.value});
  }

  addToList(event) {
    this.props.dispatch(addToList(this.state.listName, this.state.itemToAdd))
    document.getElementById('itemToAdd').value = ""
    document.getElementById('itemToAdd').focus()
  }

  // removeItemFromList() {
  //   this.props.dispatch(removeItemFromList(
  //     this.state.listName,
  //     this.state.popupItem
  //   ))
  //   this.setState({
  //     open: false,
  //   });
  // }

  removeItemFromList(name, event) {
    console.log(name)
    this.props.dispatch(
      removeItemFromList(this.state.listName, name)
    )
    // this.setState({
    //   open: false
    // })
  }

  removeAllFromList() {
    this.props.dispatch(removeAllFromList(this.state.listName))
    this.setState({dialogOpen: false})
  }

  // purchasedItem() {
  //   this.props.dispatch(purchasedItem(
  //     this.state.listName,
  //     this.state.popupItem
  //   ))
  //   this.setState({
  //     open: false,
  //   });
  // }

  purchasedItem(name, isChecked, event) {

    // console.log(isChecked.currentTarget.id)
    // console.log(isChecked.currentTarget)

    if (isChecked){
      this.props.dispatch(
        purchasedItem(this.state.listName, name)
      )
    }else{
      this.props.dispatch(
        addToList(this.state.listName, name)
      )
    }


    // this.setState({
    //   open: false
    // })
  }

  handleTouchTap = (event) => {
     // This prevents ghost click.
     event.preventDefault();

     this.setState({
       open: true,
       popupItem: event.currentTarget.getAttribute("value"),
       anchorEl: event.currentTarget,
     });
   };

   handleRequestClose = () => {
     this.setState({
       open: false,
     });
   };

   handleShoppingListActions = (item) => {
     this.props.dispatch(purchasedItem(this.state.listName, item))
   }

   sortItemsByStatus = (currentList) => {
     var activeList = {}
     var inactiveList = {}
     Object.keys(currentList).forEach(function(key) {
       if (currentList[key] == 'active') {
         activeList[key] = currentList[key]
       }else if (currentList[key] == 'inactive') {
         inactiveList[key] = currentList[key]
       }
     })
     return {activeList, inactiveList}
   }

  handleDialogOpen = () => {
    this.setState({dialogOpen: true});
  };

  handleDialogClose = () => {
    this.setState({dialogOpen: false});
  };

  handleSyncDialogOpen = () => {
    this.setState({askToSyncDialogOpen: true})
  }

  handleSyncDialogClose = () => {
    this.setState({askToSyncDialogOpen: false})
  }

  handleKeyPress = (e) => {

    if (e.key === 'Enter') {
      console.log(this)
      this.addToList();
    }
  }

  syncUnsyncedItems() {
    const { listName } = this.state
    var items_to_add = []
    // var names = document.getElementsByName("itemNotSynced")
    var names = document.getElementsByClassName("itemNotSynced")
    Array.prototype.forEach.call(names, function(parentItem){
      var item = parentItem.children[0]
      if (item.checked) {
        items_to_add.push(item.value)
      }
    })
    // names.forEach(function(item){
    //   if (item.checked) {
    //     items_to_add.push(item.value)
    //   }
    // })
    // alert(items_to_add)
    this.props.dispatch(bulkAddToList(listName, items_to_add))
    this.setState({askToSyncDialogOpen: false})

  }



  render() {
    const { listName } = this.state
    const { shoppingLists } = this.props
    const currentList = shoppingLists[listName]

    let ShoppingListsMenuItem = <ShoppingListsMenu />

    const { activeList, inactiveList } = this.sortItemsByStatus(currentList)

    const activeItemsInList = Object.keys(activeList).map(
      item =>
        <div key={item}>
          <ListStatus
            key={item}
            status={currentList[item]}
            primaryText={item}
            open={false}
            value={item}
            // onClick={this.handleTouchTap.bind(this)}
            purchasedItem={this.purchasedItem.bind(this)}
            removeItem={this.removeItemFromList.bind(this)}
          />
        </div>
    )

    const inactiveItemsInList = Object.keys(inactiveList).map(
      item =>
        <div key={item}>
          <ListStatus
            key={item}
            status={currentList[item]}
            primaryText={item}
            open={false}
            value={item}
            // onClick={this.handleTouchTap.bind(this)}
            purchasedItem={this.purchasedItem.bind(this)}
            removeItem={this.removeItemFromList.bind(this)}
          />
        </div>
    )

    const actions = [
      <FlatButton
        label="Cancel"
        onTouchTap={this.handleDialogClose}
      />,
      <FlatButton
        label="Yup!"
        onClick={this.removeAllFromList.bind(this)}
      />
    ]

    const syncDialogActions = [
      <FlatButton
        label="Nope"
        onClick={this.handleSyncDialogClose}
      />,
      <FlatButton
        label="Sure"
        onTouchTap={this.syncUnsyncedItems.bind(this)}
      />
    ]

    const itemsNotSynced = this.props.notSynced.map((item) =>
      <ListItem
        primaryText={item}
        key={item}
        leftCheckbox={
          <Checkbox
            defaultChecked={true}
            name="itemNotSynced"
            className="itemNotSynced"
            key={item}
            value={item}
          />
        }
      />
    )

    if (this.state.askToSync && this.props.notSynced.length > 0 && this.state.firstPull) {
      console.log(this.props.notSynced.length)
      this.setState({askToSync: false})
      this.handleSyncDialogOpen()
    }


    return (
    <div style={styles.container}>
      <MuiThemeProvider muiTheme={muiTheme}>

        <Paper style={styles.paper} zDepth={1}>

          <div style={{display:'block'}}>
            <table width="100%">
              <tbody>
                <tr>
                  <td>
                    <TextField

                      id="itemToAdd"
                      floatingLabelText="Add a new item"
                      hintText="Item"
                      onChange={this.handleChange}
                      onKeyPress={this.handleKeyPress.bind(this)}
                      fullWidth={true}
                    />
                  </td>
                  <td width="1%">
                    <FloatingActionButton
                      secondary={true}
                      mini={true}
                      onClick={this.addToList.bind(this)}
                    >
                      <ContentAdd />
                    </FloatingActionButton>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </Paper>
      </MuiThemeProvider>
      <br />
      {(Object.keys(activeList).length + Object.keys(inactiveList).length) > 0 ?
        (
          <MuiThemeProvider muiTheme={muiTheme}>
            <Paper style={styles.paper} zDepth={1}>
              <List>

                <h4 style={{textAlign:"center"}}>
                  <ShoppingBasket style={{margin:"0px 10px -5px -10px"}} />
                  The Pumpkin Basket ({Object.keys(activeList).length})
                </h4>
                <br />

                {activeItemsInList}
                {inactiveItemsInList}
                <Popover
                  open={this.state.open}
                  anchorEl={this.state.anchorEl}
                  anchorOrigin={{horizontal: 'right', vertical: 'center'}}
                  targetOrigin={{horizontal: 'right', vertical: 'center'}}
                  onRequestClose={this.handleRequestClose}
                >
                  <Menu style={styles.menu}>
                    <MenuItem
                      primaryText="Purchased"
                      onClick={this.purchasedItem.bind(this)}
                    />
                    <MenuItem
                      primaryText="Delete"
                      onClick={this.removeItemFromList.bind(this)}
                    />
                  </Menu>

                </Popover>
              </List>

              <RaisedButton
                label="All done!"
                primary={true}
                style={{display:'block'}}
                onClick={this.handleDialogOpen}
              />
              <Dialog
                actions={actions}
                modal={false}
                open={this.state.dialogOpen}
                onRequestClose={this.handleDialogClose}
              >
                Would you like to clear all the items from this list?
              </Dialog>
              <Dialog
                title="Out of sync"
                actions={syncDialogActions}
                modal={false}
                open={this.state.askToSyncDialogOpen}
                onRequestClose={this.handleSyncDialogClose}
                autoScrollBodyContent={true}
              >
                <br />
                <p>
                  Sync found these items missing from your current list. Would
                  you like to sync these items to this device?
                </p>
                <br />
                <List>
                  {itemsNotSynced}
                </List>
              </Dialog>
            </Paper>
          </MuiThemeProvider>
      ): (<div />)}

    </div>
    )
  }
}
//
// <input id="email"
//        placeholder="email"
//        onChange={this.handleChange} />
