import React, { Component } from 'react'
import { Dimensions, RefreshControl, ScrollView, TouchableOpacity, View } from 'react-native'
import Image from 'react-native-fast-image'
import ImageBackground from 'react-native-fast-image'
import { CustomButton } from '../../components/CustomButton'
import LinearGradient from 'react-native-linear-gradient'
import Carousel from 'react-native-snap-carousel'
import Text from '../../components/Text'
import SliderEntry from '../../components/SliderEntry'
import styles_C from '../../styles/index.style'
import { itemWidth, sliderWidth } from '../../styles/SliderEntry.style'
import SearchableDropdown from '../../components/SearchableDropDown'
import { project, room } from '../../api/UserApi'
import 'intl'
import 'intl/locale-data/jsonp/th-TH'
import IndicatorLoading from '../../components/IndicatorLoading';
//import SearchableDropdown from 'react-native-searchable-dropdown';
import { t , locale } from 'src/utils/i18n'

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


class RoomScreen extends Component {

  constructor(props) {
    super(props)
    this.state = {
      isLoading: true,
      refreshing: false,
      e: SLIDER_1_FIRST_ITEM,
      slider1ActiveSlide: 0,
      project_snap_index:0,
      project_select_id:0,
      zone_id: this.props.navigation.getParam('zone_id','NO ID'),
      items: [
        {
          id: 1,
          name: 'ยังไม่มีข้อมูล',
        },
      ],
      rooms: []
    }
    this._renderItem = this._renderItem.bind(this)
    this.initData = this.initData.bind(this)
  }

  componentDidMount() {
    this.initData()
  }

  initData(){
    Promise.all([
      this.getProjectList(),
    ])
    .then(() => {
      this.getRoomList(this.state.project_select_id)
      this.setState({ refreshing: false })
    })
  }

  _onRefresh = () => {
    this.setState({ refreshing: true })
    this.initData()
    this.setState({
      project_snap_index:0,
      project_select_id:0
    })
    this.forceUpdate()
  }

  async getProjectList(){
    return project()
    .then(async res => {
      if(res.ok){
        let filterProject = res.data.data.filter(project => project.zone_id === this.state.zone_id)
        console.log('check project in zone '+this.state.zone_id)
        this.setState({
          items: filterProject,
          project_select_id: filterProject[0].id
        },() => {
          console.log('check project ------------> '+this.state.items)
        })
      }
    })
  }

  async getRoomList(project_id){
    this.setState({
      isLoading: true,
      refreshing: false
    })
    return await room(project_id)
    .then(res => {
      if(res.ok){
        return this.setState({
          rooms: res.data.data
        })
      }
    })
    .then(() => {
      this.setState({
        isLoading: false
      })
    })
  }

  _keyExtractor = (item, index) => index

  _renderItem({ item, index }) {
    return (
      <TouchableOpacity style={{flex:1,justifyContent:'center'}} onPress={() => {this.props.navigation.navigate('RoomDetail', {item: item})}}>
        <View style={{
              alignItems: 'center',
              borderColor: 'white',
              // height: '100%',
              width:'100%',
              borderWidth: 1,
              backgroundColor: '#ffffff33',
              borderRadius: 10,
              padding: 15,
              justifyContent:'center',
              alignSelf:'center'}}>
          <View style={{width: 190,height: 190,justifyContent:'center',alignItems:'center'}}>
            <Image style={[styles.image_style, { width: 160, height: 160 }]} source={{ uri: item.url }} />
          </View>
          <View style={{alignItems: 'center'}}>
            <Text ellipsizeMode={'tail'} numberOfLines={1} style={{ color: 'white', fontSize: 16 }}>{item.name}</Text>
            <Text style={{ color: 'white', fontSize: 16 }}>{item.price}</Text>
            <Text style={{ fontSize: 14, color: 'white' }}>{t('baht_month')}</Text>
          </View>
          <TouchableOpacity style={{marginTop:5,paddingHorizontal:15,height: 40,backgroundColor: '#145EB3',borderRadius:8,justifyContent:'center'}}
                onPress={() => {this.props.navigation.navigate('RoomDetail', {item: item})}}>

            <Text style={locale() == "my" ? {color:'white',fontSize:10} :  {color:'white',fontSize:16}}>{t('view_details')}</Text>
          </TouchableOpacity>
        </View>
      </TouchableOpacity>
    )
  }

