import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
import DocumentTitle from 'react-document-title';

import Dropdown from '../shared/Dropdown';
import Icon from '../shared/Icon';
import Panel from '../shared/Panel';
import PageHeader from '../shared/PageHeader';
import ShowMoreFooter from '../shared/ShowMoreFooter';
import Spinner from '../shared/Spinner';

import AuditLogRow from './row';

const PAGE_SIZE = 30;

const EVENT_SUBJECTS = [
  { name: 'Any Subject', id: null },
  { name: 'Pipeline events', id: 'PIPELINE' },
  { name: 'Organization events', id: 'ORGANIZATION' }
];

class AuditLogIndex extends React.PureComponent {
  static propTypes = {
    organization: PropTypes.shape({
      name: PropTypes.string.isRequired,
      auditEvents: PropTypes.shape({
        edges: PropTypes.array
      }).isRequired
    }).isRequired,
    relay: PropTypes.object.isRequired
  };

  state = {
    loading: false
  };

  componentDidMount() {
    this.props.relay.setVariables({ isMounted: true });
  }

  render() {
    return (
      <DocumentTitle title={`Audit Log · ${this.props.organization.name}`}>
        <div>
          <PageHeader>
            <PageHeader.Icon>
              <Icon
                icon="eye"
                className="align-middle mr2"
                style={{ width: 40, height: 40 }}
              />
            </PageHeader.Icon>
            <PageHeader.Title>
              Audit Log
            </PageHeader.Title>
            <PageHeader.Description>
              Event log of all organization activity
            </PageHeader.Description>
          </PageHeader>

          {this.renderLogPanel()}
        </div>
      </DocumentTitle>
    );
  }

  renderLogPanel() {
    return (
      <Panel>
        <Panel.Section>
          <Dropdown width={180} ref={(_eventSubjectDropdown) => this._eventSubjectDropdown = _eventSubjectDropdown}>
            <div className="underline-dotted cursor-pointer inline-block regular dark-gray">
              {EVENT_SUBJECTS.find((subject) => subject.id === this.props.relay.variables.subjectType).name}
            </div>
            {this.renderEventSubjects()}
          </Dropdown>
        </Panel.Section>

        {this.renderEvents()}

        <ShowMoreFooter
          connection={this.props.organization.auditEvents}
          loading={this.state.loading}
          onShowMore={this.handleShowMoreAuditEvents}
        />
      </Panel>
    );
  }

  renderEvents() {
    const auditEvents = this.props.organization.auditEvents;

    if (!auditEvents) {
      return (
        <Panel.Section className="center">
          <Spinner />
        </Panel.Section>
      );
    }

    if (auditEvents.edges.length > 0) {
      return auditEvents.edges.map(({ node: auditEvent }) => (
        <AuditLogRow
          key={auditEvent.id}
          auditEvent={auditEvent}
        />
      ));
    }

    let message = 'There are no audit events';

    if (this.props.relay.variables.subjectType) {
      message = 'There are no matching audit events';
    }

    return (
      <Panel.Section>
        <div className="dark-gray">
          {message}
        </div>
      </Panel.Section>
    );
  }

  handleShowMoreAuditEvents = () => {
    this.setState({ loading: true });

    this.props.relay.setVariables(
      {
        pageSize: this.props.relay.variables.pageSize + PAGE_SIZE
      },
      (readyState) => {
        if (readyState.done) {
          this.setState({ loading: false });
        }
      }
    );
  };

  renderEventSubjects() {
    return EVENT_SUBJECTS.map((subject) => {
      return (
        <div
          key={`subject-${subject.id}`}
          className="btn block hover-bg-silver"
          onClick={() => {
            this._eventSubjectDropdown.setShowing(false);
            this.handleEventSubjectSelect(subject.id);
          }}
        >
          <span className="block">{subject.name}</span>
        </div>
      );
    });
  }

  handleEventSubjectSelect = (subjectType) => {
    this.setState({ loading: true });

    this.props.relay.setVariables(
      {
        pageSize: PAGE_SIZE,
        subjectType
      },
      (readyState) => {
        if (readyState.done) {
          this.setState({ loading: false });
        }
      }
    );
  };
}

export default Relay.createContainer(AuditLogIndex, {
  initialVariables: {
    isMounted: false,
    pageSize: PAGE_SIZE,
    subjectType: null
  },

  fragments: {
    organization: () => Relay.QL`
      fragment on Organization {
        name
        auditEvents(first: $pageSize, subject_type: $subjectType) @include (if: $isMounted) {
          edges {
            node {
              id
              ${AuditLogRow.getFragment('auditEvent')}
            }
          }
          ${ShowMoreFooter.getFragment('connection')}
        }
      }
    `
  }
});

@@ -152,51 +152,8 @@
 ';%0A%0A
-import Dropdown from '../shared/Dropdown';%0A
 impo
@@ -183,16 +183,16 @@
 /Icon';%0A
+
 import P
@@ -1747,459 +1747,8 @@
 el%3E%0A
-        %3CPanel.Section%3E%0A          %3CDropdown width=%7B180%7D ref=%7B(_eventSubjectDropdown) =%3E this._eventSubjectDropdown = _eventSubjectDropdown%7D%3E%0A            %3Cdiv className=%22underline-dotted cursor-pointer inline-block regular dark-gray%22%3E%0A              %7BEVENT_SUBJECTS.find((subject) =%3E subject.id === this.props.relay.variables.subjectType).name%7D%0A            %3C/div%3E%0A            %7Bthis.renderEventSubjects()%7D%0A          %3C/Dropdown%3E%0A        %3C/Panel.Section%3E%0A%0A
     
@@ -1773,17 +1773,16 @@
 ents()%7D%0A
-%0A
         
@@ -2433,167 +2433,8 @@
  %7D%0A%0A
-    let message = 'There are no audit events';%0A%0A    if (this.props.relay.variables.subjectType) %7B%0A      message = 'There are no matching audit events';%0A    %7D%0A%0A
     
@@ -2514,17 +2514,33 @@
     
-%7Bmessage%7D
+There are no audit events
 %0A   
@@ -2914,770 +2914,8 @@
   %7D;
-%0A%0A  renderEventSubjects() %7B%0A    return EVENT_SUBJECTS.map((subject) =%3E %7B%0A      return (%0A        %3Cdiv%0A          key=%7B%60subject-$%7Bsubject.id%7D%60%7D%0A          className=%22btn block hover-bg-silver%22%0A          onClick=%7B() =%3E %7B%0A            this._eventSubjectDropdown.setShowing(false);%0A            this.handleEventSubjectSelect(subject.id);%0A          %7D%7D%0A        %3E%0A          %3Cspan className=%22block%22%3E%7Bsubject.name%7D%3C/span%3E%0A        %3C/div%3E%0A      );%0A    %7D);%0A  %7D%0A%0A  handleEventSubjectSelect = (subjectType) =%3E %7B%0A    this.setState(%7B loading: true %7D);%0A%0A    this.props.relay.setVariables(%0A      %7B%0A        pageSize: PAGE_SIZE,%0A        subjectType%0A      %7D,%0A      (readyState) =%3E %7B%0A        if (readyState.done) %7B%0A          this.setState(%7B loading: false %7D);%0A        %7D%0A      %7D%0A    );%0A  %7D;
 %0A%7D%0A%0A
@@ -3039,31 +3039,8 @@
 SIZE
-,%0A    subjectType: null
 %0A  %7D
@@ -3137,16 +3137,16 @@
    name%0A
+
         
@@ -3177,36 +3177,8 @@
 Size
-, subject_type: $subjectType
 ) @i

Remove subject filtering