/*
 * This file is part of ORY Editor.
 *
 * ORY Editor is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ORY Editor is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with ORY Editor.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @license LGPL-3.0
 * @copyright 2016-2018 Aeneas Rekkas
 * @author Aeneas Rekkas <aeneas+oss@aeneas.io>
 *
 */
import * as React from 'react';
import Drawer from '@material-ui/core/Drawer';
import { connect } from 'react-redux';
import { isInsertMode, isEditMode, isLayoutMode, isResizeMode, isPreviewMode } from 'ory-editor-core/lib/selector/display';
import {
  insertMode,
  PreviousModeAction
}from 'ory-editor-core/lib/actions/display'
import { Dispatch, bindActionCreators } from 'redux';

import { createStructuredSelector } from 'reselect';
import { Editor } from 'ory-editor-core/lib';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListSubheader from '@material-ui/core/ListSubheader';
import TextField from '@material-ui/core/TextField';
import {
  LayoutPlugin,
  ContentPlugin
} from 'ory-editor-core/lib/service/plugin/classes';
import Item from './Item/index';
import Provider from '../Provider/index';
import { ProviderProps } from './../Provider/index';
import { Plugin } from 'ory-editor-core/lib/service/plugin/classes';

// Tabs 
import Paper from '@material-ui/core/Paper';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import AppBar from '@material-ui/core/AppBar';

import BottomToolbar from '../BottomToolbar';

import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
const styles = theme => ({
  root: {
    flexGrow: 1,
    backgroundColor: theme.palette.background.paper,
  },
  tabsRoot: {
    borderBottom: '1px solid #ececec',
    marginTop: 10
  },
  tabsIndicator: {
    backgroundColor: '#0290ff',
    width: '35% !important',
    margin: '0 25px'
  },
  tabRoot: {
    textTransform: 'capitalize',
    // fontWeight: 800,
    color: '#757b86',
    letterSpacing: '2.05px',
    fontSize: 14,
    '&:hover': {
      color: '#30353d',
      opacity: 1,
    },
    '&$tabSelected': {
      color: '#30353d',
    },
    '&:focus': {
      color: '#30353d',
    },
  },
  tabSelected: {},
  // typography: {
  //   padding: theme.spacing.unit * 3,
  // },

  drawerPaper: {
    width: 360,
    zindex: 'auto',
    position: 'absolute',
    height: '100%',
    borderTop: '1px solid #e4e8ea',
    zIndex: 2,
  }
});
type Props = {
  isInsertMode: boolean;
  editor: Editor;
  noPluginFoundContent: JSX.Element | string;
};

interface RawState {
  isSearching: boolean;
  searchText: string;
  tabState: Number;
}

class Raw extends React.Component<Props, RawState> {
  static defaultProps = {
    noPluginFoundContent: 'No plugins found',
  };

  input: HTMLInputElement;
  constructor(props: Props) {
    super(props);
    this.state = {
      isSearching: false,
      searchText: '',
      tabState: 0,
    };

    this.onSearch = this.onSearch.bind(this);
    this.searchFilter = this.searchFilter.bind(this);
  }

  componentDidUpdate() {
    const input = this.input;
    if (input && this.props.isInsertMode && input instanceof HTMLElement) {
      setTimeout(() => {
        const e = input.querySelector('input');
        if (e) {
          e.focus();
        }
      }, 100);
    }
    // if(!this.props.isLayoutMode)
  }

  

  onRef = component => {
    this.input = component;
  }

  onSearch: React.ChangeEventHandler<HTMLInputElement> = e => {
    const target = e.target;
    if (target instanceof HTMLInputElement) {
      this.setState({
        isSearching: target.value.length > 0,
        searchText: target.value,
      });
    }
  }

  searchFilter(plugin: Plugin) {
    return (
      plugin &&
      plugin.name &&
      plugin.name.toLowerCase().startsWith(this.state.searchText.toLowerCase())
    );
  }

  tabHandleChange = (event, value) => {
    //alert(value);
    this.setState({tabState:value});
    if(value === 0){
      this.props.insertMode();
    }
  }

