import React, { Component } from 'react'
import {View, ScrollView, StyleSheet, Linking, Button, TouchableOpacity, Alert, Platform, Modal, ImageBackground} from 'react-native';
import Image from 'react-native-fast-image'
import { WebView } from 'react-native-webview';
import { Body, Badge, List, ListItem, Right, Title } from 'native-base'
import Icon from '../../components/Icon'
import Text from '../../components/Text';
import LinearGradient from 'react-native-linear-gradient';
import { BackgroundImage } from '../../components/BackgroundImage'
import { getNewsDetail } from '../../api/UserApi';
import IndicatorLoading from '../../components/IndicatorLoading';
import { t } from '../../utils/i18n'
import parseDateLocale from '../../utils/parseDateLocale';
import ImageView from 'react-native-image-view';
import {NavigationActions} from "react-navigation";
import Config from 'src/utils/Config'
import Carousel from "../room/RoomDetail";
import {sliderWidth} from "../../styles/SliderEntry.style";
import {connect} from "react-redux";
var uri = null;
const injectScript = `
  (function () {
    window.onclick = function(e) {
      e.preventDefault();
      window.postMessage(e.target.href);
      e.stopPropagation()
    }
  }());
`;

class NewsDetailScreen extends Component {
  constructor(props) {
    super(props)
    this.state = {
      isLoading: true,
      isImageViewVisible: false,
      content:'',
      news_id: this.props.navigation.getParam('news_id', 'NO ITEM'),
      news_detail:{}
    }
  }

  componentDidMount(){
    this.getNewsData()
  };


  /*componentWillUnmount() {
    if(this.props && this.props.navigation && this.props.navigation.state && this.props.navigation.state.params && this.props.navigation.state.params.getNotification){
      this.props.navigation.state.params.getNotification()
    }
  }*/

  getNewsData(){
    this.setState({
      isLoading: true
    })
    getNewsDetail(this.state.news_id)
    .then(res => {
      if(res.ok){
        if(res.data.data){
          this.setState({
            isLoading: false,
            news_detail: res.data.data
          })
        }else {
          console.log('ถูกยกเลิกเผยแพร่ข่าว')
          Alert.alert('',t('news_canceled'), [{
            text: t('ok'),
            onPress: () => {
              console.log('press')
              this.setState({
                isLoading: false,
                news_detail: {}
              })
            }
          }])
        }
      }else{
        Alert.alert('',t('news_canceled'), [{
          text: t('ok'),
          onPress: () => {
            this.setState({
              isLoading: false,
              news_detail: {}
            })
          }
        }])
        // alert('ถูกยกเลิกเผยแพร่ข่าว')
        // this.context.router.goBack()

      }
    })
  }

