import React, { Component } from 'react';
import { DeviceEventEmitter, ToastAndroid, Alert } from 'react-native';
import { generateID } from './../Utils';
import { Grid, Col } from 'react-native-easy-grid';
import { SinglePickerMaterialDialog } from 'react-native-material-dialog';
import PushNotification from 'react-native-push-notification';
import {
  Container,
  Content,
  View,
  Button,
  Icon,
  Text,
  Form,
  Item,
  Label,
  Input,
  ListItem,
  Radio,
  Right,
  Left,
  Body,
} from 'native-base';
import AppHeader from './../components/Header';
import MedForm from '../components/MedForm';
import { connect } from 'react-redux';
import { reminderCreate } from './../actions';
import moment from 'moment';
import realm from './../Database';

PushNotification.configure({
  // (required) Called when a remote or local notification is opened or received
  onNotification: function (notification) {
    ToastAndroid.show(JSON.stringify(notification.id), ToastAndroid.LONG)

    // process the notification

  },

  // Should the initial notification be popped automatically
  // default: true
  popInitialNotification: true,

  /**
    * (optional) default: true
    * - Specified if permissions (ios) and token (android and ios) will requested or not,
    * - if not, you must call PushNotificationsHandler.requestPermissions() later
    */
  requestPermissions: true,
});

class MedicationsScreen extends Component {

  constructor(props) {
    super(props);
    this.state = {
      text: "",
      date: new Date(Date.now()).toISOString().split('T')[0],
      reminderDate: new Date(Date.now()),
      minDate: new Date(Date.now()).toISOString().split('T')[0],
      morning: false,
      afternoon: false,
      evening: false,
      night: false,
      morningTime: "",
      afternoonTime: "",
      eveningTime: "",
      nightTime: "",
      beforeMeal: true,
      afterMeal: false,
      dose: '1',
      singlePickerVisible: false,
      singlePickerSelectedItem: undefined
    };
  }

  componentWillMount() {

    PushNotification.registerNotificationActions(['Yes', 'No']);
    DeviceEventEmitter.addListener('notificationActionReceived', function (action) {
      console.log('Notification action received: ' + action);
      const info = JSON.parse(action.dataJSON);
      if (info.action == 'Yes') {
        ToastAndroid.show('Yes', ToastAndroid.SHORT)

      } else if (info.action == 'No') {
        ToastAndroid.show('No', ToastAndroid.LONG)
      }

    });

    let timePeriod = realm.objects('TimePeriod')
    var morningTime = timePeriod[0].morning
    var afternoonTime = timePeriod[0].afternoon
    var eveningTime = timePeriod[0].evening
    var nightTime = timePeriod[0].night

    this.setState({ morningTime, afternoonTime, eveningTime, nightTime })

  }

  _addReminder() {

    let reminder = ""

    if (this.state.morning === true) {
      var time = this.state.morningTime.split(':')
      reminder = this._setNotification(time[0], time[1], 1)
      this.props.reminderCreate(reminder)
    }
    if (this.state.afternoon === true) {
      var time = this.state.afternoonTime.split(':')
      reminder = this._setNotification(time[0], time[1], 2)
      this.props.reminderCreate(reminder)
    }
    if (this.state.evening === true) {
      var time = this.state.eveningTime.split(':')
      reminder = this._setNotification(time[0], time[1], 3)
      this.props.reminderCreate(reminder)
    }
    if (this.state.night === true) {
      var time = this.state.nightTime.split(':')
      reminder = this._setNotification(time[0], time[1], 4)
      this.props.reminderCreate(reminder)
    }

    this.props.navigation.goBack(null)
  }

  _setNotification(hour, minute, period) {

    var id = generateID()
    var reminderDate = moment().hour(hour).minute(minute).second(0).toDate()
    var beforeMeal = this.state.beforeMeal ? "\tก่อนอาหาร" : "\tหลังอาหาร";
    // var msg = "แจ้งเตือนกินยา\n" + "เวลา: " + hour + ":" + minute + "\nยา: " + this.state.text + beforeMeal;
    // scheduleLocalNotification(msg, reminderDate, id)

    return {
      id: id,
      medName: this.state.text,
      reminderTime: reminderDate,
      meal: beforeMeal.trim(),
      period: period,
      dose: this.state.dose
    }

  }

