import React, { Component } from 'react'
import {
  TouchableOpacity,
  TextInput,
  StyleSheet,
  View,
  ScrollView,
  Alert,
  Image,
  Slider,
  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 GetWidthHeightDevice from '../../components/GetWidthHeightDevice'
import Color from '../../../src/color';
import { t } from 'src/utils/i18n'
import {getRepairById, postEvaluateRepair} from "../../api/UserApi";
import IndicatorLoading from '../../components/IndicatorLoading';
import { StackActions, NavigationActions } from 'react-navigation';
import moment from 'moment';

function ConfirmEvaluate({isVisible, onPress, onCancel, points}) {
  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: 14, color: '#4F4F4F'}}>คุณต้องการจะให้คะแนน <Text style={{fontFamily: 'Prompt-Bold' }}>"{points} คะแนน"</Text> หรือไม่ ? กด <Text style={{fontFamily: 'Prompt-Bold' }}>"ยืนยัน"</Text> หากต้องการดำเนินการต่อ</Text>
          <View style={{flexDirection: 'row', justifyContent: 'flex-end', width: '100%', marginTop: 10}}>
            <TouchableOpacity onPress={onCancel} style={{marginRight: 20}}>
              <Text style={[{color: '#8A8A8F', fontSize: 16, fontWeight: '800'}]}>{t('cancel')}</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={onPress}>
              <Text style={[{color: '#269A21', fontSize: 16, fontWeight: '800'}]}>ยืนยัน</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </View>
  </Modal>
}
export default class RepairServiceDetail extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      value: 2,
      point_selected: 0,
      rating_point: [0,0,0,0,0],
      visibleConfirm: false
    }
    this.sendEvaluate = this.sendEvaluate.bind(this)
  }

  componentDidMount() {
    const { navigation } = this.props
    const id = navigation.getParam('id', 'NO-DATA')
    this.getRepairData(id)
  };

  visibleConfirm = () => {
    this.setState({
      visibleConfirm: !this.state.visibleConfirm
    })
  }

  getRepairData(id){
    this.setState({
      isLoading: true
    }, () => {
      getRepairById(id)
      .then(res => {
        console.log('repair data -------------> ',res.data.data)
        this.setState({
          repair: res.data.data,
          order_list: res.data.data.services,
          isLoading: false
        })

        this.props.navigation.setParams({statusRepair: res.data.data.status})
      })
    })
  }

  sendEvaluate(){
    let params = {
      id: this.state.repair.id,
      point: this.state.point_selected
    }

    if(this.state.point_selected === 0){
      Alert.alert('กรุณาเลือกระดับความพึงพอใจ', null, [{text: t('ok')}])
      return
    }

    this.setState({
      //isLoading: true,
      visibleConfirm: false
    }, () => {
      postEvaluateRepair(params)
        .then(res => {
          if(res.data.success){
            this.setState({
              isLoading: false,
            }, () => {
              setTimeout(() => Alert.alert('ให้คะแนนสำเร็จ', null, [
              {
                text: t('ok'),
                onPress: () => {
                  //this.getRepairData(this.state.repair.id)
                  this.props.navigation.dispatch(StackActions.reset({
                    index: 3,
                    actions: [
                      NavigationActions.navigate({
                        routeName: 'BottomTab',
                        action: NavigationActions.navigate({ routeName: 'ServiceScreen' })
                      }),
                      NavigationActions.navigate({ routeName: 'RepairService' }),
                      NavigationActions.navigate({ routeName: 'RepairHistory' }),
                      NavigationActions.navigate({ routeName: 'RepairHistoryDetail', params: { repair_id: this.state.repair.id } })
                    ]
                  }))
                }
              }
              ]), 500)
            })
          }else {
            this.setState({
              isLoading: false
            }, () => {
              Alert.alert('ให้คะแนนไม่สำเร็จ กรุณาลองใหม่อีกครั้งภายหลัง', null, [{text: t('ok')}])
            })
          }
        })
    })
  }

  setRating = (index) => {
    let rating_star = [0, 0, 0, 0, 0];
    for(let i=0; i<=index; i++){
      rating_star[i] = 1;
    }

    this.setState({
      rating_point: rating_star,
      point_selected: index + 1
    })
  }

  renderItem = (item) => {
    return <View style={{ flexDirection: 'row', marginVertical:3, justifyContent:'space-between'}}>
      <Text style={{ fontSize: 14, color: '#000000' }}>{item.name}</Text>
      <Text style={{ textAlign: 'right', fontSize: 14, color: '#7CBB33' }}>{item.service_fee} {t('baht')}</Text>
    </View>
  }

  render() {
    const {value, isLoading} = this.state;

    return (
        <ImageBackground source={require('../../../assets/images/tree2.png')} style={{width: '100%', flex: 1, backgroundColor:'#EEFFD7'}}>
          <View style={[styles.containerHeadbar]}>
            <View>
              <LinearGradient colors={['#4BAF3B', '#0E5E29']} style={{width: null,height: null,resizeMode: 'cover', borderRadius:5}}>
                <View style={{padding:16,paddingVertical: 10}}>
                  <View style={{flexDirection:'row'}}>
                    <Text style={{ flex:1,fontSize: 18, color: '#FFFFFF'}}>{t('room')} {this.state.repair && this.state.repair.room_no}</Text>
                    <Text style={{ fontSize: 18, color: '#FFFFFF'}}>#{this.state.repair && this.state.repair.id}</Text>
                  </View>
                  <Text style={{ fontSize: 14, color: 'rgba(255, 255, 255, 0.65)'}}>{this.state.repair && this.state.repair.project_name ? t('project') + this.state.repair.project_name : ''}</Text>
                </View>
              </LinearGradient>
            </View>

            <View style={{backgroundColor: '#FFFFFF',padding:16, flex: 1}}>
              <View>
                <Text style={{ fontSize: 14, color: Color.green_title}}>{t('make_appoint')}</Text>
                <View style={{ flexDirection: 'row',paddingVertical:5}}>
                  <Text style={{ fontSize: 14, color: Color.gray_half}}>{t('date')}</Text>
                  <Text style={{ fontSize: 14, color: '#000000'}}> {this.state.repair && moment(this.state.repair.date, 'YYYY-MM-DD').format('DD-MM-YYYY')}</Text>
                  <Text style={{ fontSize: 14, color: '#00000080'}}> เวลา</Text>
                  <Text style={{ fontSize: 14, color: '#000000'}}> {this.state.repair && this.state.repair.time.slice(0, -3)}</Text>
                </View>
                <View style={{ flexDirection: 'row',alignItems:'center'}}>
                  <Text style={{ fontSize: 14, color: '#00000080'}}>{t('status')}</Text>
                  <Image style={{marginHorizontal:10}} source={require('../../../assets/images/Ellipse2.png')} defaultSource={require('../../../assets/images/Ellipse2.png')} />
                  <Text style={{ fontSize: 14, color: Color.green_title}}>ซ่อมสำเร็จ</Text>
                </View>
              </View>

              <View style={[styles.hairline]}></View>

              <View style={{ flex: 1 }}>
                <View>
                  <Text style={{ fontSize: 14, color: Color.green_title}}>{t('information')}</Text>
                </View>
                <ScrollView>
                  <FlatList
                    data={this.state.order_list}
                    renderItem={({ item }) => this.renderItem(item)}
                    pagingEnabled={true}
                    extraData={this.state}
                    keyExtractor={this._keyExtractor}
                  />
                </ScrollView>
              </View>

              <View style={[styles.hairline, {marginVertical: 5}]}></View>

              <View style={styles.info_order_view}>
                <Text style={{ fontSize: 14, color: Color.green_title }} >{t('estimate_charge')}</Text>
                <Text style={{ textAlign: 'right', fontSize: 14, color: '#7CBB33'}} >{this.state.repair && this.state.repair.total} {t('baht')}</Text>
              </View>
            </View>
            {
              !isLoading && <View style={{width: '100%', marginTop:10,padding:16, backgroundColor: '#FFFFFF',borderRadius:5}}>
              <View>
                <Text style={{ fontSize: 14, color: Color.green_title, textAlign: 'center'}} >{t('rating')}</Text>
                <View style={{flexDirection: 'row', marginTop: 15, justifyContent: 'center'}}>
                  {
                      this.state.rating_point.map((point, index) =>
                      point === 0 ?
                        <View style={{alignItems: 'center', marginRight: index !== this.state.rating_point.length - 1 ? 15 : 0}}>
                          <Text style={{ fontSize: 14, color: '#000000', marginBottom: 10}} >{index + 1}</Text>
                          <TouchableOpacity onPress={() => this.state.repair.point === 0 || this.state.repair.points === null ? this.setRating(index) : {}} >
                            <Image source={require('../../../assets/images/star_grey.png')} style={{width: 40, height: 40}}/>
                          </TouchableOpacity>
                        </View>
                        : <View style={{alignItems: 'center', marginRight: index !== this.state.rating_point.length - 1 ? 15 : 0}}>
                            <Text style={{ fontSize: 14, color: '#000000', marginBottom: 10}} >{index + 1}</Text>
                            <TouchableOpacity onPress={() => this.state.repair.point === 0 || this.state.repair.points === null ? this.setRating(index) : {}} >
                              <Image source={require('../../../assets/images/star_yellow.png')} style={{width: 40, height: 40}}/>
                            </TouchableOpacity>
                        </View>
                    )
                  }
                </View>
              </View>
            </View>
            }
            {
              !isLoading && this.state.repair && (this.state.repair.points === null || this.state.repair.points === 0) &&
              <CustomButton style={[styles.button_style, {backgroundColor: this.state.point_selected === 0 ? '#C8C7CC' : '#145EB3' }, {marginTop: 16}]}
                            onPress={() => {this.visibleConfirm()}}
                            disabled={this.state.point_selected === 0}
                            title={'ส่งประเมิน'} />
            }
          </View>
          <ConfirmEvaluate
            isVisible={this.state.visibleConfirm}
            onPress={() => this.sendEvaluate()}
            onCancel={() => this.setState({visibleConfirm: false})}
            points={this.state.point_selected}
          />
          <IndicatorLoading loadingVisible={this.state.isLoading}/>
        </ImageBackground>
    )
  }
}



const styles = {
  containerHeadbar: {
    flex: 1,
    flexDirection: 'column',
    //height: GetWidthHeightDevice.HeightContainer,
    padding:16,
    fontStyle: "normal",
    justifyContent:'space-between'
  },
  hairline: {
    marginVertical: 17,
    backgroundColor: '#EAEAF4',
    height: 1,
    width: '100%'
  },
  button_style: {
    backgroundColor: '#145EB3',
    height: 40,
    borderRadius: 5,
    width: "100%",
  },
   row: {
    flex: 1, flexDirection: "row",
  },
  info_order_view:{
    paddingVertical:5,
    flexDirection: 'row',
    justifyContent:'space-between'
  },
  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%'
  }
}
