import React, {Component} from 'react';
import ReactGridLayout, {WidthProvider} from 'react-grid-layout';
import Panel from './Panel';
import {Button, Icon, Modal} from 'semantic-ui-react';
import _ from 'underscore';
import './DashboardView.css';
import * as Query from '../util/query';

export const GRID_WIDTH = 12;
export const GRID_MARGIN = 6;

function validConfigLayout(layout) {
  let requiredKeys = ['x', 'y', 'w', 'h'];
  let keys = _.keys(layout);
  return (
    _.intersection(keys, requiredKeys).length === requiredKeys.length &&
    _.union(keys, requiredKeys).length === requiredKeys.length
  );
}

const Grid = WidthProvider(ReactGridLayout);
class DashboardView extends Component {
  state = {editing: null};
  static defaultProps = {
    editMode: true,
  };

  onLayoutChange = layouts => {
    layouts.forEach(layout => {
      let i = parseInt(layout.i);
      this.props.updatePanel(i, {
        ...this.props.config[i],
        layout: {
          x: layout.x,
          y: layout.y,
          w: layout.w,
          h: layout.h,
        },
      });
    });
  };

  renderPanel(panelConfig, i, edit) {
    let query = Query.merge(this.props.pageQuery, panelConfig.query || {});
    return (
      <Panel
        histQueryKey={i}
        editMode={edit}
        noCard={edit}
        noButtons={true}
        type={panelConfig.viewType}
        size={panelConfig.size}
        sizeKey={JSON.stringify(panelConfig.layout)}
        pageQuery={this.props.pageQuery}
        panelQuery={panelConfig.query}
        query={query}
        config={panelConfig.config}
        data={this.props.data}
        updateType={newType =>
          this.props.updatePanel(i, {
            ...panelConfig,
            viewType: newType,
          })
        }
        updateSize={newSize =>
          this.props.updatePanel(i, {
            ...panelConfig,
            size: newSize,
          })
        }
        updateQuery={newQuery =>
          this.props.updatePanel(i, {...panelConfig, query: newQuery})
        }
        panelIndex={this.props.id}
        updateConfig={config =>
          this.props.updatePanel(i, {
            ...panelConfig,
            config: config,
          })
        }
        removePanel={() => this.props.removePanel(i)}
      />
    );
  }

  render() {
    const {editMode, width} = this.props;

    // Configs must have a layout key
    let panelConfigs = this.props.config.filter(
      config => config.layout && validConfigLayout(config.layout),
    );
    if (panelConfigs.length !== this.props.config.length) {
      // If we found invalid panels, update the browser state so on next save
      // we'll only save the valid set.
      this.props.updateView(panelConfigs);
    }

    return (
      <div>
        {editMode && (
          <span style={{position: 'absolute', right: 75, top: 10, zIndex: 102}}>
            <Button
              icon
              size="tiny"
              onClick={() => {
                this.props.addPanel({
                  layout: {
                    x: 0,
                    y: 0,
                    w: 6,
                    h: 2,
                  },
                  query: {strategy: 'merge'},
                });
              }}>
              <Icon name="plus" />
            </Button>
          </span>
        )}
        <Grid
          className={editMode ? 'editing' : 'display'}
          draggableCancel=".edit"
          cols={GRID_WIDTH}
          isDraggable={editMode}
          isResizable={editMode}
          margin={[GRID_MARGIN, GRID_MARGIN]}
          onLayoutChange={this.onLayoutChange}>
          {panelConfigs.map((panelConfig, i) => (
            <div key={i} className="panel" data-grid={{...panelConfig.layout}}>
              <Modal
                open={this.state.editing === i}
                dimmer="blurring"
                trigger={
                  <Icon
                    link
                    name="edit"
                    onClick={() => this.setState({editing: i})}
                  />
                }>
                <Modal.Header>Edit Panel</Modal.Header>
                <Modal.Content style={{padding: 16}}>
                  {this.renderPanel(panelConfig, i, true)}
                </Modal.Content>
                <Modal.Actions>
                  <Button
                    floated="left"
                    negative
                    icon="trash"
                    onClick={() => {
                      this.props.removePanel(i);
                      this.setState({editing: null});
                    }}
                  />
                  <Button onClick={() => this.setState({editing: null})}>
                    OK
                  </Button>
                </Modal.Actions>
              </Modal>

              {this.renderPanel(panelConfig, i, false)}
            </div>
          ))}
        </Grid>
      </div>
    );
  }
}

export default DashboardView;

@@ -3726,24 +3726,55 @@
 g.layout%7D%7D%3E%0A
+              %7BeditMode && (%0A  
             
@@ -3782,16 +3782,18 @@
  %3CModal%0A
+  
         
@@ -3852,26 +3852,27 @@
     
+  
 dimmer=
-%22blurring%22%0A
+%7Bfalse%7D%0A  
     
@@ -3915,14 +3915,18 @@
     
+ 
+ 
 %3CIcon%0A
+  
     
@@ -3966,16 +3966,18 @@
         
+  
 name=%22ed
@@ -3976,24 +3976,26 @@
 name=%22edit%22%0A
+  
             
@@ -4056,35 +4056,39 @@
                 
+  
 /%3E%0A
+  
                 
@@ -4090,16 +4090,18 @@
      %7D%3E%0A
+  
         
@@ -4148,16 +4148,18 @@
 Header%3E%0A
+  
         
@@ -4214,32 +4214,34 @@
                 
+  
 %7Bthis.renderPane
@@ -4273,32 +4273,34 @@
                 
+  
 %3C/Modal.Content%3E
@@ -4312,24 +4312,26 @@
             
+  
 %3CModal.Actio
@@ -4348,32 +4348,34 @@
             
+ 
+ 
 %3CButton%0A
             
@@ -4354,32 +4354,34 @@
         %3CButton%0A
+  
                 
@@ -4419,16 +4419,18 @@
         
+ 
+ 
 negative
@@ -4430,16 +4430,18 @@
 egative%0A
+  
         
@@ -4477,32 +4477,34 @@
                 
+ 
+ 
 onClick=%7B() =%3E %7B
@@ -4496,32 +4496,34 @@
 nClick=%7B() =%3E %7B%0A
+  
                 
@@ -4573,24 +4573,26 @@
             
+  
 this.setStat
@@ -4607,24 +4607,26 @@
 ng: null%7D);%0A
+  
             
@@ -4646,35 +4646,39 @@
                 
+  
 /%3E%0A
+  
                 
@@ -4759,11 +4759,15 @@
     
+  
 OK%0A
+  
     
@@ -4798,32 +4798,34 @@
                 
+  
 %3C/Modal.Actions%3E
@@ -4843,16 +4843,18 @@
     
+  
 %3C/Modal%3E
 %0A%0A  
@@ -4849,16 +4849,33 @@
 %3C/Modal%3E
+%0A              )%7D
 %0A%0A      

Fix run filters popup by disabling dimmer, no edit button on view page.