import React from 'react';
import {
  SafeAreaView,
  Text,
  View,
  TouchableOpacity,
  StyleSheet,
  Image,
  ImageBackground,
  ScrollView
} from 'react-native';
var _ = require('lodash');
import { width, height } from '../../services/screen';
import { colors } from '../../assets/styles/colors-theme';
import Loading from '../../components/Loading';
import Toast, { DURATION } from 'react-native-easy-toast';
import { inject, observer } from "mobx-react"
import { Col, Grid, Row } from "react-native-easy-grid";
import TitleBar from '../../components/titleBar'
import { observable, makeObservable } from 'mobx'
import { WebView } from 'react-native-webview';
import Carousel, { Pagination } from 'react-native-snap-carousel';
import ListTitle from '../../components/listTitle';
import I18n from '../../services/i18n'
import { s, vs, ms, mvs } from 'react-native-size-matters';
import { images } from '../../assets/images/imageIndex';
import RenderProducts from '../../components/renderProducts';
import HTMLView from 'react-native-htmlview';
import moment from 'moment';
import QRCode from 'react-native-qrcode-svg';
import Icon from 'react-native-vector-icons/dist/MaterialCommunityIcons'
import ProgressiveFastImage from "@freakycoder/react-native-progressive-fast-image";
const Coupon = inject("appStore")(observer(class Coupon extends React.Component {

  selected = 'all'
  coupons = []
  constructor(props) {
    super(props);
    this.store = props.appStore;
    makeObservable(this, {
      selected: observable,
      coupons: observable
    })
  }


  async componentWillMount() {

  }

  async componentDidMount() {
    await this.store.getCoupons(this)
    await this.couponsHandler()
  }



  selectCatAction(id) {
    this.selected = id
    this.couponsHandler()
  }

  renderFilter() {
    const filter = [
      { id: 'all', name: '全部' }, { id: 'usable', name: '可使用' },
      { id: 'used', name: '已使用' }, { id: 'expired', name: '已過期' },
      { id: 'willUsable', name: '將能使用' }
    ]
    return (
      <View style={{ height: s(30), width: width, backgroundColor: colors.catColor, marginTop: 10 }}>
        <ScrollView horizontal={true}>
          {filter.map((item, index) => {
            return (
              <TouchableOpacity style={{ height: s(30), justifyContent: 'center', backgroundColor: this.selected == item.id ? '#F9F4EE' : colors.catColor }}
                onPress={() => { this.selectCatAction(item.id) }}>
                <Text style={{ color: colors.fontColor, marginHorizontal: 20 }}>
                  {item.name}
                </Text>
              </TouchableOpacity>
            )
          })}
        </ScrollView>
      </View>
    )
  }

  couponStatusLabelHandler(item) {
    if (moment(item.end, 'YYYY-MM-DD').toDate() < moment().toDate()) {
      return '已過期'
    } else if (moment(item.start, 'YYYY-MM-DD').toDate() > moment().toDate()) {
      return '將能使用'
    } else if (item.used >= item.personUsed) {
      return '已使用'
    } else if (moment(item.end, 'YYYY-MM-DD').toDate() > moment().toDate() &&
      moment(item.start, 'YYYY-MM-DD').toDate() <= moment().toDate() &&
      item.used < item.personUsed) {
      return '可使用'
    }
  }

  couponsHandler() {
    this.coupons = []
    switch (this.selected) {
      case 'all':
        this.store.coupons.map((item, index) => {
          this.coupons.push(item)
        })
        break;
      case 'usable':
        this.store.coupons.map((item, index) => {
          if (moment(item.end, 'YYYY-MM-DD').toDate() > moment().toDate() &&
            moment(item.start, 'YYYY-MM-DD').toDate() <= moment().toDate() &&
            item.used < item.personUsed) {
            this.coupons.push(item)
          }
        })
        break;
      case 'used':
        this.store.coupons.map((item, index) => {
          if (item.used >= item.personUsed) {
            this.coupons.push(item)
          }
        })
        break;
      case 'expired':
        this.store.coupons.map((item, index) => {
          if (moment(item.end, 'YYYY-MM-DD').toDate() < moment().toDate()) {
            this.coupons.push(item)
          }
        })
        break;
      case 'willUsable':
        this.store.coupons.map((item, index) => {
          if (moment(item.end, 'YYYY-MM-DD').toDate() < moment().toDate()) {
            this.coupons.push(item)
          }
        })
        break;
    }
  }



  renderStatusLabel(item) {
    return (
      <View style={{ marginRight: 10, marginTop: 10, backgroundColor: '#FFFFFFA0', borderRadius: 7 }}>
        <Text style={{ marginHorizontal: 4, marginVertical: 2, fontSize: s(10), color: colors.textColor }}>
          {this.couponStatusLabelHandler(item)}
        </Text>
      </View>
    )
  }

  renderCouponList() {
    if (this.coupons.length > 0) {
      return (
        this.coupons.map((item, index) => {
          return this.renderCoupons(item)
        })
      )
    }
  }

  couponTypeHandler(item) {
    if (item.discountAmount > 0) {
      return '$' + item.discountAmount + "現金券"
    } else {
      return item.discountRate * 100 + "%折扣優惠"
    }
  }

  renderCouponButtons(item) {
    return (
      <View style={{ width: '80%', height: s(40), backgroundColor: colors.textColor, justifyContent: 'center', alignItems: 'center', borderRadius: s(10) }}>
        <Text style={{ color: 'white', fontWeight: '400' }}>
          {this.couponTypeHandler(item)}
        </Text>
      </View>
    )
  }

  renderCoupons(item) {
    return (
      <View style={{ width: width, alignItems: 'center', marginVertical: 10 }}>
        <TouchableOpacity style={{ width: s(300), height: s(150), flexDirection: 'row' }}
          onPress={() => { this.props.navigation.navigate('CouponDetails', { data: item }) }}>
          <View style={{ flex: 0.6 }}>
            {item.hasOwnProperty('imgURL') ? (<ProgressiveFastImage style={{ width: '100%', height: '100%', borderTopLeftRadius: s(20), borderBottomLeftRadius: s(20) }} source={{uri:item.imgURL}} />) :
              (<ProgressiveFastImage style={{ width: '100%', height: '100%', borderTopLeftRadius: s(20), borderBottomLeftRadius: s(20) }} source={images.coupon} />)}

          </View>
          <View style={{ width: s(140), height: s(150), backgroundColor: colors.couponbgc, borderRadius: s(20), position: 'absolute', right: 0 }}>
            <View style={{ width: '100%', alignItems: 'flex-end' }}>
              {this.renderStatusLabel(item)}
            </View>
            <View style={{ width: '100%', alignItems: 'center', marginTop: 5 }}>
              <Text style={{ fontSize: s(10), color: colors.textColor }}>
                {moment(item.start, 'YYYY-MM-DD').format('DD/MM/YYYY') + " - " + moment(item.end, 'YYYY-MM-DD').format('DD/MM/YYYY')}
              </Text>
            </View>
            <View style={{ width: '100%', height: s(40), alignItems: 'center', marginTop: 5, }}>
              <Text style={{ fontSize: s(14), color: colors.textColor, marginHorizontal: 10, fontWeight: '500' }} numberOfLines={2}>
                {item.name}
              </Text>
            </View>
            <View style={{ width: '100%', height: s(40), alignItems: 'center', marginTop: 5, }}>
              {this.renderCouponButtons(item)}
            </View>
          </View>
        </TouchableOpacity>
        <Image source={images.titleLogo} style={{ position: 'absolute', bottom: s(-10), right: s(20) }} />
      </View>
    )
  }



  render() {
    return (
      <ImageBackground resizeMode='cover' style={{ flex: 1, backgroundColor: colors.bgc }} source={require('../../assets/images/background.png')} >
        <Loading loading={this.store.loading} />
        <TitleBar navigation={this.props.navigation} back={true} user={false} />
        <View style={{ width: width, alignItems: 'center', marginTop: 30, }}>
          <Text style={{ fontWeight: '800', color: colors.fontColor, fontSize: 15 }}>
            {I18n.t('cartCoupon')}
          </Text>
        </View>
        {this.renderFilter()}

        <ScrollView style={{ marginVertical: 10 }}>
          {this.renderCouponList()}
        </ScrollView>
        <Toast
          ref="toast"
          style={{ backgroundColor: colors.mainColor }}
          position="center"
          positionValue={100}
          fadeInDuration={750}
          fadeOutDuration={2000}
          opacity={0.8}
          textStyle={{ color: 'white' }}
        />
      </ImageBackground>

    );
  }
}))
const styles = StyleSheet.create({
  titleText: {
    color: colors.fontColor,
    fontSize: 13,
    fontWeight: '800'
  },
  content: {
    margin: 20,
    br: { marginTop: -30, fontSize: 18, },
  },
});

export default Coupon
