import React, {Component} from 'react'
import {Button, View,} from 'native-base'
import {Dimensions, FlatList, ScrollView, StyleSheet, TouchableOpacity, Alert, RefreshControl} from 'react-native'
import Image from 'react-native-fast-image'
import ImageBackground from 'react-native-fast-image'
import LinearGradient from 'react-native-linear-gradient'
import Text from '../../components/Text';
import moment from "moment";
import Color from '../../../src/color';
import {getService, getServicesType, getUserProfile, payment} from '../../api/UserApi';
import IndicatorLoading from '../../components/IndicatorLoading';
import { t, locale } from '../../utils/i18n';
import Icon from '../../components/Icon';

const SLIDER_1_FIRST_ITEM = 0;
const { height, width } = Dimensions.get('window')

const btnActiveColor = '#145EB3'
const btnUnActiveColor = '#FFFFFF'
export default class RepairService extends Component {
  constructor(props) {
    super(props)

    this.state = {
      isLoading: false,
      refreshing: false,
      activePage: 0,
      repair_list:[],
      isSelectReapair: true,
      isSelectOther: false,
      indexItem: [],
      selectServiceIndex: 0,
      selectService:{},
      room_list:[],
      service_data : [],
      customer_project_name: '',
      user:'',
      room:'',
      project_name:'',

      payment: [],
      sum_payment: [],
      isCanPay: true,
      all_payment : [],
      room_number_array : [],
      selected_room: '',
      selected_project: '',
      loadMore: false,
      loadPage: 1,
      isLoadmore: false,
    };
    this._onCarouselScroll = this._onCarouselScroll.bind(this)
    this.switchSelected = this.switchSelected.bind(this)
    this.getServicesListByType = this.getServicesListByType.bind(this)
    this.setCheckIndex = this.setCheckIndex.bind(this)
    this.sendRepairService = this.sendRepairService.bind(this)
  };

  componentDidMount = () => {

    const { navigation } = this.props
    const users_state = navigation.getParam('user', 'NO ITEM')
    const selected_room_state = navigation.getParam('selected_room', '')
    const selected_project_state = navigation.getParam('selected_project', '')
    this.state.selected_room = selected_room_state
    this.state.selected_project = selected_project_state
    console.log('init selected_room:'+ selected_room_state)
    console.log('init selected_project:'+ selected_project_state)

   // if((selected_room_state !== '')&&(selected_project_state !== '')){
   //this.switchSelected('repair')
   // }else{
   this.getServicesListByType(2)
   // }

    // console.log('check user state ----------- ',users_state)
    if(users_state.gender == null || users_state.gender == 'null'){
      console.log('NULL');
      this.setState({
        user: {
          gender: 'male',
          ...users_state
        }
      })
    }else{
      console.log('NOT NULL');
      this.setState({
        user: users_state
      })
    }
    console.log('users_state:')
    console.log(users_state)
    if(users_state){
      payment(users_state.id)
          .then(res => {
            if(res.ok){
              let sum_payment = [];
              let array_payment = [];
              let sum_cost_room = res.data.sum_cost_room;
              if(Object.keys(sum_cost_room).length > 0) {
                Object.keys(sum_cost_room).map((sum_cost) => {
                  sum_payment.push({
                        total_cost : sum_cost_room[sum_cost].total_cost,
                        room: sum_cost_room[sum_cost].room,
                        project: sum_cost_room[sum_cost].project,
                        due_at: sum_cost_room[sum_cost].due_at,
                      }
                  )
                })
              }

              let payment = res.data.payment_room_period
              if(Object.keys(payment).length > 0){
                Object.keys(payment).map((pay) => {
                  if(Object.keys(payment[pay]).length > 0){
                    Object.keys(payment[pay]).map((detail) => {
                      this.state.room_number_array.push(pay)
                      array_payment.push({
                        room_id: pay,
                        period: detail,
                        // total_cost: payment[pay][detail].total_cost,
                        // details: payment[pay][detail].details,
                        // status: payment[pay][detail].status,
                        // created_at: payment[pay][detail].created_at,
                        // payment_id: payment[pay][detail].id,
                        // enable_qr: payment[pay][detail].enable_qr
                        ...payment[pay][detail]
                      })
                    })
                  }
                })
              }
              let all_payment_data = array_payment;

              let array_room_no = this.state.room_number_array;
              this.setState({
                room_number_array: array_room_no.filter((item, i, ar) => ar.indexOf(item) === i).reverse()
              });

              let first_room = this.state.room_number_array[0];
              array_payment = array_payment.filter((obj)=>{
                return Object.keys(obj).reduce((acc, curr)=>{
                  return obj.room_id === first_room
                }, false);
              });


              let date_now = moment()
              let findTimeout = array_payment.find((item) => {return moment(item.due_at) == date_now})
              //check bill timeout
              if(findTimeout !== undefined){
                this.setState({
                  isCanPay: false
                })
              }

              this.setState({
                isLoading:false,
                payment: array_payment,
                sum_payment: sum_payment,
                all_payment: all_payment_data
              })
            }
          })
    }

    //this.state.selected_room=''
    //this.state.selected_project=''
  };

