import React from 'react';
import { DatePickerAndroid, TimePickerAndroid, Alert, Keyboard, ToastAndroid } from 'react-native';
import {
  Container,
  Content,
  View,
  Button,
  Icon,
  Form,
  Item,
  Label,
  Input,
  Text
} from 'native-base';
import AppHeader from './../components/Header';
import MedForm from './../components/MedForm';
import { Grid, Col } from 'react-native-easy-grid';
import { appointmentNotification } from './../Utils';
import realm from './../Database';
import moment from 'moment';

class AppointmentsScreen extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      doctor: "",
      date: null,
      time: "",
      place: "",
    }
  }

  render() {

    const { goBack } = this.props.navigation;
    const { btnAddNoti } = styles

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

        <Content>
          <MedForm titleText={"Appointments Detail"}>
            <Form>
              <Item floatingLabel>
                <Label>Doctor's name</Label>
                <Input
                  onChangeText={(text) => this.setState({ doctor: text })}
                />
              </Item>
              <Item floatingLabel>
                <Label>Date</Label>
                <Input
                  onFocus={() => { this._datePicker(), Keyboard.dismiss() }}
                  value={this.state.date == null ? "" : this._formatDate(this.state.date)}
                />
              </Item>
              <Item floatingLabel>
                <Label>Time</Label>
                <Input
                  onFocus={() => { this._timePicker(), Keyboard.dismiss() }}
                  value={this.state.time}
                />
              </Item>
              <Item floatingLabel>
                <Label>Place</Label>
                <Input
                  onChangeText={(text) => this.setState({ place: text })}
                />
              </Item>
            </Form>
          </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._addAppointment()}>
                <Text style={{ color: "#1686C4" }}>Add</Text>
              </Button>
            </Col>

          </Grid>
        </Content>
      </Container >
    )
  }

  _onResetPressed() {
    realm.write(() => {
      let allReminder = realm.objects('Appointments')
      realm.delete(allReminder)
    })
    // ToastAndroid.show("reset", ToastAndroid.SHORT)
  }

  _addAppointment() {

    if (this.state.doctor && this.state.date && this.state.time) {
      Alert.alert(
        'Confirm',
        'Are you sure to add this appointment?',
        [
          // { text: 'CANCLE', onPress: () => ToastAndroid.show("Cancled", ToastAndroid.SHORT) },
          { text: 'CANCLE', onPress: () => { } },
          {
            text: 'OK', onPress: () => {
              var id = Math.random() * 10000
              var time = this.state.time.split(':')
              var appointmentDate = moment(this.state.date).hour(time[0]).minute(time[1]).second(0).toDate()
              var msg = "แจ้งเตือนการนัดพบแพทย์\n" + "แพทย์: " + this.state.doctor + "เวลา: " + this.state.time
              appointmentNotification(msg, appointmentDate, id)

              realm.write(() => {
                realm.create('Appointments', {
                  id: id,
                  doctorName: this.state.doctor,
                  date: appointmentDate,
                  place: this.state.place,
                  timeStamp: moment().toDate()
                })
              })

              this.props.navigation.goBack(null)
            }
          },
        ],
        { cancelable: false }
      )

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


  }

  _datePicker() {
    try {
      const { action, year, month, day } = DatePickerAndroid
        .open({
          // Use `new Date()` for current date.
          // May 25 2020. Month 0 is January.
          date: moment().toDate()
        })
        .then(({ action, year, month, day }) => {
          switch (action) {
            case "dateSetAction":
              this.setState({ date: moment().year(year).month(month).date(day).toDate() })
              break;
            case "dismissedAction":
              break;
          }

        })
      if (action !== DatePickerAndroid.dismissedAction) {
        // Selected year, month (0-11), day
      }
    } catch ({ code, message }) {
      console.warn('Cannot open date picker', message);
    }

  }

  _timePicker() {
    try {
      const { action, hour, minute } = TimePickerAndroid
        .open({
          is24Hour: true, // Will display '2 PM'
        })
        .then(({ action, hour, minute }) => {
          switch (action) {
            case "timeSetAction":
              this.setState({ time: this._formatTime(hour, minute) })
              break;
            case "dismissedAction":
              break;
          }
        })

    } catch ({ code, message }) {
      console.warn('Cannot open time picker', message);
    }
  }

  _formatDate(date) {
    return moment(date).format('DD MMM YYYY')
  }

  _formatTime(hour, minute) {
    return moment(hour + ":" + minute, 'HH:mm').format('HH:mm').toString()
  }

}


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

export default AppointmentsScreen;