import React from 'react';
import {
  SafeAreaView,
  Text,
  View,
  TouchableOpacity,
  Image,
  ScrollView,
  Keyboard,
  TouchableWithoutFeedback,
  StyleSheet,
  TextInput,
  RefreshControl,
} from 'react-native';
var _ = require('lodash');
import { inject, observer } from "mobx-react"
import { observable, makeObservable } from 'mobx'
import TitleBar from '../../components/titleBar';
import { images } from '../../assets/images/imageIndex';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import CheckAnimate from '../../components/checkAnimate';
import moment from 'moment';
import { width, height } from '../../services/screen';
import Loading from '../../components/Loading';
import { colors } from '../../assets/styles/colors-theme';
import Toast, { DURATION } from 'react-native-easy-toast';
import Icon from 'react-native-vector-icons/dist/MaterialCommunityIcons';
import IonIcon from 'react-native-vector-icons/dist/Ionicons';
import CustomTextInput from '../../components/customTextInput';
import CustomLoginButton from '../../components/customLoginButton';


Icon.loadFont();
const BuyHistory = inject("appStore")(observer(class BuyHistory extends React.Component {
  constructor(props) {
    super(props);
    this.store = props.appStore;
  }

  componentDidMount() {
    this._unsubscribe = this.props.navigation.addListener('focus', () => {
      this.store.getOrders();
    });
  }

  componentWillUnmount() {
    this._unsubscribe();
    this.store.getOrders();
  }

  paymentMethodStringReturn(value) {
    switch (value) {
      case 'Cash On Delivery':
        return this.store.text.cashOnDelivery;
        break;
      case 'Stripe Credit Card':
        return this.store.text.creditCard;
        break;
      default:
        return value;
        break;
    }
  }

  shippingMethodHandler(type) {
    switch (type) {
      case 0:
        return '門市自取';
        break;
      case 1:
        return '送到上門';
        break;
      case '3':
        return '送到上門';
        break;
    }
  }

  statusHandler(text) {
    switch (text) {
      case 'PRV':
        return '支付審查';//Payment review
        break;
      case 'PRJ':
        return '支付拒絶' //Payment reject
        break;
      case "PRU":
        return '上傳付款收據';//Upload payment receipt
        break;
      case 'pending':
        return '等待付款中';//Waiting for payment
        break;
      case 'processing':
        return '處理中';//Preocessing 
        break;
      case 'on-hold':
        return '擱置中';//On hold 
        break;
      case 'completed':
        return '已完成';//Completed
        break;
      case 'cancelled':
        return '已取消';//Cancelled
        break;
      case 'refunded':
        return '已退款';//Refunded
        break;
      case 'shipped':
        return '已出貨 ';//Shipped
        break;
    }
  }

  OrderList() {
    if (this.store.orderList.length > 0) {
      return this.store.orderList.map((items, index) => {
        return this.renderList(items);
      });
    } else {
      return <View></View>;
    }
  }

  productsList(items) {
    console.log(items);
    if (items.hasOwnProperty('line_items')) {
      return items.line_items.map((itemsData, itemsIndex) => {
        //  if (itemsIndex < 4) {
        return (
          <Text style={{ fontSize: 11, color: colors.mainColor }}>
            {itemsData.name +
              '  (' +
              this.store.text.quantity +
              ' ：' +
              itemsData.quantity +
              ')'}
          </Text>
        );
        //   }
      });
    } else {
      return <View />;
    }
  }
  renderDot(items) {
    if (items.hasOwnProperty('line_items')) {
      if (items.line_items.length > 4) {
        return <Icon name="dots-vertical" color="gray" />;
      } else {
        return <View />;
      }
    }
  }
  renderList(items) {
    return (
      <View
        style={{
          width: width - 40,
          height: 180,
          marginTop: 15,
          marginLeft: 20,
          marginRight: 20,
          alignItems: 'center',
        }}>
        <TouchableOpacity
          style={{
            width: width - 41,
            height: 50,
            borderTopLeftRadius: 30,
            borderTopRightRadius: 30,
            flexDirection: 'row',
            alignItems: 'center',
            backgroundColor: colors.mainColor,
          }}
          onPress={() =>
            this.props.navigation.navigate('HistoryDetails', {
              data: _.cloneDeep(items),
            })
          }>
          <View style={{ flex: 0.6 }}>
            <Text
              style={{
                fontSize: 11,
                color: 'white',
                marginLeft: 10,
                fontWeight: 'bold',
              }}>
              {this.store.text.orderNumber + ' ： ' + items.id}
            </Text>
          </View>
          <View style={{ flex: 0.4, alignItems: 'flex-end' }}>
            <Text
              style={{
                fontSize: 9,
                color: 'white',
                marginRight: 10,
                fontWeight: 'bold',
              }}>
              {this.store.text.date +
                ' ： ' +
                moment(items.date_created).format('DD/MM/YYYY')}
            </Text>
          </View>
        </TouchableOpacity>
        <View
          style={{
            flex: 1,
            flexDirection: 'row',
            backgroundColor: colors.historyListColor,
            borderBottomLeftRadius: 30,
            borderBottomRightRadius: 30,
          }}>
          <View style={{ flex: 0.7 }}>
            <ScrollView
              style={{
                flex: 1,
                marginLeft: 10,
                marginRight: 10,
                marginTop: 10,
              }}>
              {this.productsList(items)}
              {/* {this.renderDot(items)} */}
            </ScrollView>

            <TouchableOpacity
              style={{ margin: 10 }}
              onPress={() =>
                this.props.navigation.navigate('HistoryDetails', {
                  data: _.cloneDeep(items),
                })
              }>
              {items.hasOwnProperty('shipping') ? (
                <View>
                  <Text style={styles.textStyle}>
                    {this.store.text.shippingPrice +
                      '  ' +
                      this.shippingMethodHandler(
                        items.shipping.shipping_method_type,
                      ) +
                      ' ' +
                      this.store.priceFormatReturn(
                        parseFloat(items.shipping.fee),
                      )}
                  </Text>
                  <Text style={styles.textStyle}>
                    {this.store.text.paymentMethod +
                      '   ' +
                      this.paymentMethodStringReturn(
                        items.payment_method_title,
                      )}
                  </Text>
                  <Text style={styles.textStyle}>
                    {this.store.text.total +
                      '   ' +
                      this.store.priceFormatReturn(parseFloat(items.total))}
                  </Text>
                </View>
              ) : (
                  <View />
                )}
            </TouchableOpacity>
          </View>
          <TouchableOpacity
            style={{
              flex: 0.3,
              alignItems: 'flex-end',
              justifyContent: 'center',
            }}
            onPress={() =>
              this.props.navigation.navigate('HistoryDetails', {
                data: _.cloneDeep(items),
              })
            }>
            <Text
              style={{
                marginRight: 10,
                fontSize: 13,
                color: colors.mainColor,
                fontWeight: 'bold',
              }}>
              {this.statusHandler(items.status)}
            </Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }

  render() {
    return (
      <SafeAreaView
        style={{
          flex: 1,
          backgroundColor: colors.bgc,
        }}>
        <View style={{ flex: 1 }}>
          <Loading loading={this.store.loading} />
          <TitleBar self={this} showSearch={true} />

          <ScrollView
            style={{ flex: 1, marginBottom: 10 }}
            refreshControl={
              <RefreshControl
                refreshing={this.store.loading}
                onRefresh={() => this.store.getOrders()}
              />
            }>
            {this.OrderList()}
          </ScrollView>
        </View>
      </SafeAreaView>
    );
  }
}))
const styles = StyleSheet.flatten({
  textStyle: {
    fontSize: 11,
    color: colors.mainColor,
  },
});

export default BuyHistory