import React, {Component} from 'react'
import {ScrollView, View, FlatList, TouchableOpacity, Dimensions, Modal} from 'react-native'
import Image from 'react-native-fast-image'
import ImageBackground from 'react-native-fast-image'
import { WebView } from 'react-native-webview';
import Icon from 'src/components/Icon'
import ImageSliderz from 'react-native-image-slideshow'
import GetWidthHeightDevice from '../../components/GetWidthHeightDevice'
import {CustomButton} from '../../components/CustomButton'
import LinearGradient from 'react-native-linear-gradient';
import {BackgroundImage} from '../../components/BackgroundImage'
import Text from '../../components/Text';
import 'intl';
import 'intl/locale-data/jsonp/th-TH'
import {roomdetail} from '../../api/UserApi';
import ImageView from 'react-native-image-view';
import Carousel from 'react-native-snap-carousel'
import { itemWidth, sliderWidth } from '../../styles/SliderEntry.style'
import IndicatorLoading from '../../components/IndicatorLoading';
import { t } from '../../utils/i18n';

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

const injectScript = `
  (function () {
    window.onclick = function(e) {
      e.preventDefault();
      window.postMessage(e.target.href);
      e.stopPropagation()
    }
  }());
`;

class RoomDetailScreen extends Component {
  constructor(props) {
    super(props)
    this._onCarouselScroll = this._onCarouselScroll.bind(this)
    this.state = {
      isLoading: true,
      position: 0,
      room_detail: {},
      room_image: [],
      isImageView: false,
      select_image_index: 0
    }
  }

  componentDidMount() {
    this.getRoomDetail()
  }

  renderNativeItemImages = (item,index) => {
    return <TouchableOpacity
    onPressOut={() => {
      this.setState({
        select_image_index: index,
        isImageView: true
      })
    }}>
      <ImageBackground source={{uri: item.url}} style={styles.imgBg}>
        <LinearGradient colors={['rgba(0, 0, 0, 0)', '#000000']}>
          <View style={{padding: 15,}}>
            <Text style={styles.textNewsName}></Text>
            <View style={{flexDirection: 'row', marginTop: 5}}>
            </View>
          </View>
        </LinearGradient>
      </ImageBackground>
    </TouchableOpacity>
  }

  renderImage = ({item}) => {
    return <View style={{width: '100%',height: 200,backgroundColor:'blue'}}>
      <Image source={{uri: item.url}} style={{flex:1}} resizeMode={'contain'}/>
    </View>
  }

  getRoomDetail() {
    const {navigation} = this.props;
    const detail = navigation.getParam('item', 'NO ITEM');

    roomdetail(detail.id)
      .then(res => {
        if(res.ok){
          this.setState({
            isLoading: false,
            room_detail: res.data.data,
            room_image: res.data.image
          })
        }
      })
  }

  _onCarouselScroll(e) {
    const scrollX = e.nativeEvent.contentOffset.x
    this.setState({
      position: Math.ceil(scrollX / width)
    })
  }

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

  _keyExtractor = (item, index) => 'room_detail_' + index
  _keyExtractorImage = (item, index) => 'room_image_' + index

