import React, { Component } from 'react'
import Message from 'material-ui/svg-icons/communication/message';
import ReactMaterialUiNotifications from 'react-materialui-notifications';
import moment from 'moment';
import { deepOrange500 } from 'material-ui/styles/colors';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import lightTheme from '../../containers/themes/lightTheme';
import darkTheme from '../../containers/themes/darkTheme';
import grayTheme from '../../containers/themes/grayTheme';

import PropTypes from 'prop-types';
import FontIcon from 'material-ui/FontIcon';
import { indigo500 } from 'material-ui/styles/colors';
import Paper from 'material-ui/Paper';
import MapsDirectionsCar from 'material-ui/svg-icons/maps/directions-car';

import ContactList from '../../routes/app/components/ContactList';

const nearbyIcon = <FontIcon className="material-icons">perm phone msg</FontIcon>;

const paperStyle = {
  height: 240,
  width: 270,
  margin: 10,
  textAlign: 'center',
  display: 'inline-block',
  position: 'relative'
};

const styles = {
  appbar: {
    textAlign: 'left'
  },
  buttonContainer: {
    display: 'flex',
    justifyContent: 'space-around'
  },
  footer: {
    marginTop: 15,
    width: 'calc(100% - 30px)',
    fontSize: 16,
    padding: 15,
    backgroundColor: '#fff'
  },
  logo: {
    width: 48
  },
  paper: {
    width: '100%',
    textAlign: 'left',
    marginBottom: 15,
    padding: 15,
    fontSize: 18
  },
  rightIcon: {
    width: 36,
    height: 36,
    fill: '#fff'
  },
  table: {
    marginTop: 15
  },
  headerStyle: {
    tableLayout: 'auto'
  },
  table1Col1: {
    width: 137
  },
  table1Col2: {
    width: 72
  },
  table1Col3: {
    width: 128
  },
  table1Col2C: {
    width: 72,
  },
  table2Col3: {
    width: 36
  }
};

export default class Notification extends React.Component {
  constructor(props) {
    super(props);

    const socketURL = process.env.NODE_ENV === 'production'
      ? 'wss://portal-api.bcbsinstitute.com/v1/notification/ws?id='
      : 'wss://portal-api.dev.bcbsinstitute.com/v1/notification/ws?id='

    this.props = props;
    this.state = {
      user: {
        useruuid: '',
        name: ''
      },
      socket_url: socketURL,
      notifications: {},
      totalNotifications: 0
    };
    this.socket = null;

    this.socketMessageListener = this.socketMessageListener.bind(this);
    this.socketOpenListener = this.socketOpenListener.bind(this);
    this.socketCloseListener = this.socketCloseListener.bind(this);
    this.socketCloseListener = this.socketCloseListener.bind(this);
  }

  componentDidMount() {
    this.setState(Object.assign(this.state, { user: this.props.user, notifications: [], totalNotifications: 0 }));
    if (this.state.user.useruuid && this.state.user.useruuid != '') {
      this.setState(Object.assign(this.state, { socket_url: this.state.socket_url + this.state.user.useruuid }));
      this.socket = new WebSocket(this.state.socket_url);

      this.socketMessageListener = this.socketMessageListener.bind(this);
      this.socketOpenListener = this.socketOpenListener.bind(this);
      this.socketCloseListener = this.socketCloseListener.bind(this);

      this.socket.addEventListener('open', this.socketOpenListener);
      this.socket.addEventListener('message', this.socketMessageListener);
      this.socket.addEventListener('close', this.socketCloseListener);
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.user.useruuid !== this.state.user.useruuid) {
      if (this.socket) {
        this.socket.close();
      }
      this.setState(Object.assign(this.state, { user: nextProps.user, notifications: [], totalNotifications: 0 }));
      if (this.state.user.useruuid && this.state.user.useruuid != '') {
        this.setState(Object.assign(this.state, { socket_url: this.state.socket_url + this.state.user.useruuid }));
        this.socket = new WebSocket(this.state.socket_url);

        this.socketMessageListener = this.socketMessageListener.bind(this);
        this.socketOpenListener = this.socketOpenListener.bind(this);
        this.socketCloseListener = this.socketCloseListener.bind(this);

        this.socket.addEventListener('open', this.socketOpenListener);
        this.socket.addEventListener('message', this.socketMessageListener);
        this.socket.addEventListener('close', this.socketCloseListener);
      }
    }
  }

  disableNotification(n) {
    n.content.type = "disable-notification";
    this.socket.send(JSON.stringify(n));
    this.setState(Object.assign(this.state, { totalNotifications: this.state.totalNotifications-- }));
  }


