/** Pure component for each My Event Item **/
import firebase from 'firebase';
import React from 'react';
import { Dimensions, Image, Text, TouchableOpacity, View } from 'react-native';
import { Card, Icon } from 'react-native-elements';
import { GOING, INTERESTED } from '../../components/AttendeeStatusTypes';
import colors from '../../config/colors.json';
import { strings } from '../../locales/i18n';

const TEMP_IMAGE = require('../../../assets/tagfer_brand_and_logo_512.png');

const SCREEN_WIDTH = Dimensions.get('window').width;

let attendeesResult = {};
let attendees = [];
let interested = [];

class MyEventItem extends React.PureComponent {
  /**
  * Component Will Mount
  **/
  async componentWillMount() {
    attendeesResult = await firebase.database().ref(`/eventAttendees/${this.props.item.uid}`).once('value');
    attendeesResult = JSON.parse(JSON.stringify(attendeesResult));

    if (attendeesResult === null || (Object.keys(attendeesResult).length === 0 && attendeesResult.constructor === Object)) {
      return;
    }
    // If there are attendees we need to force a rerender since it doesn't happen on a pure component
    this.forceUpdate();
  }

  /**
  * Renders the main image for an event
  **/
  renderEventImage(item) {
    if (item.eventMainImg) {
      return (
        <Image
          source={{ uri: item.eventMainImg }}
          style={styles.eventImageStyle}
        />
      );
    }
    return (
      <Image
        source={TEMP_IMAGE}
        style={styles.eventImageStyle}
      />
    );
  }

  /**
  * Renders attendees avatars on each event
  **/
  renderEventAttendees() {
    if (attendeesResult === null || (Object.keys(attendeesResult).length === 0 && attendeesResult.constructor === Object)) {
      return <Text>0 </Text>;
    }

    attendees = [];
    interested = [];

    for (const property in attendeesResult) {
      if (attendeesResult[property].status === GOING) {
        attendees.push(attendeesResult[property]);
      }
      if (attendeesResult[property].status === INTERESTED) {
        interested.push(attendeesResult[property]);
      }
    }

    if (attendees.length === 0) {
      return <Text>0 </Text>;
    }

    return attendees.map((attendee) => {
      if (attendee.profile.profileAvatarImg) {
        return (
          <Image
            key={attendee.uid}
            source={{ uri: attendee.profile.profileAvatarImg }}
            style={styles.avatarImageStyle}
          />
        );
      }
      return (
        <Icon
          key={attendee.uid}
          name='account-circle'
          size={35}
          color={colors.lightTeal}
          containerStyle={{ marginBottom: 5 }}
        />
      );
    });
  }

  /**
  * Render method
  **/
  render() {
    const item = this.props.item;

    return (
      <Card containerStyle={{ padding: 0, marginHorizontal: 5 }}>
        <TouchableOpacity
          style={styles.eventContainer}
          onPress={() => this.props.navigation.navigate('eventEditScreen', item)}
        >
          {this.renderEventImage(item)}

          <View style={{ width: SCREEN_WIDTH * 0.5 }}>
            <Text style={styles.eventTitleStyle}>{item.eventName}</Text>
            <Text style={styles.eventMiddleText}>{item.startDate} | {item.startTime} {item.endTime} {item.eventTimeZone}</Text>
            <Text style={styles.eventMiddleText}>{item.location}</Text>
            <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center' }}>
              {this.renderEventAttendees(item)}
              <Text style={styles.eventSmallText}>{strings('event.homeScreen.areGoing_label')}</Text>
            </View>
          </View>
        </TouchableOpacity>

        <View>
          <Text style={styles.attendeeCountInfoTextStyle}>
            <Text style={styles.attendeesTextStyle}>{attendees.length} {strings('event.homeScreen.attendees_label')}</Text>
            <Text style={styles.interestedTextStyle}> | {interested.length} {strings('event.homeScreen.interested_label')}</Text>
          </Text>
        </View>

        <View style={styles.eventActionButtonsContainer}>
          <View style={{ flex: 1 }}>
            <TouchableOpacity style={{ flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginVertical: 10 }}>
              <Text style={styles.shareButtonStyle}>{strings('event.homeScreen.options_button')}</Text>
              <Icon
                name={'chevron-down'}
                type="material-community"
                size={20}
                color={colors.buttonBlue}
                containerStyle={styles.iconStyle}
              />
            </TouchableOpacity>
          </View>

          <TouchableOpacity style={styles.shareEventContainer}>
            <Icon
              name={'action-redo'}
              type="simple-line-icon"
              size={30}
              color={colors.buttonBlue}
              containerStyle={styles.iconStyle}
            />
          </TouchableOpacity>
        </View>

        <View style={{ marginVertical: 5, borderTopWidth: 1, borderColor: colors.lightGrey }}>
          <Text style={styles.attendeeCountInfoTextStyle}>
            <Text style={styles.interestedTextStyle}>{item.confirmedMeetingsCount} {strings('event.homeScreen.confirmed_label')} | </Text>
            <Text style={styles.attendeesTextStyle}>{item.newRequestsCount} {strings('event.homeScreen.requests_label')}</Text>
          </Text>
        </View>
      </Card>
    );
  }
}

const styles = {
  eventContainer: {
    flex: 1,
    flexDirection: 'row',
    width: '100%'
  },
  eventImageStyle: {
    width: SCREEN_WIDTH / 3,
    height: '100%',
    marginRight: 5,
    resizeMode: 'contain'
  },
  eventTitleStyle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginVertical: 5
  },
  eventMiddleText: {
    fontSize: 15,
    marginBottom: 5
  },
  eventSmallText: {
    fontSize: 12
  },
  eventActionButtonsContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    borderTopWidth: 1,
    borderColor: colors.lightGrey,
  },
  shareEventContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    borderLeftWidth: 1,
    borderColor: colors.lightGrey
  },
  iconStyle: {
    marginLeft: 20,
    marginRight: 5,
  },
  attendeeCountInfoTextStyle: {
    flex: 1,
    justifyContent: 'center',
    alignSelf: 'center',
    marginVertical: 5
  },
  attendeesTextStyle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: colors.darkBlue
  },
  interestedTextStyle: {
    fontSize: 14,
    color: colors.darkBlue
  },
  shareButtonStyle: {
    fontSize: 18
  },
  avatarImageStyle: {
    width: 30,
    height: 30,
    borderRadius: 15,
    marginBottom: 5,
    marginRight: 5
  }
};

export default MyEventItem;