  render() {
    return (
      <LinearGradient colors={['#3AA40C', '#2C7C0B']} style={{
        flex: 1,
        width: null,
        height: null,
        resizeMode: 'cover'
      }}>
        <BackgroundImage>
            <View style={{flex: 1,}}>
              <View style={{}}>
                {/*    <ImageSliderz
                  dataSource={this.state.room_image}
                  position={this.state.position}
                  height={250}
                  scrollEnabled={true}
                  indicatorSelectedColor={'#8BC34A'}
                  indicatorColor={'rgba(255, 255, 255, 0.3)'}
                  onPositionChanged={position => this.setState({ position })} /> */}
                <FlatList
                  data={this.state.room_image}
                  renderItem={({item,index}) => this.renderNativeItemImages(item,index)}
                  horizontal={true}
                  showsHorizontalScrollIndicator={false}
                  pagingEnabled={true}
                  onScroll={this._onCarouselScroll}
                  extraData={this.state}
                  keyExtractor={this._keyExtractor}
                  style={{height: 200,}}
                />
                <View style={{
                  position: 'absolute',
                  bottom: 10,
                  width: '100%',
                  justifyContent: 'center',
                  flexDirection: 'row'
                }}>
                  {(this.state.room_image).map((item, i) => <View key={'dot_' + i} style={[{
                    width: 10,
                    height: 10,
                    borderRadius: 5,
                    backgroundColor: this.state.position == i ? '#269A21' : 'rgba(255,255,255,0.3)',
                    marginHorizontal: 4
                  }]}></View>)}
                </View>
                <LinearGradient colors={['rgba(0, 0, 0, 0)', '#000000']}>
                  <View style={{
                    position: 'absolute',
                    bottom: 10,
                    width: '100%',
                    justifyContent: 'center',
                    flexDirection: 'row'
                  }}>
                    {(this.state.room_image).map((item, i) => <View key={'view_dot_' + i} style={[{
                      width: 10,
                      height: 10,
                      borderRadius: 5,
                      backgroundColor: this.state.position == i ? '#269A21' : 'rgba(255,255,255,0.3)',
                      marginHorizontal: 4
                    }]}></View>)}
                  </View>
                </LinearGradient>
              </View>
              <View style={styles.margin_border}>
                <View style={{marginTop: 8}}>
                  <Text style={{fontSize: 18, color: 'white'}}>{this.state.room_detail.type_name}</Text>
                </View>
                <View style={{marginTop: 5}}>
                  <Text style={{fontSize: 14, color: 'white'}}>{this.state.room_detail.price} / {t('month')}</Text>
                </View>
                <View style={{marginTop: 5, flexDirection: 'row'}}>
                  <Icon name={'ic_location'} size={16} color={'rgba(255, 255, 255, 0.65)'}/>
                  <Text style={{
                    marginLeft: 3,
                    fontSize: 12,
                    color: 'rgba(255, 255, 255, 0.65)'
                  }}>{this.state.room_detail.project != null && this.state.room_detail.project.name}</Text>
                </View>
              </View>
              <View style={{flex: 1, padding: 16}}>
                <Text style={{fontSize: 16, color: 'white'}}> {t('detail')} </Text>
                <WebView
                  style={{
                    marginTop: 0,
                    backgroundColor: 'rgba(0,0,0,0)',
                    flex: 1,
                  }}
                  ref={(ref) => {
                    this.webview = ref;
                  }}
                  bounces={true}
                  // dataDetectorTypes={['link', 'phoneNumber']}
                  originWhitelist={['*']}
                  source={{
                    baseUrl: '',
                    html: `<div id="content_detail"><meta charset="UTF-8"> ${this.state.room_detail.detail} </div>`
                  }}

                  injectedJavaScript={injectScript}
                  onMessage={this.onMessage}
                />
              </View>
            </View>
            <TouchableOpacity style={{ padding:16 }}>
              <CustomButton style={styles.room_btn} title={t('book_room')}
                onPress={() => {
                  console.log('check send data --------------',this.state.room_detail);
                  this.props.navigation.navigate('RoomHeaderReservation',{room_detail: this.state.room_detail,room_image: this.state.room_image} )}} />
            </TouchableOpacity>
        </BackgroundImage>
        <Modal animationType="none"
          transparent={true}
          visible={this.state.isImageView}
          onRequestClose={() => {
            Alert.alert('Modal has been closed.');
          }}>
          <View style={{flex:1,backgroundColor:'#000000'}}>
            <View style={{alignItems:'flex-end'}}>
              <TouchableOpacity style={{height: 80,width: 80,justifyContent:'center',alignItems:'center'}} onPress={() => {this.setState({isImageView:false})}}>
                <Icon name='ic_add' size={36} color='white' style={{transform:[{rotate:'45deg'}]}}/>
              </TouchableOpacity>
            </View>
            <Carousel
                ref={(c) => { this._carousel = c }}
                data={this.state.room_image}
                renderItem={({ item }) =>
                <View style={{width: '100%',height: '100%'}}>
                  <Image source={{uri: item.url}} style={{flex:1}} resizeMode={'contain'}/>
                </View>
                }
                sliderWidth={sliderWidth}
                itemWidth={width}
                containerCustomStyle={{}}
                slideStyle={{ flex:1, justifyContent: 'center' }}
              />
          </View>
        </Modal>
        <IndicatorLoading loadingVisible={this.state.isLoading}/>
      </LinearGradient>
    )
  }
}

const styles = {
  container: {
    flex: 1,
    flexDirection: 'column',
    height: GetWidthHeightDevice.HeightDevice

  },
  image_background: {
    width: '100%',
  },
  margin_border: {
    padding: 15,
    borderBottomColor: 'white', borderWidth: 0.5,
    borderColor: 'transparent'
  },
  box_detail: {
    height: '100%'
  }, room_btn: {
    backgroundColor: '#145EB3',
    height: 40
  }, imgBg: {
    flex: 1,
    height: 200,
    width: width,
    justifyContent: 'flex-end'
  },
}

export default RoomDetailScreen
