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

const SelectionData = (props) => {
  return (
    <View style={[Styles.mbt16, props.viewStyle]}>
      <Text style={Styles.Label}>{t(props.title)}</Text>
      <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>
  )
}

class RepairIndex extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {
        // repair_list: [
        //   {name: '', material: '', value: 0}
        // ],
        // maintenanceList: [],
        work_date: moment(new Date()).format('DD-MM-YYYY'),
        details: ''
      },
      titles: [],
      rooms: [],
      repair_types: [],
      period: [
        {value: 1, label: t('am')},
        {value: 2, label: t('pm')}
      ],
      list: [
         {id: 1, value: 1, label: '1', materials: '1', service_value: '100'},
        {id: 2, value: 2, label: '2', materials: '2', service_value: '200'},
        {id: 3, value: 3, label: '3', materials: '3', service_value: '300'}
      ],
      material: [
        {value: 1, label: '1'},
        {value: 2, label: '2'},
        {value: 3, label: '3'}
      ],
      isLoading: false,
      select_date: new Date(),
      select_time: new Date(),
      visibleDate: false,
      visibleTime: false,
      disableSubmit: true,
      summary: 0,
      visibleConfirm: false,
      visibleSuccess: false,
      visibleFailed: false,
      message_error: null
    }
  }

  componentDidMount() {
    this.getRepairTitle();
    this.getRoomList();
    this.getRepairType();
    this.getRepairList();
  }

  validateData() {
    let data = this.state.data;
    if(data.header_dropdown_id
      && data.room_id
      // && data.group_dropdown_id
      // && data.details
      && data.work_date
      && data.work_time
      // && data.maintenanceList.length > 0
    ){
      this.setState({
        disableSubmit: false
      })
    }
  }

  getRepairTitle = () => {
    getRepairDropdownList('maintenance.header')
      .then(res => {
        if(res.ok){
          this.mapOptions('titles', res.data.data)
        }
    })
  }

  getRepairType = () => {
    getRepairDropdownList('material.type')
      .then(res => {
        if(res.ok){
          this.mapOptions('repair_types', res.data.data)
        }
    })
  }

  getRepairList = () => {
    let project_id = this.props.user && this.props.user.project_id;
    getRepairListPowerCondo(project_id)
      .then(res => {
        if(res.ok){
          this.mapOptions('list', res.data.data)
        }
      })
  }

  mapOptions = (name, lists) => {
    lists = lists.map((list) => {
      return {
        ...list,
        value: list.id,
        label: list.name_th
        // name: list.name_th
        // name: eval('list.name_' + this.props.lang)
      }
    })

    this.setState({
      [name]: lists
    })
  }

  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){
      getRoomPowerCondo(project_id, customer_id)
        .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})
          }
        })
    }
  }

  setRepairList1 = (value, index) => {
    let repair_list = this.state.data.repair_list;
    let item = this.state.list.filter((l) => l.id === value)
    if(item.length > 0){
      item = item[0]
    }
    repair_list[index] = {
      id: value,
      name: item.label ? item.label : '',
      material: item.materials ? item.materials : '',
      value: item.service_value
    }

    let maintenanceList = this.state.data.maintenanceList;
    maintenanceList.push({id: value})

    this.setState({
      data : {
        ...this.state.data,
        repair_list,
        maintenanceList
      }
    }, () => {
      this.validateData()
      this.serviceSummary()
    })
  }

  serviceSummary = () => {
    let data = this.state.data;
    if(data.repair_list.length > 0){
      let summary = 0;
      data.repair_list.map((list) => {
        summary += parseFloat(list.value);
      })

      this.setState({summary})
    }
  }

  setMaterialRepairList = (value, index) => {
    let repair_list = this.state.data.repair_list;
    repair_list[index] = {
      ...repair_list[index],
      material: value,
    }

    this.setState({
      data : {
        ...this.state.data,
        repair_list
      }
    }, () => {
      this.validateData()
    })
  }

  removeRepairList = (index) => {
    this.state.data.repair_list.splice(index, 1)
    this.state.data.maintenanceList.splice(index, 1)
    this.forceUpdate()
    this.serviceSummary()
  }

  addRepairList = () => {
    let repair_list = this.state.data.repair_list;
    repair_list.push({name: '', material: ''})
    this.setState({
      data: {
        ...this.state.data,
        repair_list
      }
    }, () => {
      this.validateData()
    })
  }

  submitRepair = () => {
    this.setState({visibleConfirm: true})
  }

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

  handleDatePicked = (e, date) => {
    if(Platform.OS === 'android') {
      this.setState({ visibleDate: false })
    }

    if((Platform.OS === 'android' && e.type === 'set' && date) || (Platform.OS === 'ios' && date)) {
      this.setState({
        select_date: date
      })
      this.setRepairData(moment(date).format('DD-MM-YYYY'), 'work_date')
    }
  }

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

  setRepairData = (value, name) => {
    this.setState({
      data: {
        ...this.state.data,
        [name]: value
      }
    }, () => {
      let item = this.state.rooms.filter((room) => room.id === this.state.data.room_id);
      if(item.length > 0){
        item = item[0];
        this.setState({
          data: {
            ...this.state.data,
            building_id: item.building_id
          }
        })
      }
      this.validateData()
    })
  }

  render() {
    let data = this.state.data;
    let isIos = Platform.OS === 'ios';
    return (
      <View style={{
        flex: 1,
        width: null,
        height: null,
        backgroundColor: '#EAEAF4',
        padding: 16,
      }}>
        <ScrollView>
          <SelectionData
            items={this.state.titles}
            title={'title'}
            open={this.state.openTitle}
            setOpen={(open) => this.setOpen(open, 'openTitle')}
            value={data && data.header_dropdown_id ? data.header_dropdown_id : ''}
            setValue={(callback) => this.setRepairData(callback(this), 'header_dropdown_id')}
            placeholder={t('select_title')}
            viewStyle={isIos ? {zIndex: 5} : {}}
            zIndex={5}
          />

            <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.setRepairData(callback(this), 'room_id')}
              placeholder={t('select_room')}
              viewStyle={isIos ? {zIndex: 4} : {}}
              zIndex={4}
            />

            {/*<SelectionData
            items={this.state.repair_types}
            title={'repair_type'}
            open={this.state.openRoomType}
            setOpen={(open) => this.setOpen(open, 'openRoomType')}
            value={data && data.group_dropdown_id ? data.group_dropdown_id : ''}
            setValue={(callback) => this.setRepairData(callback(this), 'group_dropdown_id')}
            placeholder={t('select_repair_type')}
            viewStyle={isIos ? {zIndex: 3} : {}}
            zIndex={3}
          />*/}

            <View style={Styles.mbt16}>
              <Text style={Styles.Label}>{t('repair_detail')}</Text>
              <View style={Styles.textAreaBox}>
                <TextInput
                  placeholder={t('detail')}
                  style={Styles.textArea}
                  onChangeText={text => this.setRepairData(text, 'details')}
                  value={data && data.details ? data.details : ''}
                  multiline={true}
                  numberOfLines={4}
                  textAlignVertical={'top'}
                />
              </View>
            </View>

            <View style={Styles.mbt16}>
              <Text style={Styles.Label}>{t('repair_date')}</Text>
              <View style={{flex: 1}}>
                <TouchableOpacity style={Styles.DateComponent} onPress={() => this.setState({visibleDate: true})}>
                  <View style={Styles.DatePlaceholder}>
                    <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>
            </View>

            <SelectionData
              items={this.state.period}
              title={'period'}
              open={this.state.openRepairType}
              setOpen={(open) => this.setOpen(open, 'openRepairType')}
              value={data && data.work_time ? data.work_time : ''}
              setValue={(callback) => this.setRepairData(callback(this), 'work_time')}
              placeholder={t('period')}
              viewStyle={isIos ? {zIndex: 3} : {paddingBottom: 100}}
              zIndex={3}
            />

            {/*{
            data.repair_list.map((repair, index) =>
              <View style={[Styles.RepairListContainer, Styles.mbt16]} key={'repair_list' + index}>
                <SelectionData
                  items={this.state.list}
                  title={'list_name'}
                  open={this.state[`openRepairList${index}`]}
                  setOpen={(open) => this.setOpen(open, `openRepairList${index}`)}
                  value={repair && repair.id ? repair.id : ''}
                  setValue={(callback) => this.setRepairList1(callback(this), index)}
                  placeholder={t('list_name')}
                  viewStyle={isIos ? {zIndex: data.repair_list.length - index} : {}}
                  zIndex={data.repair_list.length - index}
                />

                <View style={Styles.mbt16}>
                  <Text style={Styles.Label}>{t('material_name')}</Text>
                  <Text style={Styles.textMaterial}>
                    {repair && repair.material ? repair.material : t('material_name')}
                  </Text>
                </View>

                <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
                  <Text>{t('charge')}</Text>
                  <Text>{repair.value ? repair.value : 0} {t('baht')}</Text>
                </View>

                {
                  index > 0 &&
                  <TouchableOpacity onPress={() => this.removeRepairList(index)}>
                    <Text style={{textAlign: 'center', color: '#FF2D55'}}>{t('delete_row')}</Text>
                  </TouchableOpacity>
                }

              </View>
            )
          }*/}

            {/*<TouchableOpacity onPress={() => this.addRepairList()}>
            <View style={[Styles.BtnAddList, Styles.mbt16]}>
              <Text style={{color: '#00420A', textAlign: 'center'}}>+ {t('add_list')}</Text>
            </View>
          </TouchableOpacity>*/}
        </ScrollView>

        {
          !this.state.visibleDate &&
          <View style={{backgroundColor: 'white', marginHorizontal: -16, paddingHorizontal: 16, paddingVertical: 16, marginBottom: -16}}>
            {/*<View style={[Styles.summary, {marginBottom: 10}]}>
              <Text>{t('repair_list')}</Text>
              <Text>{data.repair_list.length} {t('list_unit')}</Text>
            </View>
            <View style={[Styles.summary, {marginBottom: 10}]}>
              <Text>{t('summary_service')}</Text>
              <Text>{this.state.summary ? this.state.summary : 0} {t('baht')}</Text>
            </View>*/}

            <Button
              buttonStyle={{
                height: 40,
                borderRadius: 5,
                justifyContent: 'center',
                alignItems: 'center',
                backgroundColor: '#145EB3'
              }}
              titleStyle={{fontWeight: 'normal', fontSize: 14, fontFamily: Fonts.PromptRegular}}
              onPress={() => {
                this.submitRepair()
              }}
              disabled={this.state.disableSubmit}
              title={t('request_repair')}
            />
          </View>
        }

        {
          this.state.visibleDate &&
            <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({
                      visibleDate: 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.sendRepairData()}
          styleFooter={{justifyContent: 'center', marginTop: 30}}
        />

        <Popup
          title={t('send_data_success')}
          message={t('repair_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'
  },
  textInput: {
    backgroundColor: 'white',
    paddingVertical: 15,
    borderRadius: 5,
    borderWidth: 1,
    borderColor: 'rgba(0, 0, 0, 0.25)',
    paddingHorizontal: 10,
  },
  Select: {
    borderRadius: 5,
    backgroundColor: 'white'
  },
  SelectionBox: {
    borderRadius: 5,
    backgroundColor: 'white',
    borderWidth: 1,
    borderColor: 'white'
  },
  Selection: {
    // borderWidth: 1,
    // borderRadius: 10,
    // borderColor: 'rgba(0, 0, 0, .25)',
    height: 40,
    fontFamily: 'Prompt-Regular',
    fontSize: 14,
    // backgroundColor: 'white'
  },
  SelectionPlaceholder: {
    fontFamily: 'Prompt-Regular',
    fontSize: 14,
    color: "#00000080"
  },
  SelectionText: {
    fontFamily: 'Prompt-Regular',
    fontSize: 14
  },
  mbt16: {
    marginBottom: 16
  },
  DatePlaceholder: {
    flexDirection: 'row'
  },
  DateComponent: {
    flexDirection: 'row',
    backgroundColor: 'white',
    justifyContent: 'space-between',
    alignItems: 'center',
    borderRadius: 5,
    paddingLeft: 10,
    paddingRight: 10,
    paddingTop: 15,
    paddingBottom: 15,
    border: '1px solid gray',
    flex: 1
  },
  BtnDatePicker: {
    backgroundColor: '#00420A',
    borderRadius: 5
  },
  RepairListContainer: {
    backgroundColor: 'white',
    borderRadius: 5,
    borderWidth: 1,
    borderColor: 'rgba(0, 0, 0, .25)',
    padding: 16
  },
  BtnAddList: {
    borderWidth: 1,
    borderStyle: 'dashed',
    borderRadius: 5,
    borderColor: '#00420A',
    paddingVertical: 8
  },
  summary: {
    flexDirection: 'row',
    justifyContent: 'space-between'
  },
  textAreaBox: {
    backgroundColor: 'white',
    borderBottomColor: 'black',
    borderColor: 'rgba(0, 0,0, .25)',
    borderRadius: 5
  },
  textArea: {
    padding: 10
  },
  textMaterial: {
    backgroundColor: 'white',
    borderWidth: 1,
    borderColor: 'rgba(0, 0, 0, .25)',
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 5,
    color: '#00000080'
  }
}

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

export default connect(mapDisPatchToProps)(RepairIndex)