  render() {
    var { goBack } = this.props.navigation

    var { timeStyle, btnAddNoti } = styles;

    const dose = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

    return (
      <Container>
        <AppHeader
          headerText={'Add Reminder'}
          headerLeft={
            <Button onPress={() => goBack(null)}>
              <Icon name='arrow-back' />
            </Button>
          }
        />

        <Content>
          <MedForm titleText={"Medication Name"}>
            <Form>
              <Item floatingLabel>
                <Label>medicine or brand name</Label>
                <Input
                  onChangeText={(text) => this.setState({ text })}
                />
              </Item>
            </Form>
          </MedForm>

          <MedForm titleText={"Reminder Times"}>
            <Content>
              <ListItem onPress={() => this._onReminderTimePresses(1)}>
                <Radio selected={this.state.morning} />
                <Body>
                  <Text>Morning</Text>
                </Body>
                <Right>
                  <Text>{this.state.morningTime}</Text>
                </Right>
              </ListItem>
              <ListItem onPress={() => this._onReminderTimePresses(2)}>
                <Radio selected={this.state.afternoon} />
                <Body>
                  <Text>Afternoon</Text>
                </Body>
                <Right>
                  <Text>{this.state.afternoonTime}</Text>
                </Right>
              </ListItem>
              <ListItem onPress={() => this._onReminderTimePresses(3)}>
                <Radio selected={this.state.evening} />
                <Body>
                  <Text>Evening</Text>
                </Body>
                <Right>
                  <Text>{this.state.eveningTime}</Text>
                </Right>
              </ListItem>
              <ListItem onPress={() => this._onReminderTimePresses(4)}>
                <Radio selected={this.state.night} />
                <Body>
                  <Text>Night</Text>
                </Body>
                <Right>
                  <Text>{this.state.nightTime}</Text>
                </Right>
              </ListItem>
            </Content>
          </MedForm>

          <MedForm titleText={"Before/After Meal"}>
            <Content>
              <ListItem onPress={() => this._setBeforeAfterMeal(1)}>
                <Radio selected={this.state.beforeMeal} />
                <Body>
                  <Text>Before</Text>
                </Body>
              </ListItem>
              <ListItem onPress={() => this._setBeforeAfterMeal(2)}>
                <Radio selected={this.state.afterMeal} />
                <Body>
                  <Text>After</Text>
                </Body>
              </ListItem>
            </Content>
          </MedForm>

          <MedForm titleText={"Dose"}>
            <View style={{ padding: 15 }}>
              <Button style={{ backgroundColor: 'white' }} onPress={() => this.setState({ singlePickerVisible: true })}>
                <Text style={{ color: "#1686C4" }}>{this.state.dose}</Text>
              </Button>

              <SinglePickerMaterialDialog
                title={'Pick one element!'}
                scrolled
                items={dose.map((row, index) => ({ value: index, label: row }))}
                visible={this.state.singlePickerVisible}
                selectedItem={this.state.singlePickerSelectedItem}
                onCancel={() => this.setState({ singlePickerVisible: false })}
                onOk={result => {
                  this.setState({ singlePickerVisible: false });
                  this.setState({ dose: result.selectedItem["label"].toString() });
                }} />
            </View>

          </MedForm>

          <Grid>
            <Col>
              <Button full style={btnAddNoti} onPress={() => this._onResetPressed()}>
                <Text style={{ color: "#1686C4" }}>Reset</Text>
              </Button>
            </Col>
            <Col>
              <Button full style={btnAddNoti} onPress={() => this._addReminder()}>
                <Text style={{ color: "#1686C4" }}>Add</Text>
              </Button>
            </Col>

          </Grid>

        </Content>
      </Container>
    )
  };

  _setBeforeAfterMeal(id) {
    switch (id) {
      case 1:
        if (!this.state.beforeMeal) {
          this.setState({ beforeMeal: !this.state.beforeMeal, afterMeal: !this.state.afterMeal })
        }
        break
      case 2:
        if (!this.state.afterMeal) {
          this.setState({ afterMeal: !this.state.afterMeal, beforeMeal: !this.state.beforeMeal })
        }
        break
    }
  }

  _onResetPressed() {

    realm.write(() => {
      let allReminder = realm.objects('Reminder')
      realm.delete(allReminder)
    })

    let myReminder = realm.objects('Reminder')
  }

  _onReminderTimePresses(pos) {

    switch (pos) {
      case 1:
        this.setState({ morning: !this.state.morning })
        break
      case 2:
        this.setState({ afternoon: !this.state.afternoon })
        break
      case 3:
        this.setState({ evening: !this.state.evening })
        break
      case 4:
        this.setState({ night: !this.state.night })
        break
    }
  }

  _onMenuPressed() {
    this.props.navigation.navigate("DrawerToggle");
  }

};

const styles = {
  timeStyle: {
    flex: 1,
    padding: 15,
  },
  btnAddNoti: {
    flex: 1,
    backgroundColor: '#FFFFFF',
    marginTop: 15,
    marginBottom: 15,
    marginLeft: 20,
    marginRight: 20,
  }
}

export default connect(null, { reminderCreate })(MedicationsScreen);