import React from 'react';
import TitleBar from '../../components/titleBar';
import { colors } from '../../assets/styles/colors-theme';
import {
  SafeAreaView,
  Text,
  Image,
  View,
  ScrollView,
  TouchableHighlight,
  TouchableOpacity,
  TextInput,
  Share,
  Linking,
  StyleSheet,
  BackHandler
} from 'react-native';
var _ = require('lodash');
import ImageSwiper from '../../components/imageSwiper'
import GallerySwiper from 'react-native-gallery-swiper';
import Rating from '../../components/rating';
import { inject, observer } from 'mobx-react';
import HTMLView from 'react-native-htmlview';
import { width, height } from '../../services/screen';
import CustomLoginButton from '../../components/customLoginButton';
import CustomSmallButton from '../../components/customSmallButton';
import Toast, { DURATION } from 'react-native-easy-toast';
import Rank from '../../components/rank';
import Icon from 'react-native-vector-icons/dist/Ionicons';
import FeatherIcon from 'react-native-vector-icons/dist/Feather';
import { getStatusBarHeight } from 'react-native-status-bar-height';
import MaterialCommunityIcons from 'react-native-vector-icons/dist/MaterialCommunityIcons';
import { observable, action } from 'mobx';
import { images } from '../../assets/images/imageIndex';
import Mostcheaplist from '../../components/mostcheaplist';
import Menu, {
  MenuProvider,
  MenuTrigger,
  MenuOptions,
  MenuOption,
  renderers,
} from 'react-native-popup-menu';
const { SlideInMenu } = renderers;
Icon.loadFont();
FeatherIcon.loadFont();
MaterialCommunityIcons.loadFont();
@inject('appStore')
@observer
export default class ProductsDetails extends React.Component {
  @observable
  catalogue = [];
  @observable
  data = this.props.route.params.data;
  @observable
  imageData = [];
  @observable
  origin = '';
  @observable
  qry = 1;
  @observable
  showWriteComment = false;
  @observable
  showComment = true;
  @observable
  commentPage = 1;
  @observable
  productComment = [];
  @observable
  review = {
    //  product_id: null,
    review: '',
    //  reviewer: '',
    //  reviewer_email: '',
    rating: 3,
    // status: 'hold',
  };
  constructor(props) {
    super(props);
    this.store = props.appStore;
    this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
  }
  async componentDidMount() {
    console.log(this.data);
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
  }
  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);

  }

  handleBackButtonClick() {
    this.props.navigation.goBack();
    return true
  }


  commentAction() {
    if (this.review.review == '') {
      this.refs.toast.show(this.store.text.pleaseEnterReview);
    } else {
      this.review.product_id = this.data.id;
      this.review.reviewer = this.store.loginUserData.data.display_name;
      this.review.reviewer_email = this.store.loginUserData.data.email;
      this.store.postComment(this.data.id, _.cloneDeep(this.review), this);
      this.review = {
        product_id: null,
        review: '',
        reviewer: '',
        reviewer_email: '',
        rating: 3,
        status: 'hold',
      };
      this.showWriteComment = false;
    }
  }

  async descHandler() {
    // var pToBr = await desc.replaceAll('<p>', '<br>')
    // pToBr =  await pToBr.replaceAll('</p>', '</br>')
    // console.log(pToBr)
    // return pToBr
    this.data.desc = await this.data.desc.replaceAll('<p>', '<br>')
    this.data.desc = await this.data.desc.replaceAll('</p>', '</br>')
    console.log(this.data.desc)
  }

  comments(items) {
    return (
      <View>
        <Text style={{ fontSize: 14, color: colors.mainColor }}>
          {items.name}
        </Text>
        <View
          style={{ flexDirection: 'row', marginTop: 3, alignItems: 'center' }}>
          <Text style={{ fontSize: 12, marginTop: 2 }}>
            {this.store.text.rating + '：   '}
          </Text>
          <Rank ranking={parseFloat(items.rating)} />
        </View>
        <View style={{ flexDirection: 'row', marginTop: 5, width: width - 60 }}>
          <Text style={{ fontSize: 12 }}>{this.store.text.review + '：  '}</Text>
          <Text style={{ fontSize: 12, width: width - 100 }}>
            {items.review}
          </Text>
        </View>

        <View
          style={{
            height: 1,
            width: width - 60,
            backgroundColor: colors.lineColor,
            marginTop: 20,
            marginBottom: 20,
          }}
        />
      </View>
    );
  }

  showshowWriteCommentAction() {
    if (this.store.logined) {
      this.showWriteComment = !this.showWriteComment;
    } else {
      this.refs.toast.show(this.store.text.pleaseLogin);
    }
  }

  renderComments() {
    if (this.productComment.length > 0) {
      return this.productComment.map((items, index) => {
        console.log(items.reviewer);
        return this.comments(items);
      });
    } else {
      return <View />;
    }
  }

  async componentWillMount() {
    this.data.images.map((items, index) => {
      var data = {
        uri: items.imageURL,
      };
      this.imageData.push(data);
    });
    // await this.originHandler();

    // (this.productComment = this.store.getComment(
    //   this.data.id,
    //   this.commentPage,
    //   this,
    // )),
    this.store.getComment(this.data.id, this.commentPage, this);
    console.log(this.productComment);
  }

  async originHandler() {
    if (this.data.attributes.length > 0) {
      await this.data.attributes.map(async (items, index) => {
        if (items.name === 'origin') {
          console.log(items.options[0]);
          this.origin = items.options[0];
        } else {
          this.origin = 'N/A';
        }
      });
    } else {
      this.origin = 'N/A';
    }
  }

  renderStar() {
    var whiteStar = 0;
    var yelloStar = 0;
    var whitestarView = [];
    var yellowStarView = [];

    if (this.review.rating >= 5) {
      yelloStar = 5;
    } else {
      whiteStar = 5 - this.review.rating;
      yelloStar = 5 - whiteStar;
    }
    for (var i = 1; i <= yelloStar; i++) {
      var value = i;

      yellowStarView.push(i);
    }
    for (var i = 1; i <= whiteStar; i++) {
      var value = i;

      whitestarView.push(this.review.rating + i);
    }
    return (
      <View style={{ flexDirection: 'row', marginTop: 2 }}>
        {yellowStarView.map((items, index) => {
          return (
            <TouchableOpacity
              style={{ marginRight: 3 }}
              onPress={() => {
                console.log(items);
                this.review.rating = items;
                // console.log(this.review.rating);
              }}>
              <MaterialCommunityIcons
                name="star"
                color={colors.mainColor}
                size={20}
              />
            </TouchableOpacity>
          );
        })}
        {whitestarView.map((items, index) => {
          return (
            <TouchableOpacity
              style={{ marginRight: 3 }}
              onPress={() => {
                console.log(items);
                this.review.rating = items;
                // console.log(this.review.rating);
              }}>
              <MaterialCommunityIcons
                name="star-outline"
                color={colors.mainColor}
                size={20}
              />
            </TouchableOpacity>
          );
        })}
      </View>
    );
  }

  share() {
    Share.share({
      message:
        'pure mall',
      title: 'Pure Mall',
      url: 'http://onelink.to/3nqphw',
    });
  }

  @action
  clickstarAction(value) {
    this.review.rating = value;
  }

  renderOriPrice() {
    if (this.data.hasOwnProperty('oriPrice')) {
      if (this.data.oriPrice > this.data.price) {
        return (
          <Text
            style={{
              fontSize: 18,
              color: 'black',
              textDecorationLine: 'line-through'
            }}>
            {this.store.priceHandler(this.data.oriPrice)}
          </Text>
        )
      }
    } else {

    }
  }


  async addFavouriteAction() {
    if (
      (await this.store.favorite.findIndex(
        element => element.id == this.data.id,
      )) != -1
    ) {
      this.refs.toast.show(this.store.text.alreadyExistsInMyList);
    } else {
      console.log('addFavourite');
      this.store.addFavouritePost(this.data, this);
    }
  }

  renderStockStatus() {
    if (this.data.stock_quantity > 0) {
      return this.store.text.instock;
    } else {
      return this.store.text.outOfStock;
    }
  }

  returnContent(content) {
    const regex = /(<([^>]+)>)/gi;
    return content.replace(regex, '');
  }

  menuSelection(which) {
    if (which == '1') {
      Linking.canOpenURL('https://puremall.com.hk/tnc.html').then(
        supported => {
          if (supported) {
            Linking.openURL('https://puremall.com.hk/tnc.html');
          } else {
            console.log(
              "Don't know how to open URI: " +
              response.data.wechat.qr_code_url,
            );
          }
        })
    } else {
      Linking.canOpenURL('https://puremall.com.hk/privacy.html').then(
        supported => {
          if (supported) {
            Linking.openURL('https://puremall.com.hk/privacy.html');
          } else {
            console.log(
              "Don't know how to open URI: " +
              response.data.wechat.qr_code_url,
            );
          }
        })
    }

  }

  render() {
    return (
      <MenuProvider
        style={{
          flex: 1,
          backgroundColor: colors.bgc,
        }}>
        <ScrollView style={{ flex: 1 }}>
          <View style={{ alignItems: 'center', marginBottom: 30 }}>
            <View style={styles.naviBar}>
              <View style={[styles.barAreaView]}>
                <TouchableOpacity
                  style={{
                    flex: 0.2,
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}
                  onPress={() => {
                    this.props.navigation.goBack();
                  }}>
                  <Icon name="ios-arrow-back" color={'black'} size={40} />
                </TouchableOpacity>
                <View
                  style={{
                    flex: 0.8,
                    justifyContent: 'center',
                  }}>
                  <Text style={{ fontSize: 22, fontWeight: '800' }}>
                    {this.data.categories[0].name}
                  </Text>
                </View>
                <View
                  style={{
                    flex: 0.2,
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}>
                  <Menu
                    name="select"
                    renderer={SlideInMenu}
                    onSelect={value => {
                      this.menuSelection(value);
                    }}>
                    <MenuTrigger>
                      <MaterialCommunityIcons name="dots-horizontal" size={30} />
                    </MenuTrigger>
                    <MenuOptions
                      customStyles={{
                        optionText: {
                          margin: 5,
                          color: 'white',
                          fontSize: 15,
                        },
                        optionWrapper: {
                          backgroundColor: colors.mainColor,
                          alignItems: 'center',
                        },
                      }}>
                      <MenuOption value={'1'} text={this.store.text.regulations} />
                      <MenuOption value={'2'} text={this.store.text.refunds} />
                    </MenuOptions>
                  </Menu>
                </View>
              </View>
            </View>

            {this.data.images.length > 0 ? (
              // <GallerySwiper
              //   style={{ width: 250, height: 250, marginTop: 20 }}
              //   images={this.imageData}
              //   enableResistance={false}
              //   removeClippedSubviews={false}
              // />
              <ImageSwiper images={this.imageData} navigation={this.props.navigation} />
            ) : (
                <View
                  style={{
                    width: 250,
                    height: 250,
                    marginTop: 20,
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}>
                  <MaterialCommunityIcons
                    name="image-remove"
                    size={50}
                    color={colors.mainColor}
                  />
                  <Text style={{ color: colors.mainColor }}>No Image Yet</Text>
                </View>
              )}

            <View
              style={{
                width: width - 60,
                marginLeft: 30,
                marginTop: 20,
                marginRight: 30,
                flexDirection: 'row',
              }}>
              <View style={{ flex: 0.7, justifyContent: 'center' }}>
                <Text
                  numberOfLines={2}
                  style={{
                    fontWeight: 'bold',
                    fontSize: 20,
                  }}>
                  {this.data.name}
                </Text>
              </View>
              <View
                style={{
                  flex: 0.3,
                  alignItems: 'center',
                  flexDirection: 'row',
                }}>
                <TouchableOpacity
                  style={styles.circle}
                  onPress={() => {
                    this.share();
                  }}>
                  <MaterialCommunityIcons name="share" size={20} />
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.circle}
                  onPress={() => {
                    this.addFavouriteAction();
                  }}>
                  <MaterialCommunityIcons name="heart-outline" size={20} />
                </TouchableOpacity>
              </View>
              {/* origin and tag */}
              {/* <View style={{marginTop: 5, flexDirection: 'row'}}>
                <View style={{flex: 0.8}}>
                  <View style={{flexDirection: 'row'}}>
                    <Text style={{fontSize: 10}}>
                      {this.data.weight + ' ' + this.store.text.kg + '  '}
                    </Text>
                    <Text style={{fontSize: 10}}>|</Text>
                    <Text style={{fontSize: 10}}>
                      {'  ' + this.store.text.origin + ' ： ' + this.origin}
                    </Text>
                  </View>
                </View>
     
              </View> */}
            </View>

            {this.data.inventory == 0 ? (<View style={{ width: width }}>

              <Text style={{ color: 'red', fontWeight: '800', marginLeft: 30, marginBottom: 10 }}>
                {this.store.text.outOfStock}
              </Text>
            </View>) : (<View />)}
            {/* line */}
            <View
              style={{
                width: width,
                flexDirection: 'row',
                alignItems: 'center',
              }}>
              <MaterialCommunityIcons
                style={{ marginLeft: 30 }}
                name="star"
                size={18}
                color={colors.mainColor}
              />
              <Text style={{ marginLeft: 5, color: colors.mainColor }}>
                {'4 (300)'}
              </Text>
            </View>

            <View style={{ flexDirection: 'row', marginTop: 10 }}>
              <View style={{ flex: 1, marginLeft: 30 }}>
                {this.renderOriPrice()}
                <Text
                  style={{
                    fontSize: 25,
                    color: this.data.hasOwnProperty('oriPrice') && this.data.oriPrice > this.data.price ? 'red' : 'black',
                    fontWeight: 'bold',
                  }}>
                  {this.store.priceHandler(this.data.price)}
                </Text>

                {/* <View style={{flexDirection: 'row', marginTop: 10}}>
                  <TouchableOpacity
                    onPress={() => {
                      if (this.qry > 0) {
                        this.qry -= 1;
                      }
                    }}
                    style={{
                      height: 17,
                      width: 17,
                      borderRadius: 4,
                      backgroundColor: colors.mainColor,
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}>
                  
                    <MaterialCommunityIcons
                      name="minus"
                      color={'white'}
                      size={14}
                    />
                  </TouchableOpacity>
                  <View
                    style={{
                      width: 45,
                      height: 17,
                      borderColor: colors.line2Color,
                      backgroundColor: colors.historyListColor,
                      borderRadius: 4,
                      marginLeft: 1,
                      marginRight: 1,
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}>
                    <Text style={{fontSize: 10}}>{this.qry.toString()}</Text>
                  </View>
                  <TouchableOpacity
                    style={{
                      height: 17,
                      width: 17,
                      borderRadius: 4,
                      backgroundColor: colors.mainColor,
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}
                    onPress={() => {
                      if (this.qry < 99) {
                        this.qry += 1;
                      }
                    }}>
                    <MaterialCommunityIcons
                      name="plus"
                      color={'white'}
                      size={14}
                    />
                  </TouchableOpacity>
                </View> */}
              </View>
              <View style={{ flex: 1, marginRight: 30, alignItems: 'flex-end' }}>
                {/* <Text
                  style={{
                    color: colors.subTextColor,
                    fontSize: 10,
                    marginTop: 5,
                    fontWeight: '800',
                  }}>
                  {this.renderStockStatus()}
                </Text> */}
                <CustomSmallButton
                  title={this.store.text.addToShoppingCart}
                  iconName={'shopping-outline'}
                  onPress={() => {
                    var newData = _.cloneDeep(this.data);
                    newData.buyCount = _.cloneDeep(this.qry);
                    this.store.addSingleItemToShoppingCart(newData, this);
                  }}
                />
              </View>
            </View>

            <View style={{ width: width }}>
              <View style={{ marginLeft: 30, marginRight: 30 }}>
                <Text style={{ fontSize: 22, marginTop: 20, marginBottom: 40, fontWeight: '800' }}>
                  {this.store.text.productDescription}
                </Text>
                {/* <Text style={{fontSize: 10, marginTop: 10}}>
                  {this.returnContent(this.data.short_description)}
                </Text> */}
                {/* <Text style={{ fontSize: 10, marginTop: 10, fontSize: 14 }}>
                  {this.data.desc}
                </Text> */}
                <HTMLView
                  value={this.data.desc}

                  addLineBreaks={false}
                  paragraphBreak={false}
                  //stylesheet={{ fontSize: 10, marginTop: 0, fontSize: 14 ,}}
                  stylesheet={{
                    marginTop: 20,
                    br: { marginTop: -25, fontSize: 18 },
                    p: { marginTop: -25, fontSize: 15 }
                  }}
                />
              </View>
            </View>

            <View
              style={{
                marginLeft: 30,
                marginRight: 30,
                width: width - 60,
                marginTop: 20,
                flexDirection: 'row',
                justifyContent: 'space-between',
              }}>
              {/* <TouchableOpacity
                onPress={() => this.showshowWriteCommentAction()}
                style={{
                  flexDirection: 'row',
                  justifyContent: 'center',
                  alignItems: 'center',
                }}>
                <MaterialCommunityIcons name="comment-processing" size={20} />
                <Text
                  style={{
                    marginLeft: 10,
                    fontSize: 12,
                    color: 'black',
                    fontWeight: '800',
                  }}>
                  {this.store.text.writeAReview}
                </Text>
                {this.showWriteComment ? (
                  <Icon name={'chevron-down-outline'} size={20} />
                ) : (
                    <Icon name={'chevron-forward-outline'} size={20} />
                  )}
              </TouchableOpacity> */}
            </View>
            {this.showWriteComment ? (
              <View>
                <View
                  style={{
                    marginLeft: 30,
                    marginRight: 30,
                    width: width - 60,
                    marginTop: 20,
                    height: 150,
                  }}>
                  <Text style={{ fontSize: 12 }}>
                    {this.store.text.rating + '：'}
                  </Text>
                  <View style={{ flexDirection: 'row' }}>
                    {this.renderStar()}
                  </View>
                  <Text style={{ fontSize: 12 }}>
                    {this.store.text.review + '：'}
                  </Text>
                  <TextInput
                    value={this.review.review}
                    onChangeText={text => (this.review.review = text)}
                    style={{ width: width - 60 }}
                    multiline={true}
                    fontSize={12}
                    placeholder={this.store.text.pleaseEnterReview}
                    maxLength={100}
                  />

                  <TouchableOpacity
                    style={{
                      flexDirection: 'row',
                      position: 'absolute',
                      bottom: 9,
                      left: 0,
                      alignItems: 'center',
                    }}
                    onPress={() => this.commentAction()}>
                    <Text style={{ fontSize: 12 }}>
                      {this.store.text.send + '  '}
                    </Text>
                    <MaterialCommunityIcons name="send" size={20} />
                  </TouchableOpacity>
                  <View style={{ position: 'absolute', bottom: 10, right: 10 }}>
                    <Text style={{ fontSize: 12 }}>
                      {this.review.review.length + '/100 '}
                    </Text>
                  </View>
                </View>
              </View>
            ) : (
                <View />
              )}

            <View style={{ width: width }}>
              {/* <TouchableOpacity
                style={{ flexDirection: 'row', marginTop: 2 }}
                onPress={() => {
                  Linking.canOpenURL('https://www.hosunsin.com/tnc.html').then(
                    supported => {
                      if (supported) {
                        Linking.openURL('https://www.hosunsin.com/tnc.html');
                      } else {
                        console.log(
                          "Don't know how to open URI: " +
                          response.data.wechat.qr_code_url,
                        );
                      }
                    },
                  );
                }}>
                <View style={{ flex: 0.9, justifyContent: 'center' }}>
                  <Text
                    style={{
                      marginLeft: 30,
                      fontSize: 12,
                      color: colors.mainColor,
                      fontWeight: '800',
                    }}>
                    {this.store.text.regulations +
                      ', ' +
                      this.store.text.refunds}
                  </Text>
                </View>
                <View style={{ flex: 0.1, justifyContent: 'center' }}>
                  <Icon
                    name="chevron-forward-outline"
                    color={colors.mainColor}
                    size={20}
                  />
                </View>
              </TouchableOpacity> */}
              <TouchableOpacity
                style={{ flexDirection: 'row', marginTop: 2 }}
                onPress={() => {
                  this.showComment = !this.showComment;
                }}>
                <View style={{ flex: 0.9, justifyContent: 'center' }}>
                  <Text
                    style={{
                      marginLeft: 30,
                      fontSize: 12,
                      color: colors.mainColor,
                      fontWeight: '800',
                    }}>
                    {this.store.text.comments}
                  </Text>
                </View>
                <View style={{ flex: 0.1, justifyContent: 'center' }}>
                  {this.showComment ? (
                    <Icon
                      name="chevron-down-outline"
                      color={colors.mainColor}
                      size={20}
                    />
                  ) : (
                      <Icon
                        name="chevron-forward-outline"
                        color={colors.mainColor}
                        size={20}
                      />
                    )}
                </View>
              </TouchableOpacity>
            </View>
            {this.showComment ? (
              <View
                style={{
                  width: width - 60,
                  marginLeft: 30,
                  marginTop: 10,
                  marginRight: 30,
                  alignItems: 'center',
                }}>
                {this.renderComments()}
                <TouchableOpacity
                  style={{
                    width: 100,
                    height: 30,
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}
                  onPress={() => {
                    this.commentPage += 1;
                    this.store.getComment(this.data.id, this.commentPage, this);
                  }}>
                  <Text
                    style={{
                      fontSize: 14,
                      fontWeight: '800',
                      color: colors.mainColor,
                    }}>
                    {this.store.text.more}
                  </Text>
                </TouchableOpacity>
              </View>
            ) : (
                <View />
              )}
          </View>
        </ScrollView>
        <Toast
          ref="toast"
          style={{ backgroundColor: colors.mainColor }}
          position="center"
          positionValue={100}
          fadeInDuration={750}
          fadeOutDuration={2000}
          opacity={0.8}
          textStyle={{ color: 'white' }}
        />
      </MenuProvider>
    );
  }
}
const styles = StyleSheet.flatten({
  naviBar: {
    width,
    height: Platform.OS === 'ios' ? 70 : 75,
    backgroundColor: 'white',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginTop: Platform.OS === 'ios' ? 0 : getStatusBarHeight(),
  },
  barAreaView: {
    flex: 1,
    marginRight: 20,
    marginLeft: 20,
    marginTop: Platform.OS === 'ios' ? -5 : 15,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },

  circle: {
    width: 40,
    height: 40,
    borderRadius: 30,
    marginLeft: 10,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: colors.shoppingGroupColor,
  },
});
const richTextStyles = StyleSheet.create({
  p: {

    marginBottom: -80
  }
})