import React from 'react';
import ReactDOM from 'react-dom';
import QueueAnim from 'rc-queue-anim';
import Instance from '../../../../../components/Connection';
import {
  Row,
  Col,
  Grid,
  Table,
} from '@sketchpixy/rubix';
import moment from 'moment';
import Delete from 'material-ui/svg-icons/action/delete';
import IconButton from 'material-ui/IconButton';
import FlatButton from 'material-ui/FlatButton';
import Dialog from 'material-ui/Dialog';

import GoogleAddressComponent from './GoogleAddressComponent';
import ContactComponent from './ContactComponent';
import OrganizationComponent from './OrganizationComponent';
import ContactOption from '../../../components/ContactOption';

const formatTime = function (sec_num) {
  var hours = Math.floor(sec_num / 3600);
  var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
  var seconds = sec_num - (hours * 3600) - (minutes * 60);

  if (hours < 10) { hours = "0" + hours; }
  if (minutes < 10) { minutes = "0" + minutes; }
  if (seconds < 10) { seconds = "0" + seconds; }
  return hours + ':' + minutes + ':' + seconds;
}

const formatPhoneNumber = function (s) {
  var s2 = ("" + s).replace(/\D/g, '');
  var m = s2.match(/^(\d{3})(\d{3})(\d{4})$/);
  return (!m) ? null : "(" + m[1] + ") " + m[2] + "-" + m[3];
}

const Main = (props) => {
  return (
    <div className="row">
      <div className="col-xl-12">
        <Header organization={props.organization} onParentSelected={props.onParentSelected} onChildSelected={props.onChildSelected} />
      </div>
      <div className="col-xl-12">
        <ParentInfo organization={props.organization} onParentClick={props.onParentClick} />
      </div>
      <div className="col-xl-12">
        <ChildInfo organization={props.organization} onChildClick={props.onChildClick} />
      </div>
      <div className="col-xl-6">
        <ContactInfo organization={props.organization} onContactAdded={props.onContactAdded} onContactRemoved={props.onContactRemoved} />
      </div>
      <div className="col-xl-6">
        <Address organization={props.organization} onAddressAdded={props.onAddressAdded} onAddressRemoved={props.onAddressRemoved} />
      </div>
    </div>
  )
};

const ChildInfo = (props) => {
  if (props.organization.childs === null || props.organization.childs === undefined || props.organization.childs.length === 0) {
    return null
  } else {
    const handleChild = (e, p) => {
      if (props.onChildClick) {
        props.onChildClick(p);
      } else {
        console.log(p);
      }
    }

    let list = props.organization.childs.map(c => {
      let status = "Active";
      if (!c.active) {
        status = "Inactive";
      }
      if (c.blocked) {
        status = "Blocked";
      }
      if (c.suspended) {
        status = "Suspended"
      }

      return (
        <div className="row metrics" key={c.id}>
          <div className="col-xl-3 col-xs-3 col-md-3">
            <span className="metric"><a href={`/#/app/organization/${c.id}`} onTouchTap={(e) => handleChild(e, c)}>{c.name}</a></span>
          </div>
          <div className="col-xl-3 col-xs-3 col-md-3">
            <span className="metric"><a href={`/#/app/organization/${c.id}`} onTouchTap={(e) => handleChild(e, c)}>{c.type.name}</a></span>
          </div>
          <div className="col-xl-3 col-xs-3 col-md-3">
            <span className="metric"><a href={`/#/app/organization/${c.id}`} onTouchTap={(e) => handleChild(e, c)}>{status}</a></span>
          </div>
          <div className="col-xl-3 col-xs-3 col-md-3">
            <span className="metric"><a href={`/#/app/organization/${c.id}`} onTouchTap={(e) => handleChild(e, c)}>{moment(c.created).format('MM/DD/YYYY h:mm a')}</a></span>
          </div>
        </div>
      );
    })

    return (<div className="box box-default">
      <div className="box-body">
        <div className="row">
          <div className="col-xl-12 col-xs-12 col-md-12">
            <div className="box box-transparent">
              <div className="box-body">
                <div className="row metrics">
                  <div className="col-xl-12 col-xs-12 col-md-12">
                    <span className="metric">Child Organization</span>
                  </div>
                </div>
                <div className="row metrics">
                  <div className="col-xl-3 col-xs-3 col-md-3">
                    <span className="metric-info">Name</span>
                  </div>
                  <div className="col-xl-3 col-xs-3 col-md-3">
                    <span className="metric-info">Type</span>
                  </div>
                  <div className="col-xl-3 col-xs-3 col-md-3">
                    <span className="metric-info">Status</span>
                  </div>
                  <div className="col-xl-3 col-xs-3 col-md-3">
                    <span className="metric-info">Created</span>
                  </div>
                </div>
                {list}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>)
  }
}

