import React,{Component} from 'react'
import {
	TouchableOpacity,
    TextInput,
    StyleSheet,
    View,
    ScrollView,
    Alert,
    Image,
    ImageBackground,
    FlatList
} 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 moment from 'moment';
import { t } from '../../utils/i18n'

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: new Date(),
      tomorrow: new Date(moment().add(1, 'days').format()),
      isTimePickerVisible: false,
      isDateTimePickerVisible: false,
      room: '',
      project: '',

    }
    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')

    // this.state.repair = { repair: repair_state }
    this.state.repair =  repair_state
    this.setState({
      repair: repair_state,
      room: repair_state.repairs[0].room,
      project: repair_state.repairs[0].project,
    })
    console.log('repair_state:')
    console.log(repair_state)
    console.log('this.state.repair:')
    console.log(this.state.repair)
    console.log('room')
    console.log(this.state.repair.repairs[0].room)
    console.log('project')
    console.log(this.state.repair.repairs[0].project)
  };

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

    console.log('this.state.repair.date:')
    // console.log(this.state.repair.date)
    console.log(moment(this.state.select_date).format('YYYY-MM-DD'))
    console.log('this.state.repair.time:')
    // console.log(this.state.repair.time)
    console.log(moment(this.state.select_time).format('HH:mm'))
    console.log('this.state.repair:')
    console.log(this.state.repair)

    let params = {
      // date: this.state.repair.date,
      date: moment(this.state.select_date).format('YYYY-MM-DD'),
      // time: this.state.repair.time,
      time: moment(this.state.select_time).format('HH:mm'),
      repairs:[
        {
          services_id: this.state.repair.repairs[0].services_id,
        },
      ],
      room: this.state.repair.repairs[0].room,
      project: this.state.repair.repairs[0].project,
    }

    console.log('check paran send ------->> ', params)
    postRepair(params)
    .then(res => {
      console.log('response ----------------------- ',res.data);
      if(res.ok){
        this.setState({
          success_data: res.data.data,
          isLoading: false
        },() => {

          console.log('success_data:')
          console.log(res.data.data)
          this.props.navigation.navigate('RepairSuccess',{
            repair: this.state.success_data,
            room: this.state.repair.repairs[0].room,
            project: this.state.repair.repairs[0].project,
          })
        })
      }
    })
    .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 = date => {
    this.state.select_time = date
    //alert(date)
    this.hideTimePicker();
    // this.setState({select_time: date})
    this.state.select_time = date
  };

  render() {
    return (
      <ImageBackground source={require('../../../assets/images/tree2.png')} style={{width: '100%', height: '100%', backgroundColor:'#EEFFD7'}}>
        <View style={styles.containerHeadbar}>
          <View>
            <View style={{padding: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: 'white'}}>{  this.state.project }</Text>
                </View>
              </LinearGradient>
              <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.6,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>
                  <TouchableOpacity style={{flexDirection:'row', flex:0.4,backgroundColor: 'white',height:50, borderRadius:25, justifyContent:'center', alignItems:'center',marginLeft:5}}
                        onPress={this.hideTimePicker}>
                    <Text style={{ fontSize: 14, color: Color.gray_half}}>{t('time')}</Text>
                    <Text style={{ fontSize: 14, color: '#000000',marginLeft:10}}>{moment(this.state.select_time).format('HH:mm')}</Text>
                  </TouchableOpacity>
                </View>
              </View>
            </View>
            <Text style={{ fontSize: 14, color: '#00420A', paddingBottom: 10, marginHorizontal:16}} >{t('information')}</Text>
            <View style={{backgroundColor: 'white',}}>
              <FlatList
                data={this.state.repair.repairs}
                renderItem={this.renderItem}
                onScroll={this._onCarouselScroll}
                pagingEnabled={true}
                extraData={this.state}
                keyExtractor={this._keyExtractor}
              />
              <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.repair.service_fee} {t('baht')}</Text>
              </View>
            </View>
          </View>
          <View style={{flex:1,padding:16,justifyContent:'flex-end'}}>
            <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>
          <DateTimePicker
            date={this.state.select_date}
            isVisible={this.state.isDateTimePickerVisible}
            onConfirm={this.handleDatePicked}
            onCancel={this.hideDateTimePicker}
            minimumDate={this.state.tomorrow}
          />
          <DateTimePicker
            date={this.state.select_time}
            isVisible={this.state.isTimePickerVisible}
            onConfirm={this.handleTimePicked}
            onCancel={this.hideTimePicker}
            mode={'time'}
          />
          <IndicatorLoading loadingVisible={this.state.isLoading}/>
        </View>
      </ImageBackground>
    )
  }
}

const styles = {
  containerHeadbar: {
    flex: 1,
    height: GetWidthHeightDevice.HeightContainer,
    justifyContent:'space-between'
  },
  button_style: {
    backgroundColor: '#269A21',
    height: 40,
    borderRadius: 5,
    justifyContent:'center',
  }
}