  componentWillReceiveProps(nextprops){
  //   console.log('modes === ', nextprops, 'this props === ', this.props);
    if(nextprops.isEditMode  
      // && !this.props.isLayoutMode
    // && nextprops.isEditMode !== this.props.isEditMode
    ){
      this.setState({
        tabState: 1
      })
    }else if(nextprops.isLayoutMode || nextprops.isInsertMode){
      this.setState({
        tabState: 0
      })
    }
  }

  render() {
    const {
      editor: { plugins },
      classes
    } = this.props;
    const content = plugins.plugins.content.filter(this.searchFilter);
    const layout = plugins.plugins.layout.filter(this.searchFilter);

    return (
      <Drawer
        anchor="right"
        variant="persistent"
        className="ory-toolbar-drawer"
        open={true}
        // open={this.props.isInsertMode}
        classes={{ paper: classes.drawerPaper }}
      >
        {/* <Paper square> */}
          <Tabs
            value={this.state.tabState}
            // indicatorColor="primary"
            // textColor="primary"
            onChange={(e, value)=>this.tabHandleChange(e, value)}
            variant="fullWidth"
            classes={{ root: classes.tabsRoot, indicator: classes.tabsIndicator }}
            
          >
            <Tab
            classes={{ root: classes.tabRoot, selected: classes.tabSelected }}
            label="Components" />
            <div style={{
              backgroundColor: '#e8e8e8',
              width: '1px',
              margin: '10px 0'
            }} >

            </div>
            <Tab
            classes={{ root: classes.tabRoot, selected: classes.tabSelected }}
            label="Properties" />
          </Tabs>
        {/* </Paper> */}
        {/* <List subheader={<ListSubheader>Add plugin to content</ListSubheader>}>
          <ListItem>
            <TextField
              inputRef={this.onRef}
              placeholder="Search plugins"
              fullWidth={true}
              onChange={this.onSearch}
            />
          </ListItem>
          {layout.length + content.length === 0 && (
            <ListSubheader>{this.props.noPluginFoundContent}</ListSubheader>
          )}
        </List> */}
        {this.state.tabState == 0 &&
          content.length > 0 && (
            // <List
            //  subheader={<ListSubheader>Content plugins</ListSubheader>}
            // >
            <div>{
              content.map((plugin: ContentPlugin, k: Number) => {
                const initialState = plugin.createInitialState();

                return (
                  <Item
                    plugin={plugin}
                    key={k.toString()}
                    insert={{
                      content: {
                        plugin,
                        state: initialState,
                      },
                    }}
                  />
                );
              })}
              {layout.map((plugin: LayoutPlugin, k: Number) => {
                const initialState = plugin.createInitialState();
                const children = plugin.createInitialChildren();
  
                return (
                  <Item
                    plugin={plugin}
                    key={k.toString()}
                    insert={{
                      ...children,
                      layout: {
                        plugin,
                        state: initialState,
                      },
                    }}
                  />
                );
              })
            }
                  
                </div>
            // </List>
          )
          
        }
        {this.state.tabState == 1 &&
          // <BottomToolbar />

          <div 
          className='properties_tab ory-prevent-blur' 
          id="propertiesTab"
          style={{margin: '20px'}}
            
          >
          {/* <p>
            click any component to edit!
          </p> */}
           {/* <div
        style={{
          border: 'black 1px solid',
          borderRadius: '4px 4px 0 0',
          backgroundColor: 'black',
          padding: '12px 24px',
          margin: 'auto',
        }}>
        </div> */}
          </div>
        }
        {/* {layout.length > 0 && (
          <List
            subheader={<ListSubheader>Layout plugins</ListSubheader>}
          >
            
          </List>
        )} */}
      </Drawer>
    );
  }
}


const mapStateToProps = createStructuredSelector({ isInsertMode, isEditMode, isPreviewMode, isLayoutMode, isResizeMode });

const mapDispatchToProps = (
  dispatch: Dispatch<PreviousModeAction>,
  { id }: { id: string }
) =>
  bindActionCreators(
    {
      insertMode
    },
    dispatch
  );


  Raw.propTypes = {
    classes: PropTypes.object.isRequired,
  };
  
const Decorated = withStyles(styles)(connect(mapStateToProps, mapDispatchToProps)(Raw));

const Toolbar: React.SFC<ProviderProps> = props => (
  <Provider {...props}>
    <Decorated {...props} />
  </Provider>
);

export default Toolbar;