import React, {Component} from 'react'
import {Alert, Platform, TouchableOpacity, View} from "react-native";
import Text from "../../components/Text";
import {t} from "../../utils/i18n";
import Select2 from "react-select2-native";
import IndicatorLoading from "../../components/IndicatorLoading";
import RNDateTimePicker from '@react-native-community/datetimepicker'
import DateTimePicker from 'react-native-modal-datetime-picker'
import Color from "../../color";
import Icon from "../../components/Icon";
import moment from "moment";
import {connect} from "react-redux";
import {getRepairDropdownList, getRoomPowerCondo, getRoomSelfPowerCondo, sendMoveOutData} from "../../api/UserApi";
import {Button} from "react-native-elements";
import {Fonts} from "../../utils/Fonts";
import DropDownPicker from 'react-native-dropdown-picker';
import Popup from "../../components/Popup";

const SelectionData = (props) => {
  return (
    <View style={props.viewStyle}>
      <Text style={Styles.Label}>{t(props.title)}</Text>
      <View style={Styles.SelectionBox}>
        <DropDownPicker
          style={{
            borderColor: '1px solid rgba(0, 0, 0, 0.25)',
          }}
          dropDownContainerStyle={{
            borderColor: '1px solid rgba(0, 0, 0, 0.25)',
          }}
          translation={{
            NOTHING_TO_SHOW: t('no_data')
          }}
          textStyle={{
            fontFamily: 'Prompt-Regular',
          }}
          {...props}
        />
      </View>
    </View>
  )
}

class MoveOutScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      rooms: [],
      reasons: [],
      building: '',
      floor: '',
      room_selected: '',
      reason_selected: '',
      isLoading: false,
      select_date: new Date(),
      isDateTimePickerVisible: false,
      data: {
        comment: 1,
        move_out_date: moment(new Date()).format('DD-MM-YYYY'),
        customer_id: this.props.user && this.props.user.customer_id,
      },
      disableSubmit: false,
      visibleConfirm: false,
      visibleSuccess: false,
      visibleFailed: false,
      message_error: null,
      visibleWarning: false
    }
  }

  componentDidMount() {
    this.getRoomList()
    this.getReasonList()
  }

  getRoomList = () => {
    let project_id = this.props.user && this.props.user.project_id;
    let customer_id = this.props.user && this.props.user.customer_id;
    if(project_id && customer_id){
      getRoomSelfPowerCondo()
        .then(res => {
          if(res.ok){
            let rooms = res.data.data;
            rooms = rooms.map((room) => {
              return {
                ...room,
                value: room.id,
                label: room.name
              }
            })

            this.setState({rooms})
          }
        })
    }
  }

  getReasonList = () => {
    getRepairDropdownList('move_out.reason')
      .then(res => {
        if(res.ok){
          let reasons = res.data.data;
          reasons = reasons.map((reason) => {
            return {
              ...reason,
              name: reason.name_th,
              value: reason.id,
              label: reason.name_th
              // name: eval('list.name_' + this.props.lang)
            }
          })

          this.setState({reasons})
        }
    })
  }

  setSelectedValue = (name, value) => {
    if(value != 0){
      this.setState({
        data: {
          ...this.state.data,
          [name]: value
        }
      })
    }
  }

  handleDatePicked = (e, date) => {
    if(Platform.OS === 'android') {
      this.setState({ isDateTimePickerVisible: false })
    }
    
    if((Platform.OS === 'android' && e.type === 'set' && date) || (Platform.OS === 'ios' && date)) {
      this.setState({
        select_date: date,
        data: {
          ...this.state.data,
          move_out_date: moment(date).format('DD-MM-YYYY')
        }
      })
    }
  };

  submitMoveOut = () => {
    if(moment(this.state.select_date).diff(moment(), 'months') >= 1){
      this.setState({visibleConfirm: true})
    }else {
      this.setState({visibleWarning: true})
    }
  }

  sendMoveOutData = () => {
    this.setState({
      isLoading: true,
      visibleWarning: false
    }, () => {
      let project_id = this.props.user && this.props.user.project_id;
      sendMoveOutData(project_id, this.state.data)
        .then(res => {
          if(res.ok){
            this.setState({visibleSuccess: true, visibleConfirm: false, isLoading: false})
          }else {
            this.setState({
              visibleFailed: true,
              isLoading: false,
              message_error: res.data && res.data.warning ? res.data.warning : '',
              visibleConfirm: false
            })
          }
        })
    })
  }

  setOpen = (open, key) => {
    this.setState({
      [key]: open
    })
  }

  validateField = () => {
    let data = this.state.data;
    if(!data.room_id || !data.move_out_date || !data.move_out_reason_dropdown_id) {
      return true;
    }

    return false
  }

  render() {
    let data = this.state.data;
    let isIos = Platform.OS === 'ios';
    return (
      <View style={{
        flex: 1,
        width: null,
        height: null,
        backgroundColor: '#EAEAF4',
        padding: 16
      }}>
        <View style={{flex: 0.9}}>
          <SelectionData
            items={this.state.rooms}
            title={'room2'}
            open={this.state.openRoom}
            setOpen={(open) => this.setOpen(open, 'openRoom')}
            value={data && data.room_id ? data.room_id : ''}
            setValue={(callback) => this.setSelectedValue('room_id', callback(this))}
            placeholder={t('select_room')}
            viewStyle={isIos ? {zIndex: 2} : {}}
            zIndex={2}
          />

          <View>
            <Text style={Styles.Label}>{t('move_out_date')}</Text>
            <TouchableOpacity style={Styles.DateMoveOut} onPress={() => this.setState({isDateTimePickerVisible: true})}>
              <View style={Styles.DateMoveOutPlaceholder}>
                <Text style={{fontSize: 14, color: '#000000', marginHorizontal: 10,}}>{moment(this.state.select_date).format('DD-MM-YYYY')}</Text>
              </View>
              <View>
                <Icon name="ic_calendar_alt" size={20} color="rgba(0,0,0,.25)" />
              </View>
            </TouchableOpacity>
          </View>

          <SelectionData
            items={this.state.reasons}
            title={'reason_move_out'}
            open={this.state.openReason}
            setOpen={(open) => this.setOpen(open, 'openReason')}
            value={data && data.move_out_reason_dropdown_id ? data.move_out_reason_dropdown_id : ''}
            setValue={(callback) => this.setSelectedValue('move_out_reason_dropdown_id', callback(this))}
            placeholder={t('select_reason_moveout')}
            viewStyle={isIos ? {zIndex: 1} : {}}
            zIndex={1}
          />
        </View>

        {
          !this.state.isDateTimePickerVisible &&
          <View style={{flex: 0.1, justifyContent: 'flex-end', marginBottom: 16}}>
            <Button
              buttonStyle={{
                height: 40,
                borderRadius: 5,
                justifyContent: 'center',
                alignItems: 'center',
                backgroundColor: '#145EB3'
              }}
              disabledStyle={{
                backgroundColor: 'grey'
              }}
              titleStyle={{fontWeight: 'normal', fontSize: 14, fontFamily: Fonts.PromptRegular}}
              onPress={() => {this.submitMoveOut()}}
              title={t('submit_data')}
              disabled={this.validateField()}
            >
            </Button>
          </View>
        }

        {
          this.state.isDateTimePickerVisible &&
            <View>
              {
                Platform.OS === 'ios' &&
                <View style={Styles.BtnDatePicker}>
                <Button
                  title={t('ok')}
                  color="white"
                  buttonStyle={{
                    height: 45,
                    borderRadius: 5,
                    justifyContent: 'center',
                    alignItems: 'center',
                    backgroundColor: '#2C7C0B',
                    marginHorizontal: -15
                  }}
                  titleStyle={{fontWeight: 'normal', fontSize: 16, fontFamily: Fonts.PromptRegular}}
                  onPress={() => {
                    this.setState({
                      isDateTimePickerVisible: false,
                    });
                  }}
                />
              </View>
              }
              
              <RNDateTimePicker
                value={this.state.select_date}
                onChange={this.handleDatePicked}
                mode='date'
                display='spinner'
                is24Hour={true}
                minimumDate={new Date()}
                locale={this.props.lang === 'en' ? 'en_GB' : 'th_TH'}
              />
            </View>
        }
        <IndicatorLoading loadingVisible={this.state.isLoading}/>

          <Popup
            title={t('send_confirm_data')}
            styleTitle={{textAlign: 'center', color: '#00420A'}}
            modalVisible={this.state.visibleConfirm}
            onCancel={() => this.setState({visibleConfirm: false})}
            onConfirm={() => this.sendMoveOutData()}
            styleFooter={{justifyContent: 'center', marginTop: 30}}
          />

          <Popup
            title={t('warning_move_out')}
            styleTitle={{textAlign: 'center', color: '#00420A'}}
            modalVisible={this.state.visibleWarning}
            onCancel={() => this.setState({visibleWarning: false})}
            onConfirm={() => this.sendMoveOutData()}
            styleFooter={{justifyContent: 'center', marginTop: 30}}
          />

          <Popup
            title={t('send_data_success')}
            message={t('moveout_success_message')}
            styleTitle={{color: '#00420A'}}
            modalVisible={this.state.visibleSuccess}
            onConfirm={() => {
              this.setState({
                isLoading: false
              }, () => {
                this.props.navigation.goBack()
              })
            }}
            styleConfirmBtn={{textAlign: 'right'}}
            styleFooter={{marginTop: 10}}
          />

          <Popup
            title={t('send_data_fail')}
            message={this.state.message_error ? this.state.message_error : ''}
            styleTitle={{color: '#00420A'}}
            modalVisible={this.state.visibleFailed}
            onConfirm={() => this.setState({visibleFailed: false, isLoading: false})}
            styleConfirmBtn={{textAlign: 'right'}}
            styleFooter={{marginTop: 10}}
          />
      </View>
    );
  }
}

