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';
import { thisExpression } from '@babel/types';

Icon.loadFont();

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

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

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

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

  shippingMethodHandler(id) {
    switch (id) {
      case '4':
        return '門市自取';
        break;
      case '11':
        return '送到上門';
        break;
      case '3':
        return '送到上門';
        break;
    }
  }

  statusHandler(text) {
    switch (text) {
      case 'pending':
        return '等待付款中';
        break;
      case 'processing':
        return '處理中';
        break;
      case 'on-hold':
        return '擱置中';
        break;
      case 'completed':
        return '已完成';
        break;
      case 'cancelled':
        return '已取消';
        break;
      case 'refunded':
        return '已退款';
        break;
      case 'shipped':
        return '已出貨 ';
        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 < 5) {
          return (
            <Text style={{ fontSize: 11 }}>
              {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 (
      <TouchableOpacity
        style={{
          width: width - 40,
          height: 180,
          marginTop: 15,
          marginLeft: 20,
          marginRight: 20,
          borderWidth: 1,
          borderColor: colors.mainColor,
          alignItems: 'center',
        }}
        onPress={() =>
          this.props.navigation.navigate('HistoryDetails', {
            data: _.cloneDeep(items),
          })
        }>
        <View
          style={{
            width: width - 41,
            height: 40,
            flexDirection: 'row',
            alignItems: 'center',
            backgroundColor: colors.mainColor,
          }}>
          <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>
        </View>
        <View style={{ flex: 1, flexDirection: 'row' }}>
          <View style={{ flex: 0.7 }}>
            <View
              style={{ flex: 1, marginLeft: 10, marginRight: 10, marginTop: 10 }}>
              {this.productsList(items)}
              {this.renderDot(items)}
            </View>

            <View style={{ margin: 10 }}>
              {items.hasOwnProperty('shipping_lines') ? (
                <View>
                  <Text style={{ fontSize: 11 }}>
                    {this.store.text.shippingPrice +
                      '  ' +
                      this.shippingMethodHandler(
                        items.shipping_lines[0].instance_id,
                      ) +
                      ' ' +
                      this.store.priceFormatReturn(
                        parseFloat(items.shipping_lines[0].total),
                      )}
                  </Text>
                  <Text style={{ fontSize: 11 }}>
                    {this.store.text.paymentMethod +
                      '   ' +
                      this.paymentMethodStringReturn(items.payment_method_title)}
                  </Text>
                  <Text style={{ fontSize: 11 }}>
                    {this.store.text.total +
                      '   ' +
                      this.store.priceFormatReturn(parseFloat(items.total))}
                  </Text>
                </View>
              ) : (
                <View />
              )}
            </View>
          </View>
          <View
            style={{
              flex: 0.3,
              alignItems: 'flex-end',
              justifyContent: 'center',
            }}>
            <Text
              style={{
                marginRight: 10,
                fontSize: 13,
                color: colors.mainColor,
                fontWeight: 'bold',
              }}>
              {this.statusHandler(items.status)}
            </Text>
          </View>
        </View>
      </TouchableOpacity>
    );
  }

  render() {
    return (
      <SafeAreaView
        style={{
          flex: 1,
          backgroundColor: 'white',
        }}>
        <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>
    );
  }
}
))

export default BuyHistory