  switchSelected(typeName){
    if(typeName == 'repair'){
      this.setState({
        isSelectReapair: true,
        isSelectOther: false
      })
      this.getServicesListByType(2)
    }else{
      this.setState({
        isSelectReapair: false,
        isSelectOther: true
      })
      this.getServicesListByType(1)
    }
  }

  getServicesListByType(id){
    this.setState({
      isLoading: true
    })
    getUserProfile()
        .then(res => {
          if(res.ok){
            //alert(res.data.user.project_name)
            this.setState({
              // isLoading: false,
              user: res.data.user,
              room: res.data.room,
              project_name: res.data.user.project_name,
            })
            console.log('res.data.user.project_name:')
            console.log(res.data.user.project_name)

            getServicesType(id)
                .then(res => {
                  this.state.customer_project_name = this.state.project_name
                  //alert(this.state.project_name.slice(0,-4))
                  //alert(this.state.project_name.normalize())
                  //this.state.service_data = res.data.data
                  console.log('res.data.data:')
                  console.log(res.data.data)
                  this.state.service_data = res.data.data.filter(obj => {
                    return obj.project_code === this.state.selected_project
                  })
                  console.log('this.state.service_data:')
                  console.log(this.state.service_data)

                  /*this.state.service_data = this.state.service_data.filter(l => {
                     return l.project_code.match(
                         this.state.selected_project
                     )
                   })*/

                  this.setState({
                    repair_list: this.state.service_data,
                    isLoading: false,
                    selectService: this.state.service_data[0],
                    selected_project: this.state.service_data[0].project_name,
                  },() => {
                    this.state.repair_list.map(() => {
                      this.state.indexItem.push(false)
                    })
                  })
                })


          }else{
            this.setState({
              isLoading: false
            })
          }
        })

  }

  sendRepairService(){
    //alert(this.state.selected_room)
    //alert(this.state.selected_project)

    console.log('date:')
    console.log('time:')



    let params = {
      date: moment().format('YYYY-MM-DD'),
      time: moment().format('HH:MM:SS'),
      repairs:[
        {
          name:this.state.selectService.name,
          services_id: this.state.selectService.id,
          service_fee: this.state.selectService.service_fee,
          room: this.state.selected_room,
          project: this.state.selected_project,
        }
      ],
      service_fee: this.state.selectService.service_fee
    }

    this.props.navigation.navigate('RepairConfirm',{repair: params})

  }

  setCheckIndex(index){
    let indexBool = this.state.indexItem.slice(); //creates the clone of the state
    indexBool[index] = !this.state.indexItem[index]
    this.setState({
      indexItem: indexBool
    })
  }

  _renderContent = (item,index) => {
    return <TouchableOpacity style={{borderBottomWidth: 2,borderColor:'#F4F4F4',backgroundColor:'white'}}
      onPress={() => {
      // this.setCheckIndex(index)
        this.setState({
          selectServiceIndex: index,
          selectService: item,
          selected_project: item.project_name
        })
      }}>
      <View style={{height: 65,backgroundColor:'white',paddingLeft:16,flexDirection:'row',justifyContent:'space-between'}}>
        <View style={{justifyContent:'center'}}>
          <Text style={{color:'black',fontSize:14}}>{item.name}</Text>
          <Text style={{color:Color.green_title,fontSize:12}}>ค่าบริการขั้นต่ำ {item.service_fee} {t('baht')}</Text>
        </View>
        {
          this.state.repair_list != null && this.state.repair_list.length > 0 &&
          this.state.repair_list[this.state.selectServiceIndex].id == item.id &&
          <View style={{width: 64,justifyContent:'center',alignItems:'center'}}>
            <Image source={require('../../../assets/images/check.png')} style={{width:32, height:32}}/>
          </View>
        }
      </View>
    </TouchableOpacity>
  }

