import 'jquery-slimscroll/jquery.slimscroll.min';
import React from 'react';
import APPCONFIG from 'constants/Config';
import Badge from 'material-ui/Badge';
import NotificationsIcon from 'material-ui/svg-icons/social/notifications';
import { Card, CardActions, CardHeader, CardText } from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';
import { List, ListItem } from 'material-ui/List';
import Divider from 'material-ui/Divider';
import Subheader from 'material-ui/Subheader';
import MapsDirectionsCar from 'material-ui/svg-icons/maps/directions-car';
import ContactList from '../../routes/app/components/ContactList';
import Avatar from 'material-ui/Avatar';
import { grey400, darkBlack, lightBlack } from 'material-ui/styles/colors';
import IconButton from 'material-ui/IconButton';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import NavigationChevronRight from 'material-ui/svg-icons/navigation/more-vert';

// SocialNotificationsActive

class Notifications 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,
      notificationList: [],
    };
    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);
    }
    // }
    // const quickviewInner = this.quickview;
    // $(quickviewInner).slimscroll({
    //   height: '100%'
    // });
  }

  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) {
      notifications[n.nid] = n;
      let notificationList = []
      Object.keys(notifications).map((k) => {
        const n = notifications[k];
        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,
            };



            const iconButtonElement = (
              <IconButton
                touch={true}
                tooltip="Actions"
                tooltipPosition="bottom-left"
              >
                 <NavigationChevronRight color={grey400} />

                {/* <MoreVertIcon color={grey400} /> */}
              </IconButton>
            );

            const rightIconMenu = (
              <IconMenu iconButtonElement={iconButtonElement}>
                <MenuItem> <a href={"/#/app/member/" + n.content.payload.user.useruuid}>Member</a> </MenuItem>
                <MenuItem> <a href="/#/app/table/visits/" > Visits </a> </MenuItem>
                <MenuItem> <a href={"/#/ride/" + n.content.payload.ride_uuid + "/" + n.content.payload.user.useruuid}> Ride</a> </MenuItem>
                <MenuItem><a href={"/#/app/page/map/" + n.content.payload.ride_uuid}> Ride Details    </a> </MenuItem>
                <MenuItem> <ContactList data={rideContactList} /> </MenuItem>
              </IconMenu>
            );

            notificationList.push(
              <div>
                <ListItem
                  leftAvatar={<i className="nav-icon material-icons">directions_car</i>}
                  rightIconButton={rightIconMenu}
                  primaryText={n.content.subject}
                  secondaryText={
                    <p>
                      <span>{ride.user.name}</span><br />
                      {n.content.body}
                    </p>
                  }
                  secondaryTextLines={2}
                />
                <Divider inset={true} />
              </div>
            );
            break;
          case 'message':
            return
            notificationList.push(
              <Card id={n.id}>
                <CardHeader
                  title={n.content.subject}
                  subtitle={ride.user.name + " | " + "Time Here"}
                  avatar={<Message />}
                />
                <CardText>
                  {n.content.body}
                </CardText>
                <CardActions>
                  <ContactList data={rideContactList} />
                </CardActions>
              </Card>)
            break;
        }
      })
      this.setState(Object.assign(this.state, { notifications: notifications, totalNotifications: this.state.totalNotifications + 1, notificationList: notificationList }));

      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);
  }

  toggleCustomizer = () => {
    const $body = $('#body');
    $body.toggleClass('quickview-open-customizer');
  }

  closeCustomizer = () => {
    const $body = $('#body');
    $body.removeClass('quickview-open-customizer');
  }

  render() {
    return (
      <section
        className="quickview-wrapper customizer theme-light"
        id="quickview-customizer"
      >
        <a className="customizer-toggle" href="javascript:;" onClick={this.toggleCustomizer}>
          <Badge
            badgeStyle={{ top: 22, right: 16 }}
            badgeContent={this.state.totalNotifications}
            secondary={true}
            primary={false}
          >
            <NotificationsIcon />
          </Badge>
        </a>
        <List>
          <Subheader>Today</Subheader>
          {this.state.notificationList}
        </List>
      </section>
    );
  }
}

module.exports = Notifications;
