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 {cancelRepair, getRepairById} from '../../api/UserApi';
import IndicatorLoading from '../../components/IndicatorLoading';
import { t } from '../../utils/i18n'
import moment from 'moment';

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: '#FF3B30', marginBottom: 10}}>ยืนยันยกเลิกการแจ้งซ่อม</Text>
          <Text style={{fontSize: 14, color: 'rgba(0, 0, 0, 0.5)'}}>
            คุณต้องการที่จะยกเลิกการแจ้งซ่อม หรือไม่ ? กด <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: 'rgba(0, 0, 0, 0.5)', fontSize: 16, fontWeight: '800'}]}>{t('cancel')}</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={onPress}>
              <Text style={[{color: '#FF3B30', fontSize: 16, fontWeight: '800'}]}>ยืนยัน</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </View>
  </Modal>
}

export default class RepairHistoryDetail extends Component {
	constructor(props) {
    super(props)
    this.state = {
      isLoading: false,
      repair_id: this.props.navigation.getParam('repair_id','NO_ITEM'),
      type: this.props.navigation.getParam('type','NO_ITEM'), //params from Notification.js
      project_id: this.props.navigation.getParam('project_id',null),
      repair:{},
      visibleCancel: false,
      rating_point: [0,0,0,0,0],
      order_list:[
        // {
        //   title: 'น้ำรั่ว',
        //   price: '200'
        // },
        // {
        //   title: 'เปลี่ยนก๊อกน้ำ',
        //   price: '150'
        // },
        // {
        //   title: 'ไฟฟ้าช๊อต',
        //   price: '500'
        // },
      ]
    }
    this.convertStatus = this.convertStatus.bind(this)
    this.convertColorStatus = this.convertColorStatus.bind(this)
  }

  componentWillUnmount = () => {
    if(this.props && this.props.navigation && this.props.navigation.state && this.props.navigation.state.params && this.props.navigation.state.params.getRepairHistoryList){
      this.props.navigation.state.params.getRepairHistoryList()
    }
  }

  componentDidMount = () => {
	  this.props.navigation.setParams({cancelRepair: this.cancelRepair})
    this.getRepairData()
  };

  cancelRepair = () => {
    this.setState({
      visibleCancel: true
    })
  }

  confirmCancel = () => {
    this.setState({
      isLoading: true
    }, () => {
      cancelRepair(this.state.repair.id)
        .then(res => {
          if(res.ok){
            if(res.data.success){
              this.setState({
                visibleCancel: false,
                isLoading: false
              }, () => {
                this.getRepairData()
              })
            }else {
              this.setState({
                visibleCancel: false,
                isLoading: false
              })
            }
          }
        })
    })
  }

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

      let rating_star = [0, 0, 0, 0, 0];
      for(let i=0; i<res.data.data.points; i++){
        rating_star[i] = 1;
      }

      this.setState({
        rating_point: rating_star
      })

