import React, {Component} from 'react'
import {Accordion, 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 {getRoomUser, 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 = 'rgba(255, 255, 255, 0.45)'
export default class RepairService extends Component {
  constructor(props) {
    super(props)

    this.state = {
      isLoading: false,
      refreshing: false,
      activePage: 0,
      repair_list:[],
      isSelectRepair: true,
      isSelectOther: false,
      indexItem: [],
      selectServiceIndex: 0,
      selectServiceId: [],
      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 = () => {
      getRoomUser()
        .then(res => {
          if(res.ok){
            this.setState({
              room_list: res.data.data,
              selected_room: res.data.data && res.data.data.length > 0 && res.data.data[0].rooms_id ? res.data.data[0].rooms_id : '',
              selected_project:  res.data.data && res.data.data.length > 0 && res.data.data[0].project_name ? res.data.data[0].project_name : '',
            }, () => {
              this.getServicesListByType(2)
            })
          }
        })
  };

  switchSelected(typeName){
    if(typeName == 'repair' && this.state.isSelectOther){
      Alert.alert(null, 'คุณต้องการเปลี่ยนไปเลือกใช้บริการแจ้งซ่อมหรือไม่ ?', [
        {text: t('cancel'), style: 'cancel'},
        {text: t('ok'),
          onPress: () => {
          this.setState({
            isSelectRepair: true,
            isSelectOther: false,
            selectServiceId: [],
            selectService: [],
          }, () => {
            this.getServicesListByType(2)
          })}
        }
      ])
    }else if(typeName == 'other' && this.state.isSelectRepair){
      Alert.alert(null, 'คุณต้องการเปลี่ยนไปเลือกบริการอื่นๆ หรือไม่ ?', [
        {text: t('cancel'), style: 'cancel'},
        {text: t('ok'),
          onPress: () => {
            this.setState({
              isSelectRepair: false,
              isSelectOther: true,
              selectServiceId: [],
              selectService: []
            }, () => {
              this.getServicesListByType(1)
            })
          }
        }
      ])
    }
  }

  getServicesListByType(id){
    let services = [];
    getServicesType(id)
      .then(res => {
        if(res.ok){
          if(this.state.selected_project !== ''){
            services = res.data.data.filter(obj => {return obj.project_name == this.state.selected_project})
          }
        }

        this.setState({
          repair_list : services
        })
      })
  }

  sendRepairService(){
    let params = {
      date: moment().format('YYYY-MM-DD'),
      time: moment().format('HH:MM:SS'),
      repairs: this.state.selectService,
      rooms: this.state.room_list.filter(room => {return room.rooms_id === this.state.selected_room} )
      // service_fee: this.state.selectService.service_fee
    }

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

  }

  setCheckIndex(item){
    let indexSelected = this.state.selectServiceId.indexOf(item.id);
    if(indexSelected > -1){
      this.state.selectServiceId.splice(indexSelected, 1);
      this.state.selectService.splice(indexSelected, 1);
    }else {
      this.state.selectServiceId.push(item.id)
      this.state.selectService.push(item)
    }

    this.forceUpdate();
  }

  _renderContent = (item,index) => {
    return <TouchableOpacity style={{borderBottomWidth: 2,borderColor:'#F4F4F4',backgroundColor:'white'}}
      onPress={() => {
      this.setCheckIndex(item)
      }}>
      <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.selectServiceId.indexOf(item.id) > -1 &&
          <View style={{width: 64,justifyContent:'center',alignItems:'center'}}>
            <Image source={require('../../../assets/images/check.png')} style={{width:32, height:32}}/>
          </View>
        }
      </View>
    </TouchableOpacity>
  }

  renderNativeItemImages = (item) => {
    return <View style={{width: width, alignItems: 'center', paddingTop: 10, paddingBottom: 40,height: 177,}}>
      <View style={{width: '65%', 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 }}>{t('room')} {item.room_no}</Text>
            <Text style={{ color: 'rgba(255, 255, 255, 0.65)', fontSize: 14 }}>{t('project') + item.project_name}</Text>
          </View>

            <View style={{height:24,backgroundColor: '#FF2D55',justifyContent:'center',alignItems:'center'}}>
              <Text style={{ fontSize: 12, color: 'white'}}>มีการแจ้งใช้บริการ {this.state.selectServiceId.length} รายการ</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


  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%', flex: 1, backgroundColor:'#EEFFD7'}}>
        <View>
          <FlatList
            data={this.state.room_list}
            renderItem={({ item }) => this.renderNativeItemImages(item)}
            horizontal={true}
            onScroll={this._onCarouselScroll}
            pagingEnabled={true}
            extraData={this.state}
            keyExtractor={this._keyExtractor}
            // onScrollEndDrag={this.roomFilter(this.state.activePage)}
          />
          <View style={{ position: 'absolute', bottom: 10, width: '100%', justifyContent: 'center', flexDirection: 'row' }}>
            { this.state.room_list?.length > 0 && this.state.room_list.map((item, i) => <View key={'sum_repair'+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.isSelectRepair ? btnActiveColor : btnUnActiveColor,borderTopRightRadius:0,borderBottomRightRadius:0}]}
                        onPress={() => {this.switchSelected('repair')}}>
                  <Text style={locale() === "my" ? { fontSize: 6, color: this.state.isSelectRepair ? '#FFFFFF' : '#000000' } : 
                              locale() === "en" ?  { fontSize: 11, color: this.state.isSelectRepair ? '#FFFFFF' : '#000000' } :
                              { fontSize: 14, color: this.state.isSelectRepair ? '#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" ? { fontSize: 12, color: this.state.isSelectOther ? '#FFFFFF' : '#000000' } :
                   locale() === "en" ? { fontSize: 11, color: this.state.isSelectOther ? '#FFFFFF' : '#000000' } :
                   { fontSize: 13, 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>
        }

        {
          this.state.selected_room !== '' ?
            <View style={{ flex: 1 }}>
              <View style={{ flex: 0.8 }}>
                <ScrollView
                  contentContainerStyle={styles.contentContainer}
                >
                  <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'}}>{this.state.isSelectRepair ? 'ไม่มีรายการของแจ้งซ่อม' : 'ไม่มีรายการของบริการอื่นๆ'}</Text>
                      </View>
                    )}
                  />
                </ScrollView>
              </View>
              <View style={{ flex: 0.2, backgroundColor: 'white' }}>
                <TouchableOpacity style={[{
                  height: 40,
                  margin: 16,
                  borderRadius: 5,
                  justifyContent: 'center',
                  alignItems: 'center',
                }, this.state.selectServiceId.length === 0 ? {backgroundColor: Color.gray_half} : {backgroundColor: Color.blue}]}
                                  onPress={() => {
                                    this.sendRepairService()
                                  }}
                                  disabled={this.state.selectServiceId.length === 0}
                >
                  <Text style={{color: 'white'}}>{t('call_for_service')}</Text>
                </TouchableOpacity>
              </View>
            </View>
            :
            <View></View>
        }
        <IndicatorLoading loadingVisible={this.state.isLoading}/>
      </ImageBackground>

    )
  }
}

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