import React, { Component } from 'react';
import { TouchableOpacity, Alert } from 'react-native';
import {
  Container,
  Content,
  View,
  Button,
  Icon,
  Text,
  List,
  ListItem
} from 'native-base';
import { cancleNotification } from './../Utils';
import AppHeader from './../components/Header';
import realm from './../Database/';
import moment from 'moment';

class MedicationListScreen extends Component {

  constructor(props) {
    super(props)
    this.state = {
      reminderList: []
    }
  }

  componentWillMount() {
    this._queryMedicineList()
  }

  render() {

    const { reminderListStyle, headerStyle } = styles

    const { goBack } = this.props.navigation

    return (
      <Container>
        <AppHeader
          headerText={"Medications"}
          headerLeft={
            <Button onPress={() => goBack(null)}>
              <Icon name='arrow-back' />
            </Button>
          }
          headerRight={
            <Button onPress={() => this._addReminder()}>
              <Icon name='add' />
            </Button>
          }
        />
        <Content>
          <View style={{ flex: 1, backgroundColor: 'white', height: 60 }}>
            <Text style={headerStyle}>Medication List</Text>
          </View>
          <View>
            <List dataArray={this.state.reminderList}
              renderRow={(item) =>
                <ListItem style={reminderListStyle}>
                  <View style={{ flex: 1 }}>
                    <Text>{item.medName}</Text>
                    <Text>{"Take: " + item.dose}</Text>
                    <Text>{'Time: ' + moment(item.reminderTime).format('HH:mm')}</Text>
                  </View>
                  <TouchableOpacity onPress={() => this._deleteMedicine(item)}>
                    <Icon name='more' />
                  </TouchableOpacity>
                </ListItem>
              }>
            </List>
          </View>

        </Content>
      </Container>
    )
  }

  _queryMedicineList() {

    var tmpReminder = realm.objects("Reminder")
    this.setState({ reminderList: tmpReminder })

  }

  _addReminder() {
    this.props.navigation.navigate("AddMedication")
  }

  _deleteMedicine(data) {
    Alert.alert(
      'Confirm',
      'Want to delete this medicine?',
      [
        { text: 'CANCLE', onPress: () => this.setState({ addItemVisible: true }) },
        {
          text: 'OK', onPress: () => {
            const tmpMedicine = realm.objects("Reminder").filtered('id == ' + data.id)
            cancleNotification(data.id)
            realm.write(() => {
              realm.delete(tmpMedicine)
            })
          }
        },
      ],
      { cancelable: false }
    )
  }

}


const styles = {
  reminderListStyle: {
    marginLeft: 0,
    marginRight: 0,
    marginTop: 0,
    marginBottom: 0,
    padding: 15
  }, headerStyle: {
    color: "#1686C4",
    fontSize: 20,
    paddingTop: 15,
    paddingLeft: 15
  }
}

export default MedicationListScreen;