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,
} from 'react-native';
var _ = require('lodash');
import GallerySwiper from 'react-native-gallery-swiper';
import Rating from '../../components/rating';
import { inject, observer } from "mobx-react"
import { observable, makeObservable } from 'mobx'
import { width, height } from '../../services/screen';
import CustomLoginButton from '../../components/customLoginButton';
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 MaterialCommunityIcons from 'react-native-vector-icons/dist/MaterialCommunityIcons';
import { images } from '../../assets/images/imageIndex';
import Mostcheaplist from '../../components/mostcheaplist';

Icon.loadFont();
FeatherIcon.loadFont();
const ProductsDetails = inject("appStore")(observer(class ProductsDetails extends React.Component {
  catalogue = [];

  data = this.props.route.params.data;

  imageData = [];

  origin = '';

  qry = 1;

  showWriteComment = false;

  showComment = true;

  commentPage = 1;

  productComment = [];

  review = {
    product_id: null,
    review: '',
    reviewer: '',
    reviewer_email: '',
    rating: 3,
    status: 'hold',
  };
  constructor(props) {
    super(props);
    this.store = props.appStore;
    makeObservable(this, {
      catalogue: observable,

      data: observable,

      imageData: observable,

      origin: observable,

      qry: observable,

      showWriteComment: observable,

      showComment: observable,

      commentPage: observable,

      productComment: observable,

      review: observable,
    })
  }
  componentDidMount() {
    console.log(this.data);
  }

  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(_.cloneDeep(this.review), this);
      this.review = {
        product_id: null,
        review: '',
        reviewer: '',
        reviewer_email: '',
        rating: 3,
        status: 'hold',
      };
      this.showWriteComment = false;
    }
  }

  comments(items) {
    return (
      <View>
        <Text style={{ fontSize: 14, color: colors.mainColor }}>
          {items.reviewer}
        </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 }}>
            {this.returnContent(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.src,
      };
      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:
        '本公司專門為客人從日本空運到港 提供最新鮮時令水果及急凍海產 客人可以安坐家享受日本味道既幸福 公司屋企party 大量優質食品供應 開張節日時令果籃為你度身訂造送到你客人手上',
      title: '好新鮮APP',
      url: 'http://onelink.to/3nqphw',
    });
  }


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

  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');
      console.log(this.store.userData.username);
      this.store.addFavouritePost(this.data, this);
    }
  }

  renderStockStatus() {
    if (this.data.stock_status == 'instock') {
      return this.store.text.instock;
    } else {
      return this.store.text.outOfStock;
    }
  }

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

  render() {
    return (
      <SafeAreaView
        style={{
          flex: 1,
          backgroundColor: 'white',
        }}>
        <TitleBar self={this} showSearch={true} />
        <ScrollView style={{ flex: 1 }}>
          <View style={{ alignItems: 'center', marginBottom: 30 }}>
            <TouchableOpacity
              style={{
                height: 60,
                width: 60,
                justifyContent: 'center',
                alignItems: 'center',
                position: 'absolute',
                left: 10,
                top: 5,
              }}
              onPress={() => {
                this.props.navigation.goBack();
              }}>
              <Icon name="ios-arrow-back" color={colors.mainColor} size={40} />
            </TouchableOpacity>

            <GallerySwiper
              style={{ width: 250, height: 250, marginTop: 20 }}
              images={this.imageData}
              enableResistance={false}
              removeClippedSubviews={false}
            />
            <View
              style={{
                width: width - 60,
                marginLeft: 30,
                marginTop: 20,
                marginRight: 30,
              }}>
              <Text numberOfLines={1} style={{ fontWeight: 'bold', width: 450 }}>
                {this.data.name}
              </Text>
              {/* 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 style={{ flex: 0.2 }}>
                  {this.data.tags.length > 0 ? (
                    <View style={{ flexDirection: 'row' }}>
                      <Text style={{ fontSize: 10 }}>
                        {this.data.tags[0].name}
                      </Text>
                      {/* <Text style={{fontSize: 10}}>{' ，'}</Text>
                    <Text style={{fontSize: 10}}>{this.data.tags[1].name}</Text> */}
                    </View>
                  ) : (
                    <View />
                  )}
                </View>
              </View>
            </View>
            {/* line */}
            <View
              style={{
                height: 1,
                width: width - 20,
                backgroundColor: colors.lineColor,
                marginTop: 20,
              }}
            />
            <View style={{ flexDirection: 'row', marginTop: 20 }}>
              <View style={{ flex: 1, marginLeft: 30 }}>
                <Text
                  style={{
                    fontSize: 12,
                    textDecorationLine: 'line-through',
                    color: colors.line2Color,
                  }}>
                  {this.data.on_sale
                    ? this.store.text.originalPrice +
                    ' ' +
                    this.store.priceHandler(this.data.regular_price)
                    : ''}
                </Text>
                <Text
                  style={{
                    fontSize: 14,
                    color: this.data.on_sale ? '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: 15,
                      width: 15,
                      backgroundColor: colors.mainColor,
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}>
                    <Text style={{ color: 'white', fontSize: 14 }}>-</Text>
                    {/* <Icon name = 'remove' color = 'white'/> */}
                  </TouchableOpacity>
                  <View
                    style={{
                      width: 45,
                      height: 15,
                      borderColor: colors.line2Color,
                      borderRadius: 3,
                      borderWidth: 1,
                      marginLeft: 3,
                      marginRight: 3,
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}>
                    <Text style={{ fontSize: 10 }}>{this.qry.toString()}</Text>
                  </View>
                  <TouchableOpacity
                    style={{
                      height: 15,
                      width: 15,
                      backgroundColor: colors.mainColor,
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}
                    onPress={() => {
                      if (this.qry < 99) {
                        this.qry += 1;
                      }
                    }}>
                    <Text style={{ color: 'white', fontSize: 14 }}>+</Text>
                    {/* <Icon name = 'remove' color = 'white'/> */}
                  </TouchableOpacity>
                </View>
              </View>
              <View style={{ flex: 1, marginRight: 30, alignItems: 'flex-end' }}>
                <Rank ranking={parseFloat(this.data.average_rating)} />
                <Text
                  style={{ color: colors.mainColor, fontSize: 10, marginTop: 5 }}>
                  {this.renderStockStatus()}
                </Text>
                <TouchableOpacity
                  style={{
                    marginTop: 12,
                    flexDirection: 'row',
                    backgroundColor: colors.mainColor,
                    height: 17,
                    width: 75,
                    alignItems: 'center',
                    justifyContent: 'center',
                    borderRadius: 5,
                  }}
                  onPress={() => {
                    var newData = _.cloneDeep(this.data);
                    newData.buyCount = _.cloneDeep(this.qry);
                    this.store.addSingleItemToShoppingCart(newData, this);
                  }}>
                  <FeatherIcon
                    name={'shopping-cart'}
                    style={{ marginRight: 2 }}
                    size={12}
                    color={'white'}
                  />
                  <Text style={{ fontSize: 10, color: 'white' }}>
                    {this.store.text.addToShoppingCart}
                  </Text>
                </TouchableOpacity>
              </View>
            </View>
            <View
              style={{
                height: 1,
                width: width - 20,
                backgroundColor: colors.lineColor,
                marginTop: 20,
              }}
            />
            <View style={{ width: width }}>
              <View style={{ marginLeft: 30, marginRight: 30 }}>
                <Text style={{ fontSize: 10, marginTop: 10 }}>
                  {this.store.text.productDescription}
                </Text>
                <Text style={{ fontSize: 10, marginTop: 10 }}>
                  {this.returnContent(this.data.short_description)}
                </Text>
              </View>
            </View>
            <View
              style={{
                height: 1,
                width: width,
                backgroundColor: colors.lineColor,
                marginTop: 20,
              }}
            />
            <View
              style={{
                marginLeft: 30,
                marginRight: 30,
                width: width - 60,
                marginTop: 20,
                flexDirection: 'row',
                justifyContent: 'space-between',
              }}>
              <TouchableOpacity
                onPress={() => {
                  this.share();
                }}
                style={{
                  flexDirection: 'row',
                  justifyContent: 'center',
                  alignItems: 'center',
                }}>
                <Image source={images.details.share} />
                <Text style={{ marginLeft: 10, fontSize: 12 }}>
                  {this.store.text.share}
                </Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={{
                  flexDirection: 'row',
                  justifyContent: 'center',
                  alignItems: 'center',
                }}
                onPress={() => {
                  this.addFavouriteAction();
                }}>
                <Image source={images.details.favourite} />
                <Text style={{ marginLeft: 10, fontSize: 12 }}>
                  {this.store.text.addToFavourite}
                </Text>
              </TouchableOpacity>
              <TouchableOpacity
                onPress={() => this.showshowWriteCommentAction()}
                style={{
                  flexDirection: 'row',
                  justifyContent: 'center',
                  alignItems: 'center',
                }}>
                <Image source={images.details.comment} />
                <Text style={{ marginLeft: 10, fontSize: 12 }}>
                  {this.store.text.writeAReview}
                </Text>
              </TouchableOpacity>
            </View>
            {this.showWriteComment ? (
              <View>
                <View
                  style={{
                    height: 1,
                    width: width,
                    backgroundColor: colors.lineColor,
                    marginTop: 20,
                  }}
                />
                <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, color: colors.mainColor }}>
                      {this.store.text.send}
                    </Text>
                    <MaterialCommunityIcons
                      name="send"
                      size={20}
                      color={colors.mainColor}
                    />
                  </TouchableOpacity>
                  <View style={{ position: 'absolute', bottom: 10, right: 10 }}>
                    <Text style={{ fontSize: 12, color: colors.textColor }}>
                      {this.review.review.length + '/100 '}
                    </Text>
                  </View>
                </View>
              </View>
            ) : (
              <View />
            )}

            <View
              style={{
                height: 1,
                width: width,
                backgroundColor: colors.lineColor,
                marginTop: 20,
              }}
            />
            <View style={{ width: width }}>
              {/* <View style={{flexDirection: 'row', marginTop: 20}}>
                <View style={{flex: 0.9, justifyContent: 'center'}}>
                  <Text style={{marginLeft: 30, fontSize: 12}}>
                    {this.store.text.refunds}
                  </Text>
                </View>
                <View style={{flex: 0.1, justifyContent: 'center'}}>
                  <Icon
                    name="ios-arrow-forward"
                    color={colors.mainColor}
                    size={20}
                  />
                </View>
              </View> */}
              <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 }}>
                    {this.store.text.regulations +
                      ', ' +
                      this.store.text.refunds}
                  </Text>
                </View>
                <View style={{ flex: 0.1, justifyContent: 'center' }}>
                  <Icon
                    name="ios-arrow-forward"
                    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 }}>
                    {this.store.text.comments}
                  </Text>
                </View>
                <View style={{ flex: 0.1, justifyContent: 'center' }}>
                  {this.showComment ? (
                    <Icon
                      name="ios-arrow-down"
                      color={colors.mainColor}
                      size={20}
                    />
                  ) : (
                    <Icon
                      name="ios-arrow-forward"
                      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 }}>{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' }}
        />
      </SafeAreaView>
    );
  }
}
))
export default ProductsDetails