const ParentInfo = (props) => {
  if (props.organization.parent === null || props.organization.parent === undefined) {
    return null
  } else {
    const parent = props.organization.parent;
    let status = "Active";
    if (!parent.active) {
      status = "Inactive";
    }
    if (parent.blocked) {
      status = "Blocked";
    }
    if (parent.suspended) {
      status = "Suspended"
    }

    const handleParent = (e, p) => {
      if (props.onParentClick) {
        props.onParentClick(p);
      } else {
        console.log(p);
      }
    }

    return (
      <div className="box box-default">
        <div className="box-body">
          <div className="row">
            <div className="col-xl-12 col-xs-12 col-md-12">
              <div className="box box-transparent">
                <div className="box-body">
                  <div className="row metrics">
                    <div className="col-xl-12 col-xs-12 col-md-12">
                      <span className="metric">Parent Organization</span>
                    </div>
                  </div>
                  <div className="row metrics" key={parent.id}>
                    <div className="col-xl-3 col-xs-3 col-md-3">
                      <span className="metric-info">Name</span>
                      <span className="metric"><a href={`/#/app/organization/${parent.id}`} onTouchTap={(e) => handleParent(e, parent)}>{parent.name}</a></span>
                    </div>
                    <div className="col-xl-3 col-xs-3 col-md-3">
                      <span className="metric-info">Type</span>
                      <span className="metric"><a href={`/#/app/organization/${parent.id}`} onTouchTap={(e) => handleParent(e, parent)}>{parent.type.name}</a></span>
                    </div>
                    <div className="col-xl-3 col-xs-3 col-md-3">
                      <span className="metric-info">Status</span>
                      <span className="metric"><a href={`/#/app/organization/${parent.id}`} onTouchTap={(e) => handleParent(e, parent)}>{status}</a></span>
                    </div>
                    <div className="col-xl-3 col-xs-3 col-md-3">
                      <span className="metric-info">Created</span>
                      <span className="metric"><a href={`/#/app/organization/${parent.id}`} onTouchTap={(e) => handleParent(e, parent)}>{moment(parent.created).format('MM/DD/YYYY h:mm a')}</a></span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>)
  }
}