      this.props.navigation.setParams({statusRepair: res.data.data.status})
    })
    .catch(() => {
      this.setState({
        isLoading: false
      })
    })
  }

  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: this.state.type === 'effect_responsible' ? 'red' : '#7CBB33' }}>{this.state.repair.status === 'Cancel' ? 0: item.service_fee} {t('baht')}</Text>
    </View>
  }

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

  convertStatus(statusName){
    switch(statusName){
      case 'Pending':
        return t('request_repair');
      case 'InProgress':
        return 'ยืนยันนัด';
      case 'NewAppointment':
        return t('repair_re_appoint');
      case 'Cancel':
        return t('cancel');
      case 'Success':
        return t('repair_success');
      default:
        return t('pending')
    }
  }

  convertColorStatus(statusName){
    switch(statusName){
      case 'Pending':
        return '#FF9500';
      case 'InProgress':
        // return '#FFCC00'
        return '#007AFF';
      case 'NewAppointment':
        return '#145EB3';
      case 'Cancel':
        return '#666666';
      case 'Success':
        return '#2C7C0B';
      default:
        return '#C4C4C4';
    }
  }

  render() {
    return (
      <ImageBackground source={require('../../../assets/images/tree2.png')} style={{width: '100%', height: '100%', backgroundColor:'#EEFFD7'}}>
        <View style={{padding:16, flex: 1}}>
          <LinearGradient colors={['#4BAF3B', '#0E5E29']} style={{borderRadius:5, padding:16}}>
            <View style={{flexDirection:'row',justifyContent:'space-between'}}>
              <Text style={{ fontSize: 18, color: '#FFFFFF'}} >{t('room')} {this.state.repair && this.state.repair.room_no ? this.state.repair.room_no : ''}</Text>
              <Text style={{ textAlign:'right', fontSize: 18, color: '#FFFFFF', }} >#{this.state.repair && this.state.repair.id ? 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 ? this.state.repair.project_name : '' }</Text>
          </LinearGradient>

          <View style={{backgroundColor: '#FFFFFF',borderRadius:5,padding:16, flex: 1 }}>
            <View>
              <Text style={styles.textTitle}>{t('make_appoint')}</Text>
              <View style={{ flexDirection: 'row',}}>
                {
                  this.state.repair && this.state.repair.status ?
                    this.state.repair.status === 'Pending'
                    && (this.state.repair.date === null || this.state.repair.time === null || this.state.repair.date === '' || this.state.repair.time === '')
                      ? <Text style={{ fontSize: 14, color: '#000000', paddingRight: 10,}}>กรุณารอการนัดหมายใหม่จากเจ้าหน้าที่</Text>
                      : <View style={{flexDirection: 'row'}}>
                        <Text style={{ fontSize: 14, color: 'rgba(0, 0, 0, 0.5)' }}>{t('date')}</Text>
                        <Text style={{ fontSize: 14, color: '#000000', paddingHorizontal: 10,}}>{this.state.repair && this.state.repair.date ? moment(this.state.repair.date, 'YYYY-MM-DD').format('DD-MM-YYYY') : '' }</Text>
                        <Text style={{ fontSize: 14, color: 'rgba(0, 0, 0, 0.5)' }}>เวลา</Text>
                        <Text style={{ fontSize: 14, color: '#000000', paddingHorizontal: 10,}}>{this.state.repair && this.state.repair.time ? moment(this.state.repair.time, 'HH:mm:ss').format('HH:mm') + ' น.' : '' }</Text>
                      </View>
                    : <Text/>
                }
              </View>
              <View style={{ flexDirection: 'row',alignItems:'center',marginVertical:3}}>
                <Text style={{ fontSize: 14, color: 'rgba(0, 0, 0, 0.5)'}}>{t('status')}</Text>
                <View style={{backgroundColor:this.convertColorStatus(this.state.repair.status),height: 10,width: 10,borderRadius:5, marginHorizontal:10}}/>
                <Text style={{ fontSize: 14, color:this.convertColorStatus(this.state.repair.status)}}>{this.state.repair && this.state.repair.status ? this.convertStatus(this.state.repair.status) : ''}</Text>
              </View>
            </View>

            <View style={{borderWidth:1,marginVertical:16,borderColor:'silver'}}></View>

            <View style={{ flex: 1 }}>
              <Text style={[styles.textTitle, this.state.type === 'effect_responsible' ? {color: '#FF3B30'} : {}]} >
                {this.state.type === 'effect_responsible' ? 'รายการซ่อมที่ต้องรับผิดชอบ' : t('information')}
              </Text>
              <ScrollView>
                <FlatList
                  data={this.state.order_list}
                  renderItem={({ item }) => this.renderItem(item)}
                  pagingEnabled={true}
                  extraData={this.state}
                  keyExtractor={this._keyExtractor}
                />
              </ScrollView>
            </View>

            <View style={{borderWidth:1,marginVertical:16,borderColor:'silver'}}></View>

            <View style={{ flexDirection:'row',justifyContent:'space-between'}}>
              <Text style={[{ fontSize: 14}, this.state.type === 'effect_responsible' ? {color: '#FF3B30'} : {color: Color.green_title}]}>{t('estimate_charge')}</Text>
              <Text style={[{ textAlign: 'right', fontSize: 14, color: '#7CBB33'}, this.state.type === 'effect_responsible' ? {color: '#FF3B30'} : {color: Color.green_title}]}>{this.state.repair.status === 'Cancel' ? 0 : this.state.repair && this.state.repair.total ? this.state.repair.total : 0} {t('baht')}</Text>
            </View>
          </View>

          {
            this.state.repair.status === 'Success' && this.state.repair.points &&
            <View style={{marginTop: 16, backgroundColor: '#FFFFFF',borderRadius:5, paddingVertical: 16}}>
              <View>
                <Text style={{ fontSize: 14, color: Color.green_title, textAlign: 'center'}} >คะแนนการประเมิน</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>
                          <Image source={require('../../../assets/images/star_grey.png')} style={{width: 40, height: 40}}/>
                        </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>
                          <Image source={require('../../../assets/images/star_yellow.png')} style={{width: 40, height: 40}}/>
                        </View>
                    )
                  }
                </View>
              </View>
            </View>
          }

          <View style={{ width: '100%', alignItems: 'center', marginTop: 16}}>
            {
              !this.state.repair.points &&
              <CustomButton style={[styles.button_style]}
                            onPress={() => {
                              this.props.navigation.navigate('Question')
                            }}
                            title={'ติดต่อเจ้าหน้าที่'}/>
            }

            {
              !this.state.repair.points && this.state.repair.status === 'Success' &&
              <CustomButton style={[styles.button_style, {backgroundColor: '#269A21', marginTop: 16}]}
                            onPress={() => {
                              this.props.navigation.navigate('RepairDetail', {
                                id: this.state.repair.id
                              })
                            }}
                            title={'ประเมินให้คะแนน'}/>
            }
          </View>
         {/* <View>


        {
          this.state.repair.status === 'Success' && this.state.repair.points &&
          <View style={{padding:16, backgroundColor: '#FFFFFF',borderRadius:5, marginHorizontal: 16}}>
            <View>
              <Text style={{ fontSize: 14, color: Color.green_title, textAlign: 'center'}} >คะแนนการประเมิน</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>
                        <Image source={require('../../../assets/images/star_grey.png')} style={{width: 40, height: 40}}/>
                      </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>
                        <Image source={require('../../../assets/images/star_yellow.png')} style={{width: 40, height: 40}}/>
                      </View>
                  )
                }
              </View>
            </View>
          </View>
        }


          <View style={{position: 'absolute', bottom: 16, width: '100%', alignItems: 'center'}}>
            {
              !this.state.repair.points &&
              <CustomButton style={[styles.button_style, {marginBottom: 10}]}
                            onPress={() => {
                              this.props.navigation.navigate('Question')
                            }}
                            title={'ติดต่อเจ้าหน้าที่'}/>
            }

            {
              !this.state.repair.points && this.state.repair.status === 'Success' &&
              <CustomButton style={[styles.button_style, {backgroundColor: '#269A21'}]}
                            onPress={() => {
                              this.props.navigation.navigate('RepairDetail', {
                                id: this.state.repair.id
                              })
                            }}
                            title={'ประเมินให้คะแนน'}/>
            }
          */}
        </View>
        <IndicatorLoading loadingVisible={this.state.isLoading} />
        <AlertWarning
          isVisible={this.state.visibleCancel}
          onPress={() => this.confirmCancel()}
          onCancel={() => this.setState({visibleCancel: false})}
        />
      </ImageBackground>
    )
  }
}

const styles = {
  textTitle:{
    fontSize: 14,
    color: Color.green_title,
    marginBottom: 10
  },
  button_style: {
    backgroundColor: '#007AFF',
    height: 40,
    borderRadius: 5,
    width: '100%',
    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%'
  }
}
