import React,{Component} from 'react'
import {
  TouchableOpacity,
  TextInput,
  StyleSheet,
  View,
  ScrollView,
  Alert,
  Image,
  ImageBackground,
  FlatList,
  Modal
} from 'react-native'
import Icon from "../../components/Icon";
import { CustomButton } from '../../components/CustomButton';
import {  Button, Card, Body, Badge, ListItem, Left, Right,CheckBox, } from 'native-base'
import { BackgroundImage } from '../../components/BackgroundImage'
import Text from '../../components/Text';
import LinearGradient from 'react-native-linear-gradient';
import Color from '../../color';
import GetWidthHeightDevice from '../../components/GetWidthHeightDevice'
import { postRepair } from '../../api/UserApi';
import IndicatorLoading from '../../components/IndicatorLoading';
import DateTimePicker from "react-native-modal-datetime-picker";
//import { CustomPicker } from '../../components/CustomPicker'
import moment from 'moment';
import { t } from '../../utils/i18n'
import { Picker } from 'native-base'

function AlertWarning({isVisible, onPress, onCancel}) {
  return <Modal visible={isVisible} transparent={true} animationType="none" key="alert-warning">
    <View style={styles.AlertWarningContainer}>
      <View style={styles.AlertWarning}>
        <View style={{width: '100%'}}>
          <Text style={{fontSize: 18, color: '#00420A', marginBottom: 10}}>ไม่สามารถนัดหมายเวลาดังกล่าวได้</Text>
          <Text style={{fontSize: 13, color: 'rgba(0, 0, 0, 0.5)'}}>ไม่สามารถนัดหมายเวลาในช่วงเวลาดังกล่าวได้ กรุณาเลือกวันและเวลานัดหมายใหม่</Text>
          <TouchableOpacity onPress={onCancel} style={{width: '100%'}}>
            <Text style={[{color: '#269A21', fontSize: 16, fontWeight: '800', textAlign: 'right'}]}>รับทราบ</Text>
          </TouchableOpacity>
        </View>
      </View>
    </View>
  </Modal>
}
export default class RepairConfirm extends Component {
	constructor(props) {
    super(props)
    this.state = {
      isLoading: false,
      repair:{},
      order_list:[
        {
          title: 'น้ำรั่ว',
          price: '200'
        },
        {
          title: 'เปลี่ยนก๊อกน้ำ',
          price: '150'
        },
        {
          title: 'ไฟฟ้าช๊อต',
          price: '500'
        }
      ],
      success_data:{},
      select_date: new Date(),
      select_time: '09:00:00',
      isTimePickerVisible: false,
      isDateTimePickerVisible: false,
      room: '',
      project: '',
      isShowWarning: false
    }
    this.confirmRepairService = this.confirmRepairService.bind(this)
    this.hideDateTimePicker = this.hideDateTimePicker.bind(this)
    this.handleDatePicked = this.handleDatePicked.bind(this)
    this.hideTimePicker = this.hideTimePicker.bind(this)
    this.handleTimePicked = this.handleTimePicked.bind(this)
  }

  componentDidMount = () => {
    const { navigation } = this.props
    const repair_state = navigation.getParam('repair', 'NO-DATA')
    let sum_service_fee = 0;
    if(repair_state && repair_state.repairs && repair_state.repairs.length > 0){
      repair_state.repairs.map((value) => {
        sum_service_fee += parseFloat(value.service_fee)
      })
    }
    console.log('service >>> ', repair_state.repairs)

    this.setState({
      repair: repair_state,
      room: repair_state.rooms && repair_state.rooms.length > 0 && repair_state.rooms[0].room_no ? repair_state.rooms[0].room_no : '',
      project_name: repair_state.rooms && repair_state.rooms.length > 0 && repair_state.rooms[0].project_name ? repair_state.rooms[0].project_name : '',
      project_id: repair_state.rooms && repair_state.rooms.length > 0 && repair_state.rooms[0].project_id ? repair_state.rooms[0].project_id : null,
      sum_service_fee: sum_service_fee
    })
  };

