import React from 'react';
import { SafeAreaView, Text, Image, Alert, Linking, View, TouchableOpacity, StyleSheet, TextInput, Keyboard, DatePickerIOS, ScrollView } from 'react-native';
import { inject, observer } from "mobx-react"
import { observable, makeObservable } from 'mobx'
import Loading from '../../components/Loading'
import { width, height } from '../../services/screen';
import { colors } from '../../assets/styles/colors-theme';
import { images } from '../../assets/images/imageIndex';
import AsyncStorage from '@react-native-community/async-storage';
import moment from 'moment'
import { getStatusBarHeight } from 'react-native-status-bar-height';
import CustomLoginButton from '../../components/customLoginButton';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import CustomCircleButton from '../../components/customCircleButton'
import Icon from 'react-native-vector-icons/MaterialCommunityIcons'
import Setting from '../../components/setting'
import DatePicker from 'react-native-date-picker'
Icon.loadFont();
const Order = inject("appStore")(observer(class Order extends React.Component {


    settingViewAble = false
    lang = this.props.appStore.lanuageSelection
    additionalItems = []
    date = moment().toDate()
    constructor(props) {
        super(props);
        this.store = props.appStore;
        makeObservable(this, {
            settingViewAble: observable,
            lang: observable,
            additionalItems: observable,
            date: observable,
        })
        if (!this.props.route.params.order) {
            this.additionalItems = this.props.route.params.additionalItems
        }
    }

    init() {
        if (this.props.route.params.order) {
            this.store.orderData.map((items, index) => {
                items.allPrice = items.price
                items.qty = 1
                items.discount = 0,
                    items.charges = 0,

                    items.options.map((item, i) => {
                        if (item.type == 0 || item.type == 2) {
                            if (item.valueType == 2) {
                                items.allPrice += item.selections[parseInt(item.index)].price

                            }
                        }
                    })
            })
        } else {
            this.store.orderData.map((items, index) => {
                items.allPrice = items.suit.price
                console.log('basic price: ' + items.price)


                items.options.map((item, i) => {
                    if (item.type == 0 || item.type == 2) {
                        if (item.valueType == 2) {
                            items.allPrice += item.selections[parseInt(item.index)].price
                            console.log('index: ' + i + "   " + 'price: ' + item.selections[parseInt(item.index)].price)
                        }
                    }
                })
            })
        }
    }


    componentWillMount() {


    }

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

    componentWillUnmount() {
        this._unsubscribe();
        this.init();
    }

    amountHandler(data) {
        return (((parseInt(data.allPrice) * (1 - (parseInt(data.discount) / 100)) * parseInt(data.qty)) + parseInt(data.charges))).toFixed(1)
    }



    totalPriceHandler() {
        var price = 0
        this.store.orderData.map((items, index) => {
            price = price + parseInt(this.amountHandler(items))
        })
        this.additionalItems.map((items, index) => {
            if (this.props.route.params.order) {
                price = price + parseInt(this.amountHandler(items))
            } else {
                price = price + parseInt(items.price)
            }
        })
        return price.toFixed(1)
    }


    qtyChange(value, data) {
        console.log(value)
        if (/^\d+$/.test(value)) {
            data.qty = value
        }
    }

    discountChange(value, data) {
        if (/^\d+$/.test(value)) {
            data.discount = value
        }
    }

    chargesChange(value, data) {
        if (/^\d+$/.test(value)) {
            data.charges = value
        }
    }
    priceChange(value, data) {
        if (/^\d+$/.test(value)) {
            data.allPrice = value
        }
    }

    additionalEditPriceChange(value, data) {
        if (/^\d+$/.test(value)) {
            data.price = value
        }
    }

    removeItems(index, additional) {
        if (additional) {
            this.additionalItems.splice(index, 1)
        } else {
            this.fakeData.splice(index, 1)
        }
    }

    orderAction() {
        if (this.props.route.params.order) {
            this.store.orderPost(this.store.orderData, this.additionalItems, this)
        } else {
            this.store.editPost(this.store.orderData, this.additionalItems, this.props.route.params.data.id, this)
        }

    }

    edit(data, index, additional) {
        if (!additional) {
            if (this.props.route.params.order) {
                this.props.navigation.navigate('SuitStyle', { data: JSON.parse(JSON.stringify(data)), edit: true, index: index, order: true })
            } else {
                this.props.navigation.navigate('SuitStyle', { data: JSON.parse(JSON.stringify(data)), edit: true, index: index, order: false, member: this.props.route.params.member, sales: this.props.route.params.sales, recordData: this.props.route.params.data, additionalItems: this.additional })
            }
        }
    }

    renderItem(data, index, additional) {
        return (
            <View style={{ width: width - 40, flexDirection: 'row', marginTop: 10 }}>

                <TouchableOpacity style={{ flex: 0.3, alignItems: 'center', flexDirection: 'row' }}
                    onPress={() => { this.edit(data, index, additional) }}>
                    <Text style={[styles.itemsText, { marginRight: 10 }]}>
                        {index + 1}
                    </Text>
                    {additional ? (<View style={{ justifyContent: 'center', alignItems: 'center', borderWidth: 1, borderRadius: 5, width: 150 }}>

                        <TextInput style={[styles.itemsText, { width: 140 }]}
                            value={data.name} maxLength={50}
                            onChangeText={text => data.name = text} />
                    </View>) : (<Text style={styles.itemsText}>
                        {this.props.route.params.order ? data.nameEn : data.suit.nameEn}
                    </Text>)}

                </TouchableOpacity>
                <View style={{ flex: 0.125, justifyContent: 'center', alignItems: 'center' }}>
                    <View style={{ justifyContent: 'center', alignItems: 'center', borderWidth: 1, borderRadius: 5, width: 70 }}>

                        <TextInput style={[styles.itemsText, { width: 70 }]}
                            textAlign={'center'} value={'' + data.qty} keyboardType={'number-pad'} maxLength={3}
                            onChangeText={text => this.qtyChange(text, data)} />
                    </View>
                </View>
                <View style={{ flex: 0.125, justifyContent: 'center', alignItems: 'center' }}>
                    {additional ? (<View style={{ justifyContent: 'center', alignItems: 'center', borderWidth: 1, borderRadius: 5, width: 70 }}>
                        {
                            this.props.route.params.order ? (<TextInput style={[styles.itemsText, { width: 70 }]}
                                textAlign={'center'} value={'' + data.allPrice} keyboardType={'number-pad'} maxLength={6}
                                onChangeText={text => { this.priceChange(text, data) }} />) : (<TextInput style={[styles.itemsText, { width: 70 }]}
                                    textAlign={'center'} value={'' + data.price} keyboardType={'number-pad'} maxLength={6}
                                    onChangeText={text => { this.additionalEditPriceChange(text, data) }} />)
                        }

                    </View>) : (<Text style={styles.itemsText}>
                        {data.allPrice}
                    </Text>)}

                </View>
                <View style={{ flex: 0.125, justifyContent: 'center', alignItems: 'center' }}>
                    {additional && !this.props.route.params.order ? (<View />) : (<View style={{ justifyContent: 'center', alignItems: 'center', borderWidth: 1, borderRadius: 5, width: 90 }}>

                        <TextInput style={[styles.itemsText, { width: 70 }]}
                            textAlign={'center'} value={'' + data.discount} keyboardType={'number-pad'} maxLength={2}
                            onChangeText={text => this.discountChange(text, data)} />
                        <Text style={[styles.itemsText, { position: 'absolute', right: 10 }]}>%</Text>
                    </View>)}


                </View>
                <View style={{ flex: 0.125, justifyContent: 'center', alignItems: 'center' }}>
                    {additional && !this.props.route.params.order ? (<View />) : (
                        <View style={{ justifyContent: 'center', alignItems: 'center', borderWidth: 1, borderRadius: 5, width: 100 }}>

                            <TextInput style={[styles.itemsText, { width: 70 }]}
                                textAlign={'center'} value={'' + data.charges} keyboardType={'number-pad'} maxLength={7}
                                onChangeText={text => this.chargesChange(text, data)} />
                            <Text style={[styles.itemsText, { position: 'absolute', left: 5 }]}>$</Text>
                        </View>)}

                </View>

                <View style={{ flex: 0.2, justifyContent: 'center', alignItems: 'center' }}>
                    {additional && !this.props.route.params.order ? (<View />) : (
                        <Text style={styles.itemsText}>
                            {this.amountHandler(data)}
                        </Text>)}
                </View>
                {this.props.route.params.order ? (<TouchableOpacity style={{ width: 40, height: 20, justifyContent: 'center', alignItems: 'center', position: 'absolute', right: 0, }}
                    onPress={() => {
                        Alert.alert(
                            "",
                            "Are you sure to remove this item ?",
                            [
                                {
                                    text: "Cancel",
                                    onPress: () => console.log("Cancel Pressed"),
                                    style: "cancel"
                                },
                                { text: "Yes", onPress: () => this.removeItems(index, additional) }
                            ]
                        );
                    }}>
                    <Text style={styles.itemsText}>
                        -
                    </Text>
                </TouchableOpacity>) : (<View />)}

            </View>
        )
    }


    render() {
        return (

            <SafeAreaView
                style={{
                    flex: 1,
                    backgroundColor: 'white',
                    alignItems: 'center'
                }}>
                <Loading loading={this.store.loading} />
                <View style={{ flexDirection: 'row', marginTop: Platform.OS === 'ios' ? 40 : getStatusBarHeight(), }}>
                    <Image source={images.title.logo} />
                    {this.props.route.params.order ? (<View />) : (<TouchableOpacity style={{ position: 'absolute', left: -450 }}
                        onPress={() => this.props.navigation.navigate('OrderRecord')}>
                        <Icon name='arrow-left' size={40} color={colors.buttonColor} />
                    </TouchableOpacity>)}

                </View>
                <View style={{ flex: 1 }}>
                    <KeyboardAwareScrollView>
                        <View style={{ flex: 0.9, alignItems: 'center' }}>
                            <Text style={{ fontSize: 24, color: colors.buttonColor, marginTop: 10 }}>
                                {'Confilm Order'}
                            </Text>
                            {/* <View style={{ width: width }}>
                                <Text style={styles.headerText}>
                                    {"Date: " + moment(this.date).format('DD/MM/YYYY')}
                                </Text>
                                <Text style={styles.headerText}>
                                    {"Sales: " + this.store.user.user.name}
                                </Text>
                                <Text style={[styles.headerText, { marginTop: 5 }]}>
                                    {"Bill To: " + this.store.customer.name}
                                </Text>
                                <Text style={styles.headerText}>
                                    {"Contact: " + this.store.customer.mobile}
                                </Text>
                            </View> */}

                            {this.props.route.params.order ? (<View style={{ width: width }}>
                                <Text style={styles.headerText}>
                                    {"Date: " + moment(this.date).format('DD/MM/YYYY')}
                                </Text>
                                <Text style={styles.headerText}>
                                    {"Sales: " + this.store.user.user.name}
                                </Text>
                                <Text style={[styles.headerText, { marginTop: 5 }]}>
                                    {"Bill To: " + this.store.customer.name}
                                </Text>
                                <Text style={styles.headerText}>
                                    {"Contact: " + this.store.customer.mobile}
                                </Text>
                            </View>) : (<View style={{ width: width }}>
                                <Text style={styles.headerText}>
                                    {"Date: " + moment(this.props.route.params.data.created).format('DD/MM/YYYY')}
                                </Text>
                                <Text style={styles.headerText}>
                                    {"Sales: " + this.props.route.params.sales.name}
                                </Text>
                                <Text style={[styles.headerText, { marginTop: 5 }]}>
                                    {"Bill To: " + this.props.route.params.member.name}
                                </Text>
                                <Text style={styles.headerText}>
                                    {"Contact: " + this.props.route.params.member.mobile}
                                </Text>
                            </View>)}

                            <View style={{ width: width - 40, height: 40, flexDirection: 'row' }}>
                                <View style={{ flex: 0.3, justifyContent: 'center', }}>
                                    <Text style={styles.itemsTitleText}>
                                        {'Item'}
                                    </Text>
                                </View>
                                <View style={{ flex: 0.125, justifyContent: 'center', alignItems: 'center' }}>
                                    <Text style={styles.itemsTitleText}>
                                        {'Qty'}
                                    </Text>
                                </View>
                                <View style={{ flex: 0.125, justifyContent: 'center', alignItems: 'center' }}>
                                    <Text style={styles.itemsTitleText}>
                                        {'Unit Price'}
                                    </Text>
                                </View>
                                <View style={{ flex: 0.125, justifyContent: 'center', alignItems: 'center' }}>
                                    <Text style={styles.itemsTitleText}>
                                        {'Discount'}
                                    </Text>
                                </View>
                                <View style={{ flex: 0.125, justifyContent: 'center', alignItems: 'center' }}>
                                    <Text style={styles.itemsTitleText}>
                                        {'Charges'}
                                    </Text>
                                </View>

                                <View style={{ flex: 0.2, justifyContent: 'center', alignItems: 'center' }}>
                                    <Text style={styles.itemsTitleText}>
                                        {'Amount (HKD)'}
                                    </Text>
                                </View>

                            </View>
                            <ScrollView>
                                {this.store.orderData.map((items, index) => {
                                    return (
                                        this.renderItem(items, index, false)
                                    )
                                })}
                                <View style={{ width: width - 40 }}>
                                    <Text style={[styles.itemsTitleText, { marginTop: 40, fontWeight: '800' }]}>
                                        {'Additional Item'}
                                    </Text>
                                </View>
                                {this.additionalItems.map((items, index) => {
                                    return (
                                        this.renderItem(items, index, true)
                                    )
                                })}
                                {this.props.route.params.order ? (<TouchableOpacity
                                    onPress={() => {
                                        this.additionalItems.push(
                                            {
                                                type: 1,
                                                name: '',
                                                qty: 1,
                                                price: 0,
                                                allPrice: 0,
                                                discount: 0,
                                                charges: 0,
                                            }
                                        )
                                    }}>
                                    <Text style={[styles.itemsText, { marginTop: 20 }]}>
                                        {'Add +'}
                                    </Text>
                                </TouchableOpacity>) : (<View />)}

                                <View style={{ flex: 1, alignItems: 'flex-end', marginTop: 20 }}>
                                    <Text style={{ fontSize: 25, color: colors.buttonColor }}>
                                        {'Total: ' + this.totalPriceHandler()}
                                    </Text>
                                </View>
                            </ScrollView>
                        </View>
                    </KeyboardAwareScrollView>
                    <View style={{ width: width, justifyContent: 'center', alignItems: 'center' }}>
                        <CustomLoginButton title={'確定'} width={3} onPress={() => { this.orderAction() }} />
                    </View>


                    <View style={{ flex: 0.1, justifyContent: 'center', alignItems: 'center', }}>


                        <Setting self={this} settingViewAble={this.settingViewAble} onPress={() => { this.settingViewAble = !this.settingViewAble }} />


                    </View>

                </View>
            </SafeAreaView>

        );
    }
}))

const styles = StyleSheet.create({
    headerText: {
        color: colors.buttonColor,
        fontSize: 17,
        marginLeft: 20,
    },
    itemsTitleText: {
        fontSize: 17,
        fontWeight: '600',
        color: colors.buttonColor
    },
    itemsText: {
        fontSize: 17,
        color: colors.buttonColor
    },
    rowView: {
        flexDirection: 'row', width: 800, height: 50, justifyContent: 'center', alignItems: 'center',
    },
    rowLeftView: {
        flex: 0.3, alignItems: 'flex-end', justifyContent: 'center',
    },
    rowRightView: {
        flex: 0.6, flexDirection: 'row', marginLeft: 40, alignItems: 'center'
    },
    rowTitleView: {
        color: colors.buttonColor, fontSize: 20
    },
    inputTextBorder: {
        width: 350, height: 40, justifyContent: 'center', alignItems: 'center', flexDirection: 'row', borderWidth: 1, borderColor: colors.buttonColor, borderRadius: 10
    },
    inputTextView: {
        color: colors.buttonColor,
        width: 350,
        height: 40,
        fontSize: 20,
        marginLeft: 10,
        marginBottom: Platform.OS === 'ios' ? 3 : 0,
        paddingVertical: 0,
    }
});

export default Order