import React, { Component } from 'react';
import { DeviceEventEmitter, ToastAndroid, Alert } from 'react-native';
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 DatePicker from 'react-native-datepicker';
import AppHeader from './../components/Header';
import MedForm from '../components/MedForm';
import { formatDate, scheduleLocalNotification } from './../Utils';
import moment from 'moment'
import realm from './../Database'
import { Grid, Col } from 'react-native-easy-grid';

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() {
    super();
    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,
    };
  }

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

    // ToastAndroid.show(morningTime + afternoonTime + eveningTime + nightTime, ToastAndroid.SHORT)

  }

  render() {

    var { timeStyle, btnAddNoti } = styles;

    return (
      <Container>
        <AppHeader
          headerText={'Medications'}
          headerLeft={
            <Button onPress={this._onMenuPressed.bind(this)}>
              <Icon name='menu' />
            </Button>
          }
        />

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

          <MedForm titleText={"Reminder Time"}>
            <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={"Schedule"}>

            <Text style={timeStyle}>Start date : {formatDate(new Date(Date.now()))}</Text>
            {/* <DatePicker
              style={timeStyle}
              date={new Date(this.state.date).toISOString().split('T')[0]}
              mode="date"
              placeholder="placeholder"
              format="YYYY-MM-DD"
              minDate={this.state.minDate}
              confirmBtnText="Confirm"
              cancelBtnText="Cancel"
              onDateChange={(date) => { this.setState({ date: date }); }}
            /> */}
          </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._onAddNotificationPressed()}>
                <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
    }
  }

  _onAddNotificationPressed() {

    if (this.state.text && this.state.morning || this.state.afternoon || this.state.evening || this.state.night) {


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

      Alert.alert(
        'Successful',
        '',
        [
          { text: 'OK', onPress: () => ToastAndroid.show("Successful", ToastAndroid.SHORT) },
        ],
        { cancelable: false }
      )

    } else {
      Alert.alert(
        'Please enter medine name / Select reminder time',
        '',
        [
          { text: 'OK', onPress: () => ToastAndroid.show("Please enter medine name / Select reminder time", ToastAndroid.SHORT) },
        ],
        { cancelable: false }
      )

    }
  }

  _setNotification(hour, minute, period) {

    var id = Math.random() * 10000
    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)

    realm.write(() => {
      realm.create('Reminder', {
        id: id,
        medName: this.state.text,
        reminderTime: reminderDate,
        meal: beforeMeal.trim(),
        period: period
      })
    })
  }


  _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 MedicationsScreen;