  getDueDate (date) {
    let d = moment(date).format('D')
    let m = moment(date).format('MM')
    let y = parseInt(moment(date).format('Y')) + 543
    let new_month = 'ม.ค.';
    let new_date = d + ' ' + new_month + ' ' + y;
    switch (m) {
      case '01':
        new_month = 'ม.ค.';
        break;
      case '02':
        new_month = 'ก.พ.';
        break;
      case '03':
        new_month = 'มี.ค.';
        break;
      case '04':
        new_month = 'เม.ย.';
        break;
      case '05':
        new_month = 'พ.ค.';
        break;
      case '06':
        new_month = 'มิ.ย.';
        break;
      case '07':
        new_month = 'ก.ค.';
        break;
      case '08':
        new_month = 'ส.ค.';
        break;
      case '09':
        new_month = 'ก.ย.';
        break;
      case '10':
        new_month = 'ต.ค.';
        break;
      case '11':
        new_month = 'พ.ย.';
        break;
      case '12':
        new_month = 'ธ.ค.';
        break;
      default:
        new_month = 'ม.ค.';
        break;
    }
    new_date = d + ' ' + new_month + ' ' + y;
    return new_date;
  }

  renderNativeItemImages = (item) => {
    return <View style={{width: width, alignItems: 'center', paddingTop: 10, paddingBottom: 40,height: 177,}}>
    <View style={{width: '60%', height: '100%', backgroundColor: '#06ADB8', borderRadius: 5 }}>
      <LinearGradient colors={['#4BAF3B', '#0E5E29']} style={{ flex:1, borderRadius: 5, height: 120,paddingBottom:10, justifyContent:'space-between'}}>
        <View style={{ padding: 16,paddingBottom: 5,paddingTop:10 , borderRadius: 5}}>
          <Text style={{ color: 'white', fontSize: 18 }}>{item.room && item.room.name}</Text>
          <Text style={{ color: 'rgba(255, 255, 255, 0.65)', fontSize: 14 }}>{item.project && item.project.name}</Text>
        </View>
        <View style={{height:24,backgroundColor: '#FF2D55',justifyContent:'center',paddingLeft:16}}>
          <Text style={{ fontSize: 12, color: 'white'}}>มีการแจ้งใช้บริการ</Text>
        </View>
      </LinearGradient>
    </View>
  </View>
  }
  _onCarouselScroll(e) {
    const scrollX = e.nativeEvent.contentOffset.x
    this.setState({
      activePage: Math.floor(scrollX / width)
    })
  }

  _keyExtractor = (item, index) => 'repair_'+index
  _keyExtractorContent = (item, index) => 'repair_content_'+index


  getListViewItem = (item) => {
    console.log('this.state.payment:')
    console.log(this.state.payment)
    console.log('this.state.sum_payment:')
    console.log(this.state.sum_payment)

    let selected_room_data = this.state.sum_payment.filter(obj => {
      return obj.room === item
    })
    console.log('selected_room_data[0].project:')
    console.log(selected_room_data[0].project)

    //this.payment_room_period[''].project_code*/
    this.state.selected_room=item
    this.state.selected_project=selected_room_data[0].project
    console.log("selected_room_data[0]:")
    console.log(selected_room_data[0])
    //Alert.alert(this.state.selected_project)

    this.switchSelected('repair')

    this.props.navigation.navigate('RepairService',
        {user:this.state.user, selected_room:this.state.selected_room,selected_project:this.state.selected_project})

  }

  _onRefresh = () => {
    this.setState({
      refreshing: true, loadPage: 1, loadMore: false
    }, () => {
      //this.initData()
      //alert('refresh')
    })
  }