  format_price(n) {
    return new Intl.NumberFormat('th-TH', {maximumSignificantDigits: 3}).format(n)
  }

  _search(project_id) {
    room(project_id)
    .then(res => {
      this.setState({
        rooms: res.data.data
      })
    })
  }

  _renderItemWithParallax({ item, index }, parallaxProps) {
    return (
      <SliderEntry
        data={item}
        even={(index + 1) % 2 === 0}
        parallax={true}
        parallaxProps={parallaxProps}
      />
    )
  }

  render() {
    return (
      <LinearGradient colors={['#3AA40C', '#2C7C0B']} style={{
        flex: 1,
        width: null,
        height: null,
        resizeMode: 'cover'
      }}>
        <ImageBackground source={require('../../../assets/images/map.png')} style={styles.backgroundImage}>
          <View style={{ flex: 1 }}>
            <View style={styles.box_search}>
              <SearchableDropdown
                //onTextChange={text => alert(text)}
                onItemSelect={item => {
                  let findIndex = this.state.items.findIndex(project => item.id == project.id)
                  this._carousel.snapToItem(findIndex)
                  this._search(item.id)
                }}
                containerStyle={{ padding: 5, flexDirection: 'row' }}
                textInputStyle={styles.room_screen_search}
                itemStyle={{
                  padding: 10,
                  backgroundColor: '#ffffff',
                  borderColor: 'rgba(0, 0, 0, 0.25)',
                  borderWidth: 0.5,

                }}
                itemTextStyle={{ color: '#269A21' }}
                itemsContainerStyle={{ maxHeight: 170, backgroundColor: 'white' }}
                items={this.state.items}
                placeholder={t('search_project')}
                resetValue={false}
                underlineColorAndroid="transparent"
                placeholderTextColor={'#269A21'}
              />
            </View>
            <ScrollView contentContainerStyle={styles.contentContainer} showsVerticalScrollIndicator={false}
                        refreshControl={
                          <RefreshControl
                            refreshing={this.state.refreshing}
                            onRefresh={() => {
                              this._onRefresh()
                              this._carousel.snapToItem(0)
                              this._slider1Ref.snapToItem(0)
                            }}
                          />
                        }>
              <View style={{ flex:1, alignItems: 'center'}}>
              <Carousel
                    lockScrollWhileSnapping={true}
                    ref={c => this._slider1Ref = c}
                    data={this.state.rooms}
                    renderItem={this._renderItem}
                    sliderWidth={sliderWidth}
                    itemWidth={itemWidth}
                    hasParallaxImages={true}
                    firstItem={SLIDER_1_FIRST_ITEM}
                    inactiveSlideOpacity={0.5}
                    loop={false}
                    loopClonesPerSide={0}
                    autoplay={false}
                    autoplayDelay={500}
                    autoplayInterval={3000}
                    // containerCustomStyle={{backgroundColor:'red'}}
                    // contentContainerCustomStyle={{backgroundColor:'black'}}
                    onSnapToItem={(index) => this.setState({ slider1ActiveSlide: index })}
                  />
              </View>
              {this.state.rooms != null && this.state.rooms != '' ?
              <View>
              </View> : <View style={{ flex: 1, marginTop: 20 }}>
                <View style={{ backgroundColor: 'rgba(0, 0, 0, 0.4)', borderRadius: 8, padding: 15, }}>
                  <Text style={{ textAlign: 'center', color: 'white' }}>ยังไม่มีข้อมูลประเภทห้อง</Text>
                </View>
              </View>}
            </ScrollView>
            {/* Bottom View */}
            <View style={{ justifyContent: 'center',paddingTop:5 }}>
              <Carousel
                ref={(c) => { this._carousel = c }}
                data={this.state.items}
                renderItem={({ item }) =>
                  <View style={{ backgroundColor: '#ffffff33', paddingVertical:10, borderWidth: 2, borderColor: 'white', borderRadius: 5, justifyContent: 'center', alignItems: 'center' }}>
                    <Text style={{ color: 'white', fontSize: 16 }}>{item.name}</Text>
                    {/* <TouchableOpacity style={{marginTop:10,backgroundColor:'#145EB3',height:30,width:100,borderRadius: 5,justifyContent: 'center', alignItems: 'center' }}>
                      <Text style={{ color: 'white', fontSize: 16 }}>ดูโครงการ</Text>
                    </TouchableOpacity> */}
                  </View>
                }
                sliderWidth={sliderWidth}
                itemWidth={itemWidth+50}
                containerCustomStyle={{}}
                slideStyle={{ justifyContent: 'center' }}
                onSnapToItem={(index) => {
                  this.setState({
                    project_snap_index:index,
                  },() => {
                    this.setState({
                      project_select_id: this.state.items[this.state.project_snap_index].id
                    },() => {
                      this.getRoomList(this.state.project_select_id)
                      this._slider1Ref.snapToItem(0)
                    })
                  })}}
              />
              <View style={{position:'absolute',height:40,width:'100%',flexDirection: 'row',alignItems: 'center',justifyContent: 'space-between',paddingHorizontal: 15}}>
                <TouchableOpacity style={{width: 40,height: 40,alignItems: 'center',justifyContent: 'center'}} onPress={() => { this._carousel.snapToPrev() }}>
                  <Text style={{color:'white',fontSize:30}}>{'<'}</Text>
                </TouchableOpacity>
                <TouchableOpacity style={{width: 40,height: 40,alignItems: 'center',justifyContent: 'center'}} onPress={() => { this._carousel.snapToNext() }}>
                  <Text style={{color:'white',fontSize:30}}>{'>'}</Text>
                </TouchableOpacity>
              </View>
            </View>
            <TouchableOpacity style={{margin: 10, paddingVertical: 5, height: 70, paddingHorizontal: 30, backgroundColor: '#00000080', borderRadius: 5, justifyContent: 'center', alignItems: 'center' }}
            onPress={() => { this.state.items[this.state.project_snap_index].news_link != null && this.props.navigation.navigate('NewsDetail', {news_id: this.state.items[this.state.project_snap_index].news_link})}}>
              <Text style={{ color: 'white', fontSize: 14, textAlign:'center'}}>{t('phone')}: {this.state.items[this.state.project_snap_index].telephone}</Text>
              <Text style={{ color: 'white', fontSize: 14, textAlign:'center'}}>{t('address')}: {this.state.items[this.state.project_snap_index].address}</Text>
            </TouchableOpacity>
          </View>
        </ImageBackground>
        <IndicatorLoading loadingVisible={this.state.isLoading}/>
      </LinearGradient>
    )
  }
}

const styles = {
  backgroundImage: {
    flex: 1,
    width: null,
    height: null,
    resizeMode: 'center'
  },
  container: {
    flex: 1
  },
  room_screen_search: {
    color: '#269A21',
    height: 40,
    borderWidth: 1,
    borderColor: 'rgba(0,0,0,0)',
    width: '100%',
  },
  room_border: {
    alignItems: 'center',
    borderColor: 'white',
    borderWidth: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.8)',
    width: 220,

    marginBottom: 5,
    marginTop: 10,
    borderRadius: 5,
    padding: 15
  },
  image_style: {
    borderColor: 'white',
    borderWidth: 5,
    borderRadius: 80,
    width: '100%',
    height: '100%',
    backgroundColor: 'black'
  },
  button_reservation: {
    backgroundColor: '#145EB3',
    height: 40,
    borderRadius: 8
  },
  box_search: {
    width: '100%',
    flexDirection: 'row',
    display: 'flex',
    marginTop: 10,

    paddingLeft: 10,
    paddingRight: 10
  },
  contentContainer: {
    paddingHorizontal: 15,
    flex:1,
  }
}

export default RoomScreen
