import * as React from 'react';
import * as ReactDOM from 'react-dom';
// import App from './App';
import registerServiceWorker from './registerServiceWorker';
import './index.css';
import 'jsplumb';
import { Machine } from 'xstate';
import * as xstate from 'xstate';
import * as utils from 'xstate/lib/graph';
import styled from 'styled-components';

const pedestrianStates = {
  initial: 'walk',
  states: {
    walk: {
      on: {
        PED_COUNTDOWN: 'wait'
      }
    },
    wait: {
      on: {
        PED_COUNTDOWN: 'stop'
      }
    },
    stop: {}
  }
};

const lightMachine = Machine({
  key: 'light',
  initial: 'green',
  states: {
    green: {
      on: {
        TIMER: 'yellow',
        POWER_OUTAGE: 'red'
      }
    },
    yellow: {
      on: {
        TIMER: 'red',
        POWER_OUTAGE: 'red'
      }
    },
    red: {
      on: {
        TIMER: 'green',
        POWER_OUTAGE: 'red'
      },
      ...pedestrianStates
    }
  }
});

const testNodes = utils.getNodes(lightMachine);
const testEdges = utils.getEdges(lightMachine);

const NodeDiv = styled.div`
  position: relative;
  width: auto;
  display: inline-block;
  border: 2px solid black;
  padding: 1rem;
`;

class App extends React.Component<{
  nodes: xstate.StateNode[];
  edges: utils.IEdge[];
}> {
  public plumb: jsPlumbInstance;

  componentDidMount() {
    const { nodes, edges } = this.props;

    console.log(nodes, edges);

    this.plumb = jsPlumb.getInstance({
      Container: '.ui-container'
    });

    this.plumb.importDefaults({
      Connector: ['Bezier', { curviness: 150 }],
      Anchors: ['TopCenter', 'BottomCenter']
    });

    edges.forEach(edge => {
      this.plumb.connect({
        source: edge.source.id,
        target: edge.target.id
      });
    });

    nodes.forEach(node => {
      this.plumb.draggable(node.id);
    });
  }

  renderNodes() {
    const { nodes } = this.props;

    return nodes.map(node => (
      <NodeDiv key={node.id} id={node.id}>
        {node.id}
      </NodeDiv>
    ));
  }

  render() {
    return (
      <div className="ui-container" style={{ height: 500 }}>
        {this.renderNodes()}
      </div>
    );
  }
}

ReactDOM.render(
  <App nodes={testNodes} edges={testEdges} />,
  document.getElementById('root') as HTMLElement
);