const Styles = {
  Label: {
    marginBottom: 8,
    color: '#00420A'
  },
  Select: {
    marginBottom: 16,
    borderRadius: 5,
    backgroundColor: 'white',
    fontFamily: 'Prompt-Regular'
  },
  DateMoveOut: {
    flexDirection: 'row',
    backgroundColor: 'white',
    justifyContent: 'space-between',
    alignItems: 'center',
    borderRadius: 5,
    paddingLeft: 10,
    paddingRight: 10,
    paddingTop: 15,
    paddingBottom: 15,
    marginBottom: 16,
    border: '1px solid gray'
  },
  DateMoveOutPlaceholder: {
    flexDirection: 'row'
  },
  BtnDatePicker: {
    backgroundColor: '#00420A',
    borderRadius: 5
  },
  textBox: {
    backgroundColor: 'white',
    borderWidth: 1,
    borderColor: 'rgba(0, 0, 0, .25)',
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 5,
    color: '#00000080'
  },
  SelectionBox: {
    marginBottom: 8
  },
  Selection: {
    height: 40,
    fontFamily: 'Prompt-Regular',
    fontSize: 14,
  },
  SelectionPlaceholder: {
    fontFamily: 'Prompt-Regular',
    fontSize: 14,
    color: "#00000080"
  },
  SelectionText: {
    fontFamily: 'Prompt-Regular',
    fontSize: 14
  },
}

const mapDisPatchToProps = state => {
  return state.app
}

export default connect(mapDisPatchToProps)(MoveOutScreen)