  render() {
    let source_webview = {};
    source_webview = {
      baseUrl: '',
      // uri: `${Config.API_BASE_URL_POWER_CONDO_PROD}/news/${this.state.news_id}/detail`,
      uri: `${this.props.server_mode === 'production' ? Config.API_BASE_URL_POWER_CONDO_PROD : Config.API_BASE_URL_POWER_CONDO_DEV}/news/${this.state.news_id}/detail`
    }

    // if(Platform.OS === 'android'){
    //   source_webview = {
    //     baseUrl: '',
    //     uri: `${Config.API_BASE_URL_POWER_CONDO_DEV}/news/${this.state.news_id}/detail`
    //   }
    // }else {
    //   source_webview = {
    //     baseUrl: '',
    //     html: `${this.state.news_detail && this.state.news_detail.style ? this.state.news_detail.style : ''}<div id="content_detail"><meta charset="UTF-8"> ${this.state.news_detail && this.state.news_detail.content ? this.state.news_detail.content : ""} </div>`
    //   }
    // }

    return (
      <LinearGradient colors={['#3AA40C', '#2C7C0B']} style={{
        flex: 1,
        width: null,
        height: null
      }}>
        <BackgroundImage>
          {
            Platform.OS === 'android' &&
            <ImageView
              images={[{source: {uri: this.state.news_detail != null && this.state.news_detail.url ? this.state.news_detail.url : '' }}]}
              imageIndex={0}
              isVisible={this.state.isImageViewVisible}
              animationType={'fade'}
              onClose={() => {this.setState({isImageViewVisible: false})}}
            />
          }
          <View>
            <TouchableOpacity onPress={() => {this.setState({isImageViewVisible: true})}}>
              <Image source={{ uri: this.state.news_detail != null && this.state.news_detail.url ? this.state.news_detail.url : '' }} style={styles.imgBg} />
            </TouchableOpacity>
          </View>
          <View style={{ backgroundColor: 'white', padding: 15 }}>
            <View style={{ flexDirection: 'row' }}>
              <Text style={{ color: '#00420A', fontSize: 16, }}>{this.state.news_detail != null && this.state.news_detail.title}</Text>
            </View>
            <View style={{ flexDirection: 'row', marginTop: 5 }}>
              <View style={{ width: '50%', flexDirection: "row", marginTop: 5 }}>
                <Icon name="ic_event_note" size={16} color="#00420A" />
                {
                  this.state.news_detail &&
                  <Text style={{ marginLeft: 5, color: '#00420A', fontSize: 12, }}>{parseDateLocale(this.state.news_detail.date)}</Text>
                }
              </View>
              <View style={{ width: '50%', flexDirection: "row", flex: 1, justifyContent: 'flex-end' }}>
                {this.state.news_detail && this.state.news_detail.is_new == true ? <Badge style={{ backgroundColor: '#FF9500', borderRadius: 50, paddingLeft: 10, paddingTop: 5 }}>
                  <Text style={{ fontSize: 12, color: 'white' }}>{this.state.news_detail.type === 'promotion' ? t('latest_promotion') : t('latest_news')} </Text>
                </Badge> : null}
              </View>
            </View>
          </View>
          <View style={{ padding:15, paddingBottom:0 }}>
            <Text style={{ color: 'white', fontSize: 16, }} >{t('detail')}</Text>
          </View>
          <WebView
            style={{
              margin:12,
              marginTop:0,
              backgroundColor: 'rgba(0,0,0,0)' ,
              flex: 1,
            }}
            originWhitelist={['*']}
            // source={{baseUrl: '', html: `${this.state.news_detail && this.state.news_detail.style ? this.state.news_detail.style : ''}<div id="content_detail"><meta charset="UTF-8"> ${this.state.news_detail && this.state.news_detail.content ? this.state.news_detail.content : ""} </div>` }}
            source={source_webview}
            ref={(ref) => { this.webview = ref; }}
            javaScriptEnabled={true}
            domStorageEnabled={true}
            onMessage={(event) => {
              if(event.nativeEvent.data){
                let data = JSON.parse(event.nativeEvent.data);
                if(data.video_id){
                  Linking.openURL(`https://youtube.com/embed/${data.video_id}`);
                }
              }
            }}

            /*onNavigationStateChange={(event) => {
              console.log('onNavigationStateChange >>>>>> ',event);
              if (event.url.startsWith("http")) {
                this.webview.stopLoading();
                this.webview.goBack();
                Linking.openURL(event.url);
              }
            }}*/
          />
        </BackgroundImage>
        {
          Platform.OS === 'ios' &&
          <Modal animationType="none"
                 transparent={true}
                 visible={this.state.isImageViewVisible}
                 onRequestClose={() => {
                   Alert.alert('Modal has been closed.');
                 }}>

            <View style={{flex:1,backgroundColor: 'rgba(0,0,0,.9)', justifyContent: 'center', alignItems: 'center', width: '100%'}}>
              <TouchableOpacity style={{height: 80,width: 80, position: 'absolute', zIndex: 1000, right: -25, top: '6%'}}
                                onPress={() => {this.setState({isImageViewVisible:false})}}
              >
                <Icon name='ic_add' size={36} color='white' style={{transform:[{rotate:'45deg'}]}}/>
              </TouchableOpacity>
              <View style={{width: '90%', justifyContent: 'center', height: '100%'}}>
                <Image source={{ uri: this.state.news_detail != null && this.state.news_detail.url ? this.state.news_detail.url : '' }}
                       style={{flex: 1}}
                       resizeMode={'contain'}
                />
              </View>
            </View>
          </Modal>
        }

        <IndicatorLoading loadingVisible={this.state.isLoading}/>
      </LinearGradient>
    )
  }
}

const mapStateToProps = state => {
  return {
    server_mode: state.app.server_mode
  }
}

export default connect(mapStateToProps)(NewsDetailScreen)

const styles = StyleSheet.create({
  imgBg: {
    width: '100%',
    height: 200,
    paddingTop: 80
  },
  textNews: {
    backgroundColor: '#0D8890',
    width: 60,
    color: '#FFFFFF',
    borderRadius: 5,

    textAlign: 'center',
    fontSize: 12
  },
  backgroundImage: {
    flex: 1,
    width: null,
    height: null,
    resizeMode: 'cover'
  }
})
