import React, { Component } from 'react'
import {View, ScrollView, StyleSheet, Linking, Button, TouchableOpacity, Alert} 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 ImageView from 'react-native-image-view';
import {NavigationActions} from "react-navigation";
var uri = null;
const injectScript = `
  (function () {
    window.onclick = function(e) {
      e.preventDefault();
      window.postMessage(e.target.href);
      e.stopPropagation()
    }
  }());
`;

export default 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){
        this.setState({
          isLoading: false,
          news_detail: res.data.data
        })
      }else{
        this.setState({
          isLoading: false,
          news_detail: [
            {
              title: '',
              content: '',
              style: '',
              is_new: true,
              date:'',
              url:'',
            }
            ],

        })
        Alert.alert('','ถูกยกเลิกเผยแพร่ข่าว')
        // alert('ถูกยกเลิกเผยแพร่ข่าว')
        // this.context.router.goBack()

      }
    })
  }

  render() {
    return (
      <LinearGradient colors={['#3AA40C', '#2C7C0B']} style={{
        flex: 1,
        width: null,
        height: null
      }}>
        <BackgroundImage>
          <ImageView
            images={[{source: {uri: this.state.news_detail != null && this.state.news_detail.url }}]}
            imageIndex={0}
            isVisible={this.state.isImageViewVisible}
            animationType={'fade'}
          />
          <View>
            <TouchableOpacity onPress={() => {this.setState({isImageViewVisible: true})}}>
              <Image source={{ uri: this.state.news_detail != null && 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.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" />
                <Text style={{ marginLeft: 5, color: '#00420A', fontSize: 12, }}>{this.state.news_detail.date}</Text>
              </View>
              <View style={{ width: '50%', flexDirection: "row", flex: 1, justifyContent: 'flex-end' }}>
                {this.state.news_detail.is_new == true ? <Badge style={{ backgroundColor: '#FF9500', borderRadius: 50, paddingLeft: 10, paddingTop: 5 }}>
                  <Text style={{ fontSize: 12, color: 'white' }}>{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.style}<div id="content_detail"><meta charset="UTF-8">`+this.state.news_detail.content+'</div>' }}
            ref={(ref) => { this.webview = ref; }}
            javaScriptEnabled={true}
            domStorageEnabled={true}
            // onShouldStartLoadWithRequest={(navState)=>{ //open external browser for android
            //   console.log('onShouldStartLoadWithRequest >>>>>> ',navState);
            //   Linking.openURL(navState.url)
            //   return false;
            // }}

            onNavigationStateChange={(event) => {
              console.log('onNavigationStateChange >>>>>> ',event);
              if (event.url.startsWith("http")) {
                this.webview.stopLoading();
                this.webview.goBack();
                Linking.openURL(event.url);
              }
            }}
          />
        </BackgroundImage>
        <IndicatorLoading loadingVisible={this.state.isLoading}/>
      </LinearGradient>
    )
  }
}

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

    textAlign: 'center',
    fontSize: 12
  }
})
