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

class AppointmentsScreen extends React.Component {

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

  _addAppointment() {
    let id = generateID();
    let time = this.state.time.split(':')
    let appointment = {
      id: id,
      doctorName: this.state.doctor,
      date: moment(this.state.date).hour(time[0]).minute(time[1]).second(0).toDate(),
      place: this.state.place,
      time: moment().date()
    };
    this.props.appointmentCreate(appointment)
    this.props.navigation.goBack(null)
  }

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



  _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 connect(null, { appointmentCreate })(AppointmentsScreen);