  socketMessageListener(event) {
    let n = JSON.parse(event.data);

    let notifications = this.state.notifications;
    if (notifications[n.nid] === null || notifications[n.nid] === undefined) {
      switch (n.content.type) {
        case 'ride':
          const ride = n.content.payload;
          const driverPhoneNumber = (ride.driver && ride.driver.phone_number) ? ride.driver.phone_number : '';

          const rideContactList = {
            driverMobile: driverPhoneNumber,
            memberMobile: ride.user.phonenumber,
            memberEmail: ride.user.email,
            schedulerEmail: ride.created_user.email,
            schedulerMobile: ride.created_user.phonenumber,
            rideID: ride.ride_uuid,
          }

          ReactMaterialUiNotifications.showNotification({
            title: n.content.subject,
            additionalText: n.content.payload.user.name,
            priority: true,
            icon: <MapsDirectionsCar />,
            // icon: <Message />,
            iconBadgeColor: indigo500,
            personalized: true,
            timestamp: moment(n.date).format('ddd, MMMM DD, hh:mm A'),
            onClick: () => { this.disableNotification(n); },
            overflowContent:
              <div>
                <div>
                  <div>
                    {n.content.body}
                    <p>
                      <a href={"/#/app/member/" + n.content.payload.user.useruuid}>Member</a>   |
                      <a href="/#/app/table/visits/" > Visits </a>   |
                      <a href={"/#/ride/" + n.content.payload.ride_uuid + "/" + n.content.payload.user.useruuid}> Ride</a>   |
                      <a href={"/#/app/page/map/" + n.content.payload.ride_uuid}> Ride Details  |  </a>

                      <ContactList data={rideContactList} />
                    </p>

                  </div>
                </div>
                <div >
                </div>
              </div>,
          });
          if (this.props.onRideUpdate) {
            this.props.onRideUpdate(n.content.payload);
          }
          break;
        case 'message':
          ReactMaterialUiNotifications.showNotification({
            title: `Message Received`,
            additionalText: n.content.payload.user.name,
            priority: true,
            icon: <Message />,
            iconBadgeColor: deepOrange500,
            personalized: true,
            avatar: '/assets/images/ic_account_circle_white_48dp_1x.png',
            timestamp: moment(n.date).format('ddd, MMMM DD, hh:mm A'),
            onClick: () => { this.disableNotification(n); },
            overflowContent:
              <div>
                <div>
                  {n.content.body}
                </div>
                <div>
                  <Paper style={paperStyle} zDepth={1} />
                </div>

              </div>
          });
          break;
      }
      notifications[n.nid] = n;
      this.setState(Object.assign(this.state, { notifications: notifications, totalNotifications: this.state.totalNotifications++ }));

      if (this.props.onNotificationUpdate) {
        this.props.onNotificationUpdate(n, this.state.totalNotifications);
      }

      this.forceUpdate();
    }
  }

  socketOpenListener(event) {
    console.log('Connected for the ID: ' + this.state.user.useruuid);
  }

  socketCloseListener(event) {
    if (this.socket) {
      console.error('Disconnected.');
    }
    this.socket = new WebSocket(this.state.socket_url);

    this.socketMessageListener = this.socketMessageListener.bind(this);
    this.socketOpenListener = this.socketOpenListener.bind(this);
    this.socketCloseListener = this.socketCloseListener.bind(this);

    this.socket.addEventListener('open', this.socketOpenListener);
    this.socket.addEventListener('message', this.socketMessageListener);
    this.socket.addEventListener('close', this.socketCloseListener);
  }

  render() {
    const { layoutBoxed, navCollapsed, navBehind, fixedHeader, sidebarWidth, theme } = this.props;
    let materialUITheme;
    switch (theme) {
      case 'gray':
        materialUITheme = grayTheme;
        break;
      case 'dark':
        materialUITheme = darkTheme;
        break;
      default:
        materialUITheme = lightTheme;
    }

    return (
      <MuiThemeProvider muiTheme={getMuiTheme(materialUITheme)}>
        <ReactMaterialUiNotifications
          desktop={false}
          transitionName={{
            leave: 'dummy',
            leaveActive: 'fadeOut',
            appear: 'dummy',
            appearActive: 'zoomInUp'
          }}
          transitionAppear={true}
          transitionLeave={true}
        />
      </MuiThemeProvider>
    );
  }
}

Notification.propTypes = {
  user: PropTypes.object.isRequired,
  onRideUpdate: PropTypes.func,
  onNotificationUpdate: PropTypes.func,
}