const Address = (props) => {
  let list = [];
  let buttonStyle = {
    marginTop: -10
  }

  if (props.organization.addresses && props.organization.addresses !== null && props.organization.addresses.length > 0) {
    const handleRemoveAddress = (a) => {
      if (props.onAddressRemoved) {
        props.onAddressRemoved(a);
      }
    }

    list = props.organization.addresses.map(c => {
      return (<div className="row metrics" key={c.id}>
        <div className="col-xl-4 col-xs-4 col-md-4">
          <span className="metric">{c.name}</span>
        </div>
        <div className="col-xl-6 col-xs-6 col-md-6">
          <span className="metric">{c.address}</span>
        </div>
        <div className="col-xl-2 col-xs-2 col-md-2">
          <span className="metric">
            <IconButton onTouchTap={(e) => handleRemoveAddress(c)} style={buttonStyle}><Delete /></IconButton></span>
        </div>
      </div>);
    });
  }

  return (
    <div className="box box-default">
      <div className="box-body">
        <div className="row">
          <div className="col-xl-12 col-xs-12 col-md-12">
            <div className="box box-transparent">
              <div className="box-body">
                <div className="row metrics">
                  <div className="col-xl-9 col-xs-9 col-md-9">
                    <span className="metric">Addresses</span>
                  </div>
                  <div className="col-xl-3 col-xs-3 col-md-3">
                    <GoogleAddressComponent title={"Organization Address"} buttonValue={"Add Address"} onSelectAddress={props.onAddressAdded} />
                  </div>
                </div>

                <div className="row metrics">
                  <div className="col-xl-4 col-xs-4 col-md-4">
                    <span className="metric-info">Name</span>
                  </div>
                  <div className="col-xl-6 col-xs-6 col-md-6">
                    <span className="metric-info">Address</span>
                  </div>
                  <div className="col-xl-2 col-xs-2 col-md-2">
                    <span className="metric-info">Actions</span>
                  </div>
                </div>
                {list}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
};

const ContactInfo = (props) => {
  let list = [];
  let buttonStyle = {
    marginTop: -10
  }

  if (props.organization.contacts && props.organization.contacts !== null && props.organization.contacts.length > 0) {
    const handleRemoveContact = (c) => {
      if (props.onContactRemoved) {
        props.onContactRemoved(c);
      }
    }

    list = props.organization.contacts.map(c => {
      let contact = c.contact
      switch (c.type.key) {
        case "phone":
        case "landline":
        case "mobile":
        case "sms":
        case "fax":
          contact = contact.replace('+1', '');
          contact = formatPhoneNumber(contact);
          break;
      }

      return (<div className="row metrics" key={c.id}>
        <div className="col-xl-3 col-xs-3 col-md-3">
          <span className="metric">{c.name}</span>
        </div>
        <div className="col-xl-5 col-xs-5 col-md-5">
          <span className="metric">{contact}</span>
        </div>
        <div className="col-xl-4 col-xs-4 col-md-4">
          <span className="metric">
            <ContactOption contact={c} onContactDeleted={handleRemoveContact} />
          </span>
        </div>
      </div>);
    });
  }

  return (
    <div className="box box-default">
      <div className="box-body">
        <div className="row">
          <div className="col-xl-12 col-xs-12 col-md-12">
            <div className="box box-transparent">
              <div className="box-body">
                <div className="row metrics">
                  <div className="col-xl-9 col-xs-9 col-md-9">
                    <span className="metric">Contact Info</span>
                  </div>
                  <div className="col-xl-3 col-xs-3 col-md-3">
                    <ContactComponent title={"Organization Contact"} buttonValue={"Add Contact"} onNewContact={props.onContactAdded} showName={true} showDescription={true} />
                  </div>
                </div>

                <div className="row metrics">
                  <div className="col-xl-3 col-xs-3 col-md-3">
                    <span className="metric-info">Name</span>
                  </div>
                  <div className="col-xl-5 col-xs-5 col-md-5">
                    <span className="metric-info">Contact</span>
                  </div>
                  <div className="col-xl-4 col-xs-4 col-md-4">
                    <span className="metric-info">Actions</span>
                  </div>
                </div>
                {list}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
};

const Header = (props) => {
  let profileName = "";
  let organizationName = "";
  let organizationType = "";

  let status = "Active";
  if (!props.organization.active) {
    status = "Inactive";
  }
  if (props.organization.blocked) {
    status = "Blocked";
  }
  if (props.organization.suspended) {
    status = "Suspended"
  }

  let addParentButton = null;
  if (props.organization.parent === null) {
    addParentButton = (<div className="col-xl-2 col-xs-2 col-md-2">
      <OrganizationComponent title={"Parent Organization"} buttonValue={"Add Parent"} onSelectOrganization={props.onParentSelected} />
    </div>);
  }

  return (
    <div className="box box-default">
      <div className="box-body">
        <div className="row">
          <div className="col-xl-12 col-xs-12 col-md-12">
            <div className="box box-transparent">
              <div className="box-body">
                <div className="row metrics">

                  <div className="col-xl-4 col-xs-4 col-md-4">
                    <span className="metric-info">Name</span>
                    <span className="metric">{props.organization.name}</span>
                  </div>

                  <div className="col-xl-4 col-xs-4 col-md-4">
                    <span className="metric-info">Type</span>
                    <span className="metric">{props.organization.type.name}</span>
                  </div>

                  <div className="col-xl-4 col-xs-4 col-md-4">
                    <span className="metric-info">Status</span>
                    <span className="metric">{status}</span>
                  </div>

                  <div className="col-xl-4 col-xs-4 col-md-4">
                    <span className="metric-info">Author</span>
                    <span className="metric">{props.organization.author.name}</span>
                  </div>


                  <div className="col-xl-4 col-xs-4 col-md-4">
                    <span className="metric-info">Last Editor</span>
                    <span className="metric">{props.organization.last_editor.name}</span>
                  </div>

                  <div className="col-xl-4 col-xs-4 col-md-4">
                    <span className="metric-info">Created</span>
                    <span className="metric">{moment(props.organization.created).format('MM/DD/YYYY h:mm a')}</span>
                  </div>

                  <div className="col-xl-4 col-xs-4 col-md-4">
                    <span className="metric-info">Updated</span>
                    <span className="metric">{moment(props.organization.updated).format('MM/DD/YYYY h:mm a')}</span>
                  </div>

                </div>
                <div className="row metrics">
                  {addParentButton}
                  <div className="col-xl-2 col-xs-2 col-md-2">
                    <OrganizationComponent title={"Child Organization"} buttonValue={"Add Child"} onSelectOrganization={props.onChildSelected} searchType={"child"} />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
};

class Organization extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;

    this.getOrganization = this.getOrganization.bind(this);
    this.handleAddressAdded = this.handleAddressAdded.bind(this);
    this.handleAddressRemoved = this.handleAddressRemoved.bind(this);
    this.handleContactAdded = this.handleContactAdded.bind(this);
    this.handleContactRemoved = this.handleContactRemoved.bind(this);
    this.handleParentSelected = this.handleParentSelected.bind(this);
    this.handleChildSelected = this.handleChildSelected.bind(this);
    this.handleParentClick = this.handleParentClick.bind(this);
    this.handleChildClick = this.handleChildClick.bind(this);
  }

  state = {
    organization: {
      "id": "",
      "type": {
        "name": "",
        "key": ""
      },
      "name": "",
      "main": false,
      "created": "",
      "updated": "",
      "active": true,
      "blocked": false,
      "suspended": false,
      "author": {
        "useruuid": "",
        "name": "",
      },
      "last_editor": {
        "useruuid": "",
        "name": "",
      }
    },
    showErrorMessage : false,
    errorMessage : ''
  }

  componentDidMount() {
    const self = this;
    const orguuid = this.props.params.org_uuid;
    this.getOrganization(orguuid);
  }

  getOrganization(orgUUID) {
    const self = this;
    Instance.getRawConn().get(`/v1/nemt/organization/${orgUUID}`)
      .then(res => {
        self.setState(Object.assign(self.state, { organization: res.data }));
      })
      .catch(err => {
        if (err.response.status === 422) {
          location.href = '/#/app/table/organizations';
        } else {
          console.error(err);
        }
      });
  }

  handleAddressAdded(address) {
    const orguuid = this.props.params.org_uuid;
    const self = this;

    const addressObj = {
      "internal_id": address.id,
      "name": address.name,
      "address": address.address,
      "lat": address.lat,
      "long": address.long,
    }
    Instance.getRawConn().post(`/v1/nemt/organization/${orguuid}/address`, addressObj)
      .then(res => {
        self.setState(Object.assign(self.state, { organization: res.data }));
      })
      .catch(err => {
        if (err.response.status === 422) {
          location.href = '/#/app/table/organizations';
        } else {
          console.error(err);
        }
      });
  }

  handleAddressRemoved(address) {
    const orguuid = this.props.params.org_uuid;
    const self = this;

    Instance.getRawConn().put(`/v1/nemt/organization/${orguuid}/address`, address)
      .then(res => {
        self.setState(Object.assign(self.state, { organization: res.data }));
      })
      .catch(err => {
        if (err.response.status === 422) {
          location.href = '/#/app/table/organizations';
        } else {
          console.error(err);
        }
      });
  }

  handleContactAdded(contact) {
    const orguuid = this.props.params.org_uuid;
    const self = this;

    var contactObj = {
      "type": contact.type,
      "contact": contact.contact,
      "name": contact.name,
      "desc": contact.desc,
    }

    Instance.getRawConn().post(`/v1/nemt/organization/${orguuid}/contact`, contactObj)
      .then(res => {
        self.setState(Object.assign(self.state, { organization: res.data }));
      })
      .catch(err => {
        if (err.response.status === 422) {
          location.href = '/#/app/table/organizations';
        } else {
          console.error(err);
        }
      });
  }

  handleContactRemoved(contact) {
    const orguuid = this.props.params.org_uuid;
    const self = this;

    Instance.getRawConn().put(`/v1/nemt/organization/${orguuid}/contact`, contact)
      .then(res => {
        self.setState(Object.assign(self.state, { organization: res.data }));
      })
      .catch(err => {
        if (err.response.status === 422) {
          location.href = '/#/app/table/organizations';
        } else {
          console.error(err);
        }
      });
  }

  handleParentSelected(organization) {
    const org = organization[0];
    const orguuid = this.props.params.org_uuid;
    const self = this;

    Instance.getRawConn().post(`/v1/nemt/organization/${orguuid}/parent`, org)
      .then(res => {
        self.setState(Object.assign(self.state, { organization: res.data }));
      })
      .catch(err => {
        if (err.response.status === 422) {
          location.href = '/#/app/table/organizations';
        } else {
          console.error(err);
        }
      });
  }

  handleChildSelected(organization) {
    const org = organization[0];
    const orguuid = this.props.params.org_uuid;
    const self = this;

    Instance.getRawConn().post(`/v1/nemt/organization/${orguuid}/child`, org)
      .then(res => {
        self.setState(Object.assign(self.state, { organization: res.data }));
      })
      .catch(err => {
        let errorMessage = '';
        switch(err.response.status){
          case 403:
            errorMessage = 'Not authorized to add child organization';
            break;
          case 422:
            location.href = '/#/app/table/organizations';
            break;
          default:
            errorMessage = 'Error adding child organization';
            console.error(err);
        }
        this.setState(Object.assign(this.state, { showErrorMessage:true, errorMessage:errorMessage }));

      });
  }

  handleParentClick(organization) {
    this.getOrganization(organization.id);
  }

  handleChildClick(organization) {
    this.getOrganization(organization.id);
  }

  handleDialogDismiss(){
    this.setState(Object.assign(this.state, { showErrorMessage:false }));
  }

  render() {

    const actions = [
      <FlatButton
        label="Dismiss"
        primary={true}
        onClick={this.handleDialogDismiss.bind(this)}
      />,
    ];

    return (
      <div className="container-fluid no-breadcrumbs page-dashboard">
        <QueueAnim type="bottom" className="ui-animate">
          <Dialog
            title="Error"
            actions={actions}
            modal={false}
            open={this.state.showErrorMessage}
            onRequestClose={this.handleDialogDismiss.bind(this)}
          >
            {this.state.errorMessage}
          </Dialog>
          <Main organization={this.state.organization}
            onAddressAdded={this.handleAddressAdded} onAddressRemoved={this.handleAddressRemoved}
            onContactAdded={this.handleContactAdded} onContactRemoved={this.handleContactRemoved}
            onParentSelected={this.handleParentSelected} onChildSelected={this.handleChildSelected}
            onParentClick={this.handleParentClick} onChildClick={this.handleChildClick} />
        </QueueAnim>
      </div>)
  }
}
module.exports = Organization;