  confirmRepairService(){
    this.setState({
      isLoading: true
    })

    let services = [];
    if(this.state.repair && this.state.repair.repairs && this.state.repair.repairs.length > 0){
      this.state.repair.repairs.map(value => {
        services.push(value.id)
      })
    }

    let params = {
      date: moment(this.state.select_date).format('YYYY-MM-DD'),
      time: this.state.select_time,
      repairs: services,
      room: this.state.room,
      project: this.state.project_id,
    }

    postRepair(params)
    .then(res => {
      console.log('response ----------------------- ',res.data);
      if(res.ok){
        if(!res.data.success){
          this.setState({
            isLoading: false,
            isShowWarning: true
          })
        }else {
          this.setState({
            success_data: res.data.data,
            isLoading: false
          },() => {
            this.props.navigation.navigate('RepairSuccess',{
              repair: this.state.success_data
            })
          })
        }

      }else {
        this.setState({
          isLoading: false
        })
      }
    })
    .catch(() => {
      this.setState({
        isLoading: false
      })
    })
  }

  renderItem = ({item}) => {
    console.log(item)
    return <View style={{ flexDirection: 'row',paddingHorizontal:16,height: 40, borderBottomWidth:1, borderColor:'#00000040',justifyContent:'space-between',alignItems:'center'}}>
      <Text style={{ fontSize: 14, color: '#000000'}}>{item.name}</Text>
      <Text style={{ textAlign: 'right', fontSize: 14, color: '#7CBB33',}}>{item.service_fee} {t('baht')}</Text>
  </View>
  }

  _keyExtractor = (item, index) => 'repair_order_'+index

  hideDateTimePicker(){
    this.setState({ isDateTimePickerVisible: !this.state.isDateTimePickerVisible });
    //alert("hideDateTimePicker")
  };

  handleDatePicked = date => {
    //alert(date)
    this.state.select_date = date
    this.hideDateTimePicker();
    //this.setState({select_date: date})
    this.state.select_date = date
    //alert("handleDatePicked")
    //alert(date)
  };

  hideTimePicker(){
    this.setState({ isTimePickerVisible: !this.state.isTimePickerVisible });
  };

  handleTimePicked = time => {
    this.setState({
      select_time: time
    })
  };

