import React, { Component } from 'react';
import { View, Text, StyleSheet, TextInput } from 'react-native';
import Button from '../../components/Button';

export default class EditAddress extends Component {
  constructor(props) {
    super(props);
    this.state = {
      addressDto: userInfo.address ?? {}
    };
  }

  componentDidMount() {
    userInfo.editAddress = false;
  }

  saveInfo() {
    const dto = this.state.addressDto
    if (!dto.street) {
      toastShort('Please input street');
      return;
    }
    if (!dto.houseNumber) {
      toastShort('Please input unit number');
      return;
    }
    if (!dto.zipCode) {
      toastShort('Please input postal code');
      return;
    }
    userInfo.address = dto;
    userInfo.addressLine = dto.houseNumber + ', ' + dto.street + ', ' + dto.zipCode
    userInfo.editAddress = true;
    goBack();
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.formView}>
          <Text style={styles.label}>Street</Text>
          <TextInput
            style={styles.formInput}
            placeholder='Street name and number'
            placeholderTextColor={textPlacehoder}
            maxLength={50}
            defaultValue={this.state.addressDto?.street}
            onChangeText={text => this.state.addressDto.street = text}
          />
        </View>
        <View style={styles.formView}>
          <Text style={styles.label}>Unit Number</Text>
          <TextInput
            style={styles.formInput}
            placeholder='Unit number'
            placeholderTextColor={textPlacehoder}
            maxLength={15}
            defaultValue={this.state.addressDto?.houseNumber}
            onChangeText={text => this.state.addressDto.houseNumber = text}
          />
        </View>
        <View style={styles.formView}>
          <Text style={styles.label}>Postal Code</Text>
          <TextInput
            style={styles.formInput}
            placeholder='Postal Code'
            placeholderTextColor={textPlacehoder}
            maxLength={10}
            defaultValue={this.state.addressDto?.zipCode}
            onChangeText={text => this.state.addressDto.zipCode = text}
          />
        </View>
        <Text style={ui.flex1}></Text>
        <View style={styles.buttonView}>
          <Button
            text='Save'
            elevation={1.5}
            onClick={() => {
              this.saveInfo();
            }}/>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white'
  },
  formView: {
    paddingTop: 16,
    paddingLeft: 16,
    paddingRight: 16,
    paddingBottom: 4
  },
  label: {
    color: '#333',
    fontSize: 14
  },
  formInput: {
    color: '#333',
    fontSize: 14,
    paddingBottom: 2,
    borderBottomColor: '#EEE',
    borderBottomWidth: 1
  },
  buttonView: {
    padding: 16,
    marginBottom: 16
  },
})