  render() {
    let dataTest = ['']
    console.log('room_number_array:')
    console.log(this.state.room_number_array)
    return (



      <ImageBackground source={require('../../../assets/images/tree2.png')} style={{width: '100%', height: '100%', backgroundColor:'#EEFFD7'}}>
        <ScrollView
            contentContainerStyle={styles.contentContainer}
            // refreshControl={
            //   <RefreshControl
            //       refreshing={this.state.refreshing}
            //       onRefresh={this._onRefresh}
            //   />
            // }
        >
          <View style={{ alignItems: 'center' }}>
          <FlatList
              data={this.state.room_list}
              renderItem={({ item }) => this.renderNativeItemImages(item)}
              horizontal={true}
              onScroll={this._onCarouselScroll}
              pagingEnabled={true}
              extraData={this.state}
              keyExtractor={this._keyExtractor}
              showsHorizontalScrollIndicator={false}
            />
            <View style={{ position: 'absolute', bottom: 10, width: '100%', justifyContent: 'center', flexDirection: 'row' }}>
              {this.state.room_list.map((item, i) => <View key={'sum_payment_'+i} style={[{ width: 10, height: 10, borderRadius: 5, backgroundColor: this.state.activePage == i ? '#269A21' : 'rgba(124, 187, 51, 0.3)', marginHorizontal: 4 }]}></View>)}
            </View>
          </View>




            { this.state.selected_room !== ''?
                <View style={{alignItems:'center'}}>
                <Text style={{ fontSize: 14, marginTop: 5, color: '#00420A' }}>{t('place_choose_service')}</Text>
                <View style={{  alignItems: 'center', marginTop: 12, flexDirection: 'row', marginBottom: 20 }}>
                  <Button style={[styles.button_style_repair,{backgroundColor:this.state.isSelectReapair ? btnActiveColor : btnUnActiveColor,borderTopRightRadius:0,borderBottomRightRadius:0}]}
                            onPress={() => {this.switchSelected('repair')}}>
                    <Text style={locale() == "my" ? { color: 'white', fontSize: 6, color: this.state.isSelectReapair ? '#FFFFFF' : '#000000' } : { color: 'white', fontSize: 14, color: this.state.isSelectReapair ? '#FFFFFF' : '#000000' }}>{t('request_repair')}</Text>
                  </Button>
                  <Button style={[styles.button_style_other,{backgroundColor:this.state.isSelectOther ? btnActiveColor : btnUnActiveColor,borderTopLeftRadius:0,borderBottomLeftRadius:0}]}
                            onPress={() => {this.switchSelected('other')}}>
                    <Text style={locale() == "my" ? { color: 'black', fontSize: 12, color: this.state.isSelectOther ? '#FFFFFF' : '#000000' }: { color: 'black', fontSize: 14, color: this.state.isSelectOther ? '#FFFFFF' : '#000000' }}>{t('other_service')}</Text>
                  </Button>
                </View>
                </View>
              :
                <View style={{alignItems:'center'}}>
                <Text style={{ fontSize: 14, marginTop: 5, marginBottom: 10, color: '#00420A' }}>กรุณาเลือกห้องที่ต้องการแจ้ง</Text>
                </View>
              }



          <View style={{}}>
            { !this.state.room_number_array?
                <Text>ไม่มีรายการห้องพัก</Text>
            :

                this.state.selected_room == ''?
                <FlatList
                    style={{backgroundColor:'white'}}
                    data={this.state.room_number_array}
                    renderItem={({ item }) => (
                        <View onPress={this.getListViewItem.bind(this, item)}  style={{ margin: 0,padding:5,borderRadius:5,backgroundColor:'white',  borderBottomColor:'black',borderBottomWidth: 0.5}}>
                            <Text  style={{ margin: 5, left: 5, fontSize: 14,}}>
                              ห้อง { item }
                            </Text>
                        </View>
                    )}
                    ListEmptyComponent={() => (
                        <View style={{height:64,margin:16,alignItems:'center',justifyContent:'center',backgroundColor:'white',borderRadius:5}}>
                          <Text style={{color:'black'}}>ไม่มีรายการห้องพัก</Text>
                        </View>
                    )}
                />
                :
                    <FlatList
                        style={{backgroundColor:'white'}}
                        data={this.state.repair_list}
                        renderItem={({ item, index }) => this._renderContent(item,index)}
                        extraData={this.state}
                        keyExtractor={this._keyExtractorContent}
                        ListEmptyComponent={() => (
                            <View style={{height:64,margin:16,alignItems:'center',justifyContent:'center',backgroundColor:'white',borderRadius:5}}>
                              <Text style={{color:'black'}}>ไม่มีรายการของบริการอื่นๆ</Text>
                            </View>
                        )}
                    />


            }

          </View>
        </ScrollView>
        <View style={{}}>


          {this.state.selected_room !== '' ?
              <TouchableOpacity style={{
                backgroundColor: Color.blue,
                height: 40,
                margin: 16,
                borderRadius: 5,
                justifyContent: 'center',
                alignItems: 'center',
              }}
                                onPress={() => {
                                  this.sendRepairService()
                                  // this.props.navigation.navigate('RepairConfirm')
                                }}>
                <Text style={{color: 'white'}}>{t('call_for_service')}</Text>
              </TouchableOpacity>
              :
              <Text></Text>
          }



        </View>
        <IndicatorLoading loadingVisible={this.state.isLoading}/>
      </ImageBackground>

    )
  }
}

const styles = StyleSheet.create({
  contentContainer: {
    paddingVertical: 0,
    flexGrow: 1,
  },
  button_style_repair: {
    height: 32,
    borderRadius: 5,
    width: 127,
    justifyContent: 'center',
    marginLeft: 10
  },
  button_style_other: {
    height: 32,
    borderRadius: 5,
    width: 127,
    justifyContent: 'center',
  },
})