  render() {
    return (
      <ImageBackground source={require('../../../assets/images/tree2.png')} style={{width: '100%', flex: 1, backgroundColor:'#EEFFD7'}}>
        <View style={styles.containerHeadbar}>
          <View style={{paddingHorizontal: 16, paddingTop: 16}}>
            <LinearGradient colors={['#4BAF3B', '#0E5E29']} style={{resizeMode: 'cover', borderRadius:5}}>
              <View style={{padding:16}}>
                <Text style={{ fontSize: 18, color: 'white'}}>{t('room')} {  this.state.room }</Text>
                <Text style={{ fontSize: 14, color: 'rgba(255, 255, 255, 0.65)' }}>{t('project') + this.state.project_name }</Text>
              </View>
            </LinearGradient>
          </View>

          <View style={{paddingHorizontal: 16, paddingBottom: 16}}>
            <Text style={{ fontSize: 14, color: '#00420A', paddingBottom: 10, paddingTop: 16 }}>{t('make_appoint')}</Text>
            <View style={{width: '100%'}}>
              <View style={{ flexDirection: 'row',}}>
                <TouchableOpacity style={{flexDirection:'row', flex:0.5,backgroundColor: 'white',height:50, borderRadius:25, justifyContent:'center', alignItems:'center',marginRight:5}}
                                  onPress={this.hideDateTimePicker}>
                  <Text style={{ fontSize: 14, color: Color.gray_half}}>{t('date')}</Text>
                  <Text style={{fontSize: 14, color: '#000000', marginHorizontal: 10,}}>{moment(this.state.select_date).format('DD-MM-YYYY')}</Text>
                  <Icon name="ic_calendar_alt" size={14} color="rgba(0,0,0,.5)" />
                </TouchableOpacity>

                <View style={{ flexDirection:'row', paddingLeft: 15, flex:0.5,backgroundColor: 'white',height:50, borderRadius:25, justifyContent:'center', alignItems:'center',marginLeft:5}}>
                  <Text style={{ fontSize: 14, color: Color.gray_half}}>{t('time')}</Text>
                  <Picker
                    mode="dialog"
                    inlineLabel
                    iosHeader={t('time')}
                    style={{ backgroundColor: 'white', flexGrow: 0, width: 80, height: 40, fontFamily: 'Prompt-Regular', fontSize: 14 }}
                    placeholderStyle={{ fontFamily: 'Prompt-Regular', fontSize: 14, color: "#bfc6ea" }}
                    placeholderIconColor="#007aff"
                    textStyle={{ fontFamily: 'Prompt-Regular', fontSize: 14 }}
                    itemTextStyle={{ fontFamily: 'Prompt-Regular', fontSize: 14 }}
                    selectedValue={this.state.select_time}
                    enabled={true}
                    onValueChange={(itemValue, itemIndex) => {
                      console.log(itemValue) 
                      this.handleTimePicked(itemValue)
                    }}
                  >
                    <Picker.Item label="09:00" value="09:00:00" />
                    <Picker.Item label="10:00" value="10:00:00" />
                    <Picker.Item label="11:00" value="11:00:00" />
                    <Picker.Item label="12:00" value="12:00:00" />
                    <Picker.Item label="13:00" value="13:00:00" />
                    <Picker.Item label="14:00" value="14:00:00" />
                    <Picker.Item label="15:00" value="15:00:00" />
                    <Picker.Item label="16:00" value="16:00:00" />
                  </Picker>
                  {/*<Picker
                    selectedValue={this.state.select_time}
                    // mode={'dropdown'}
                    style={{
                      height: 50, flex:1
                    }}
                    onValueChange={(itemValue, itemIndex) => this.handleTimePicked(itemValue)}
                  >
                    <Picker.Item label="09:00" value="09:00:00" />
                    <Picker.Item label="10:00" value="10:00:00" />
                    <Picker.Item label="11:00" value="11:00:00" />
                    <Picker.Item label="12:00" value="12:00:00" />
                    <Picker.Item label="13:00" value="13:00:00" />
                    <Picker.Item label="14:00" value="14:00:00" />
                    <Picker.Item label="15:00" value="15:00:00" />
                    <Picker.Item label="16:00" value="16:00:00" />
                  </Picker>*/}
                </View>
              </View>
            </View>
          </View>

          <View style={{ flex: 1 }}>
            <Text style={{ fontSize: 14, color: '#00420A', paddingBottom: 10, marginHorizontal:16}} >{t('information')}</Text>
            <View style={{ backgroundColor: 'white', flex: 1}}>
              <ScrollView>
                <FlatList
                  data={this.state.repair.repairs}
                  renderItem={this.renderItem}
                  onScroll={this._onCarouselScroll}
                  pagingEnabled={true}
                  extraData={this.state}
                  keyExtractor={this._keyExtractor}
                />
              </ScrollView>

              <View style={{ flexDirection: 'row',paddingHorizontal:16,height: 40,justifyContent:'space-between',alignItems:'center'}}>
                  <Text style={{ fontSize: 14, color: '#269A21'}}>{t('estimate_charge')}</Text>
                  <Text style={{ textAlign: 'right', fontSize: 14, color: '#7CBB33'}}>{this.state.sum_service_fee} {t('baht')}</Text>
                </View>
              </View>
          </View>

          <View style={{ padding: 16}}>
            <CustomButton style={[styles.button_style]}
                          onPress={() => {
                            Alert.alert(
                              t('send_confirmation'),
                              t('send_confirm'),
                              [
                                { text: t('cancel'), style: 'cancel' },
                                { text: t('ok'), onPress: () => this.confirmRepairService() },
                              ],
                              { cancelable: false }
                            )
                          }}
                          title={'ยืนยัน'} />
          </View>
        </View>

        <DateTimePicker
          date={this.state.select_date}
          isVisible={this.state.isDateTimePickerVisible}
          onConfirm={this.handleDatePicked}
          onCancel={this.hideDateTimePicker}
          minimumDate={new Date()}
        />
        <IndicatorLoading loadingVisible={this.state.isLoading}/>

        <AlertWarning
          isVisible={this.state.isShowWarning}
          onCancel={() => this.setState({isShowWarning: false})}
          onPress={() => this.setState({isShowWarning: false})}/>
      </ImageBackground>
    )
  }
}

const styles = {
  containerHeadbar: {
    flex: 1,
    height: GetWidthHeightDevice.HeightContainer ? GetWidthHeightDevice.HeightContainer : null,
    // justifyContent:'space-between',
  },
  button_style: {
    backgroundColor: '#269A21',
    height: 45,
    borderRadius: 5,
    justifyContent:'center',
  },
  AlertWarningContainer: {
    backgroundColor: 'rgba(0,0,0,0.6)',
    justifyContent: 'center',
    alignItems: 'center',
    position: 'absolute',
    width: '100%',
    height: '100%',
    flex: 1
  },
  AlertWarning: {
    backgroundColor: 'white',
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 5,
    marginHorizontal: 25,
    paddingVertical: 20,
    paddingHorizontal: 20,
    maxWidth: 300,
    width: '100%'
  }
}
