import React from 'react';
import { SafeAreaView, Text, Image, Alert, Linking, View, TouchableOpacity, TouchableHighlight, ScrollView, StyleSheet, DatePickerIOS, Picker, FlatList } from 'react-native';
import { inject, observer } from "mobx-react"
import { observable, makeObservable } from 'mobx'
import SizeInput from '../../components/sizeInput'
import RNPickerSelect from 'react-native-picker-select';
import CustomTextInput from '../../components/customTextInput'
import { images } from '../../assets/images/imageIndex';
import AsyncStorage from '@react-native-community/async-storage';
import { width, height } from '../../services/screen';
import CustomLoginButton from '../../components/customLoginButton'
import Setting from '../../components/setting'
import { TabView, SceneMap, TabBar } from 'react-native-tab-view';
import { colors } from '../../assets/styles/colors-theme';
import { getStatusBarHeight } from 'react-native-status-bar-height';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import Menu, {
    MenuProvider,
    MenuTrigger,
    MenuOptions,
    MenuOption,
    renderers,
} from 'react-native-popup-menu';

const { SlideInMenu } = renderers;

const SuitStyle = inject("appStore")(observer(class SuitStyle extends React.Component {


    lang = this.props.appStore.lanuageSelection

    buttonSelected = 0

    data = null

    settingViewAble = false

    optionsIndex = 0

    index = 0;

    constructor(props) {
        super(props);
        this.store = props.appStore;
        makeObservable(this, {

            lang: observable,

            buttonSelected: observable,

            data: observable,

            settingViewAble: observable,
            optionsIndex: observable,

            index: observable,

        })
        this.data = this.props.route.params.data
        //  this.renderSelectOption()
    }



    // @observable routes = [
    //     { key: 'first', title: 'First' },
    //     { key: 'second', title: 'Second' },
    // ];




    async componentWillMount() {
        console.log(this.data)
        if (!this.props.route.params.edit) {
            this.data.options.map((items, index) => {
                if (items.valueType == 2) {
                    if (items.selections.length > 0) {
                        items.value = items.selections[0].id
                    } else {
                        items.value = ''
                    }
                } else {
                    items.value = ''
                }
                items.index = 0
            })
        }
        console.log(this.data)
        const index = this.data.options.findIndex(element => element.type == 2 && element.previewIndex == 0)
        if (index >= 0) {
            this.optionsIndex = index
        }
        console.log(this.optionsIndex)

    }


    init() {
        if (!this.props.route.params.edit) {
            this.data.options.map((items, index) => {
                if (items.valueType == 2) {
                    if (items.selections.length > 0) {
                        items.value = items.selections[0].id
                    } else {
                        items.value = ''
                    }
                } else {
                    items.value = '1'
                }
                items.index = 0
            })
        }

        console.log(this.data)
        const index = this.data.options.findIndex(element => element.type == 2 && element.previewIndex == 0)
        if (index >= 0) {
            this.optionsIndex = index
        }
        console.log(this.optionsIndex)
    }

    async sortAction() {

        const sortedArray = this.data.options.sort((a, b) => a.previewIndex < b.previewIndex);
        console.log(sortedArray)
        this.data.options.replace(sortedArray);


    }

    pushSelectImages() {
        this.selectImages = []
        this.selectImages = this.allStyle[this.buttonSelected].images
    }

    renderSelectImages() {
        if (this.optionsIndex >= 0) {
            return (
                <ScrollView horizontal={true} >
                    {
                        this.data.options[this.optionsIndex].selections.map((items, index) => {

                            return (
                                <TouchableOpacity style={{ justifyContent: 'center', alignItems: 'center', height: 120, width: 120, }}
                                    onPress={() => { this.data.options[this.optionsIndex].index = index; this.data.options[this.optionsIndex].value = items.id }}>
                                    <Image source={{ uri: items.imageListingURL }} style={{ width: 120, height: 120 }} />
                                </TouchableOpacity>
                            )


                        })
                    }
                </ScrollView>
            )
        }
    }

    renderSelectOption() {
        var count = 0;
        var selection = []
        var matrix = [];
        this.data.options.map((items, index) => {
            if (items.type == 2) {
                count += 1;
                matrix.push(items);
                if (count % 2 == 0) {
                    selection.push(matrix)
                    matrix = []
                }
            }
        })
        if (matrix.length > 0) {
            selection.push(matrix)
            matrix = []
        }
        console.log(selection)

        return (
            <View style={{ flex: 1 }}>
                {selection.map((items, index) => {
                    return (
                        <View style={{ flex: 1, flexDirection: 'row' }}>
                            {items.map((item, i) => {
                                return (
                                    <View style={{ flex: 1 }}>
                                        <View
                                            style={{
                                                backgroundColor: 'white',
                                                height: 20,
                                                borderRadius: 15,
                                                width: 220,
                                                alignItems: 'center',
                                                marginTop: 20,
                                                flexDirection: 'row'

                                            }}>
                                            <Text style={{ color: colors.buttonColor, marginRight: 5 }}>
                                                {this.store.languageHandler(this.lang, item)}
                                            </Text>
                                            <View style={{ width: 200, height: 20, justifyContent: 'center', alignItems: 'center', flexDirection: 'row', borderWidth: 1, borderColor: colors.buttonColor, borderRadius: 5 }}>

                                                <Text style={{
                                                    color: colors.buttonColor,
                                                }}>
                                                    {this.store.languageHandler(this.lang, item.selections[item.index])}
                                                </Text>
                                            </View>

                                        </View>
                                    </View>
                                )
                            })}
                        </View>
                    )
                })}
            </View>
        )
    }



    renderPreviewAndSelectOptions() {
        return (
            < View style={{ flex: 1 }}>
                <View style={{ flex: 0.6, justifyContent: 'center', alignItems: 'center', }}>
                    {this.data.options.map((items, index) => {
                        const previewType = items.previewOptions

                        if (items.type == 2 && items != null && items.selections.length > 0) {
                            console.log(items)
                            switch (this.index) {
                                case 0:
                                    console.log(previewType)
                                    if (previewType == 1 || previewType == 3 || previewType == 5 || previewType == 7) {

                                        if (items.selections[items.index].hasOwnProperty('imagePreviewURL'))
                                            return (
                                                <Image style={{ position: 'absolute', width: 400, height: 400 }} source={{ uri: items.selections[items.index].imagePreviewURL }} />
                                            )
                                    }
                                    break;
                                case 1:
                                    if (previewType == 2 || previewType == 3 || previewType == 6 || previewType == 7) {
                                        if (previewType == 2 || previewType == 6) {
                                            if (items.selections[items.index].hasOwnProperty('imagePreviewURL')) {
                                                return (
                                                    <Image style={{ position: 'absolute', width: 400, height: 400 }} source={{ uri: items.selections[items.index].imagePreviewURL }} />
                                                )
                                            }
                                        }
                                        else if (previewType == 3 || previewType == 7) {

                                            if (items.selections[items.index].hasOwnProperty('imagePreview2URL')) {
                                                console.log(items.name + " : " + items.selections[items.index].imagePreview2URL)
                                                return (
                                                    <Image style={{ position: 'absolute', width: 400, height: 400 }} source={{ uri: items.selections[items.index].imagePreview2URL }} />
                                                )
                                            }
                                        }
                                    }
                                    break;
                                case 2: if (previewType == 4 || previewType == 5 || previewType == 6, previewType == 7) {

                                    if (previewType == 4) {
                                        if (items.selections[items.index].hasOwnProperty('imagePreviewURL')) {
                                            return (
                                                <Image style={{ position: 'absolute', width: 400, height: 400 }} source={{ uri: items.selections[items.index].imagePreviewURL }} />
                                            )
                                        }
                                    } else if (previewType == 5 || previewType == 6) {
                                        if (items.selections[items.index].hasOwnProperty('imagePreview2URL')) {
                                            return (
                                                <Image style={{ position: 'absolute', width: 400, height: 400 }} source={{ uri: items.selections[items.index].imagePreview2URL }} />
                                            )
                                        }
                                    } else if (previewType == 7) {
                                        if (items.selections[items.index].hasOwnProperty('imagePreview3URL')) {
                                            return (
                                                <Image style={{ position: 'absolute', width: 400, height: 400 }} source={{ uri: items.selections[items.index].imagePreview3URL }} />
                                            )
                                        }
                                    }


                                }
                                    break;
                            }

                        }
                    })}

                </View>
                <View style={{ flex: 0.3, }}>
                    <View style={{ margin: 20, }}>
                        {this.renderStyleButtons()}
                        {this.renderSelectImages()}
                    </View>
                </View>
            </View >
        )
    }

    returnImage() {

    }

    async idToIndex(id, index) {
        const newIndex = await this.data.options.findIndex(element => element.id == id)
        if (newIndex >= 0) {
            console.log(newIndex)
            this.optionsIndex = newIndex
        } else {

        }
    }

    renderStyleButtons() {

        return (
            <ScrollView horizontal={true} >
                {this.data.options.map((items, index) => {
                    const previewType = items.previewOptions
                    if (items.type == 2) {
                        switch (this.index) {
                            case 0:
                                if (previewType == 1 || previewType == 3 || previewType == 5 || previewType == 7) {
                                    return (
                                        <TouchableOpacity style={{ justifyContent: 'center', alignItems: 'center', height: 40, width: 120, borderBottomWidth: this.optionsIndex == index ? 3 : 1, borderBottomColor: colors.buttonColor }}
                                            onPress={() => { this.idToIndex(items.id, index) }}>
                                            <Text style={{ fontWeight: '800', color: colors.buttonColor }}>
                                                {this.store.languageHandler(this.lang, items)}
                                            </Text>
                                        </TouchableOpacity>
                                    )

                                }
                                break;
                            case 1:
                                if (previewType == 2 || previewType == 3 || previewType == 6 || previewType == 7) {
                                    return (
                                        <TouchableOpacity style={{ justifyContent: 'center', alignItems: 'center', height: 40, width: 120, borderBottomWidth: this.optionsIndex == index ? 3 : 1, borderBottomColor: colors.buttonColor }}
                                            onPress={() => { this.idToIndex(items.id, index) }}>
                                            <Text style={{ fontWeight: '800', color: colors.buttonColor }}>
                                                {this.store.languageHandler(this.lang, items)}
                                            </Text>
                                        </TouchableOpacity>
                                    )
                                }
                                break;
                            case 2:
                                if (previewType == 4 || previewType == 5 || previewType == 6, previewType == 7) {
                                    return (
                                        <TouchableOpacity style={{ justifyContent: 'center', alignItems: 'center', height: 40, width: 120, borderBottomWidth: this.optionsIndex == index ? 3 : 1, borderBottomColor: colors.buttonColor }}
                                            onPress={() => { this.idToIndex(items.id, index) }}>
                                            <Text style={{ fontWeight: '800', color: colors.buttonColor }}>
                                                {this.store.languageHandler(this.lang, items)}
                                            </Text>
                                        </TouchableOpacity>
                                    )
                                }
                                break;
                        }
                    }
                })}
            </ScrollView>
        )
    }

    rendertype1Input() {
        var count = 0;
        var selection = []
        var matrix = [];
        this.data.options.map((items, index) => {
            if (items.type == 1) {
                count += 1;
                matrix.push(items);
                if (count % 2 == 0) {
                    selection.push(matrix)
                    matrix = []
                }
            }
        })
        if (matrix.length > 0) {
            selection.push(matrix)
            matrix = []
        }
        console.log(selection)

        return (
            <View style={{ flex: 1 }}>
                {selection.map((items, index) => {
                    return (
                        <View style={{ flex: 1, flexDirection: 'row', }}>
                            {items.map((item, i) => {
                                return (
                                    <View style={{ flex: 0.5, }}>
                                        <SizeInput
                                            title={this.store.languageHandler(this.lang, item)}
                                            unit={this.store.languageHandler(this.lang, item.unit)}
                                            value={item.value}
                                            onChangeText={text => {
                                                item.value = text;
                                            }}
                                            secureTextEntry={false}

                                        />
                                    </View>
                                )
                            })}
                        </View>
                    )
                })}
            </View>
        )
    }

    async sideClickAction(value) {
        this.index = value;
        var optionsIndex = 0
        switch (value) {
            case 0:
                optionsIndex = await this.data.options.findIndex(e => e.previewOptions == 1 || e.previewOptions == 3 || e.previewOptions == 5 || e.previewOptions == 7)
                console.log(optionsIndex)
                // if (optionsIndex >= 0) {
                //     this.optionsIndex = optionsIndex
                // }
                this.optionsIndex = optionsIndex
                break;
            case 1:
                optionsIndex = await this.data.options.findIndex(e => e.previewOptions == 2 || e.previewOptions == 3 || e.previewOptions == 7 || e.previewOptions == 7)
                console.log(optionsIndex)
                // if (optionsIndex >= 0) {
                //     this.optionsIndex = optionsIndex
                // }
                this.optionsIndex = optionsIndex
                break;
            case 2:
                optionsIndex = await this.data.options.findIndex(e => e.previewOptions == 4 || e.previewOptions == 5 || e.previewOptions == 7 || e.previewOptions == 7)
                console.log(optionsIndex)
                // if (optionsIndex >= 0) {
                //     this.optionsIndex = optionsIndex
                // }
                this.optionsIndex = optionsIndex
                break;
        }

    }

    renderType0Input() {
        var count = 0;
        var selection = []
        var matrix = [];
        this.data.options.map((items, index) => {
            if (items.type == 0) {
                count += 1;
                matrix.push(items);
                if (count % 2 == 0) {
                    selection.push(matrix)
                    matrix = []
                }
            }
        })
        if (matrix.length > 0) {
            selection.push(matrix)
            matrix = []
        }
        console.log(selection)

        return (
            <View style={{ flex: 1 }}>
                {selection.map((items, index) => {

                    return (
                        <View style={{ flex: 1, flexDirection: 'row' }}>
                            {items.map((item, i) => {
                                console.log(item.selections)

                                if (item != null) {
                                    if (item.valueType == 2) {
                                        return (
                                            <View style={{ flex: 1 }}>
                                                <View
                                                    style={{
                                                        backgroundColor: 'white',
                                                        height: 20,
                                                        borderRadius: 15,
                                                        width: 220,
                                                        alignItems: 'center',
                                                        marginTop: 20,
                                                        flexDirection: 'row'

                                                    }}>
                                                    <Text style={{ color: colors.buttonColor, marginRight: 5 }}>
                                                        {this.store.languageHandler(this.lang, item)}
                                                    </Text>
                                                    <Menu
                                                        name={item.nameEn}
                                                        renderer={SlideInMenu}
                                                        onSelect={value => {
                                                            item.index = value;
                                                            item.value = item.selections[value].id;
                                                        }}>
                                                        <MenuTrigger style={{ width: 200, height: 20, justifyContent: 'center', alignItems: 'center', flexDirection: 'row', borderWidth: 1, borderColor: colors.buttonColor, borderRadius: 5 }}>

                                                            <Text style={{
                                                                color: colors.buttonColor,
                                                            }}>
                                                                {this.store.languageHandler(this.lang, item.selections[item.index])}

                                                            </Text>
                                                        </MenuTrigger>
                                                        <MenuOptions
                                                            customStyles={{
                                                                optionText: {
                                                                    margin: 5,
                                                                    color: colors.buttonColor,
                                                                    fontSize: 20,
                                                                },
                                                                optionWrapper: {
                                                                    backgroundColor: 'white',
                                                                    alignItems: 'center',
                                                                },
                                                            }}>

                                                            <ScrollView style={{ height: 200 }}>
                                                                {item.selections.map((obj, ob) => {
                                                                    return <MenuOption value={ob} text={this.store.languageHandler(this.lang, obj)} />;
                                                                })}
                                                            </ScrollView>
                                                        </MenuOptions>
                                                    </Menu>
                                                </View>
                                            </View>
                                        )
                                    } else {
                                        return (
                                            <View style={{ flex: 1, }}>
                                                <SizeInput
                                                    title={this.store.languageHandler(this.lang, item)}
                                                    unit={null}
                                                    value={item.value}
                                                    onChangeText={text => {
                                                        item.value = text;
                                                    }}
                                                    secureTextEntry={false}

                                                />
                                            </View>
                                        )
                                    }
                                }
                            })}
                        </View>
                    )

                })}
            </View>
        )

    }

    handleSetTabIndex = (index: number) => {
        console.log('changed', index);
        // This was our initial solution which is normally fine with mobx but does not work with tab-view
        this.index = index;

        // This is the fix we had to make, I suspect this lib is doing a memoization with reference
        // equality checking on tabState
        /*
        this.tabState = {
          routes: [...this.tabState.routes],
          index
        };
        */
    };

    async confirmAction() {
        //this.props.navigation.navigate('Confirm')
        var allInput = false
        console.log(this.data)
        for (var i = 0; i < this.data.options.length; i++) {
            if (this.data.options[i].value == '') {
                Alert.alert(
                    '',
                    'Please input all fields',
                    [

                        { text: 'OK', onPress: () => console.log('OK Pressed') },
                    ],
                    { cancelable: false },
                );
                break;

            }
            if (i == this.data.options.length - 1 && this.data.options[i].value != '') {
                allInput = true
            }
        }
        if (allInput) {
            if (this.props.route.params.edit) {
                this.store.orderData[this.props.route.params.index] = JSON.parse(JSON.stringify(this.data))
                if (this.props.route.params.order) {
                    this.props.navigation.navigate('Order', { order: true })
                } else {
                    this.props.navigation.navigate('Order', { order: false, edit: true, member: this.props.route.params.member, sales: this.props.route.params.sales, data: this.props.route.params.recordData, additionalItems: this.props.route.params.additional })
                }
            } else {
                this.props.navigation.navigate('ConfirmSuit', { data: this.data, order: true })
            }
        }
    }

    renderTabBar = props => (
        <TabBar
            {...props}
            activeColor={colors.buttonColor}
            inactiveColor={colors.buttonColor}
            indicatorStyle={{ backgroundColor: colors.buttonColor }}
            style={{ backgroundColor: 'white' }}
        />
    );

    render() {
        return (
            <MenuProvider
                style={{
                    flex: 1,
                    backgroundColor: 'white',
                }}>

                <View style={{ flex: 1 }}>
                    <View style={{ flex: 0.9, flexDirection: 'row' }}>
                        <View style={{ flex: 0.52, }}>
                            <KeyboardAwareScrollView>
                                <View style={{ marginTop: Platform.OS === 'ios' ? 40 : getStatusBarHeight() }}>
                                    <Image style={{ marginLeft: 40, }} source={images.title.logo} />

                                    <Text style={{ margin: 40, fontWeight: '700', color: colors.buttonColor, fontSize: 20 }}>
                                        {this.store.languageHandler(this.lang, this.data)}
                                    </Text>
                                    <View style={{ marginLeft: 40, marginRight: 40 }}>
                                        {this.renderType0Input()}
                                        <View style={styles.lineStyle} />

                                        {this.rendertype1Input()}
                                        <View style={styles.lineStyle} />
                                    </View>


                                    <View style={{ marginRight: 40, marginLeft: 40 }}>

                                        {this.renderSelectOption()}
                                    </View>

                                </View>
                            </KeyboardAwareScrollView>
                        </View>
                        <View style={{ flex: 0.48 }}>
                            <View style={{ flex: 0.1, flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center', }}>
                                <CustomLoginButton title={'返回'} width={6} onPress={() => { this.props.navigation.goBack() }} />
                                <CustomLoginButton title={'確認 '} width={6} onPress={() => { this.confirmAction() }} />
                            </View>
                            <View style={{ flexDirection: 'row' }}>
                                <TouchableOpacity style={{ width: 150, height: 50, borderBottomColor: colors.buttonColor, borderBottomWidth: this.index == 0 ? 2 : 0, justifyContent: 'center', alignItems: 'center' }}
                                    onPress={() => this.sideClickAction(0)}>
                                    <Text style={{ fontWeight: '800', color: colors.buttonColor }}>
                                        {this.store.text.front}
                                    </Text>
                                </TouchableOpacity>
                                <TouchableOpacity style={{ width: 150, height: 50, borderBottomColor: colors.buttonColor, borderBottomWidth: this.index == 1 ? 2 : 0, justifyContent: 'center', alignItems: 'center' }}
                                    onPress={() => this.sideClickAction(1)}>
                                    <Text style={{ fontWeight: '800', color: colors.buttonColor }}>
                                        {this.store.text.back}
                                    </Text>
                                </TouchableOpacity>
                                <TouchableOpacity style={{ width: 150, height: 50, borderBottomColor: colors.buttonColor, borderBottomWidth: this.index == 2 ? 2 : 0, justifyContent: 'center', alignItems: 'center' }}
                                    onPress={() => this.sideClickAction(2)}>
                                    <Text style={{ fontWeight: '800', color: colors.buttonColor }}>
                                        {this.store.text.side}
                                    </Text>
                                </TouchableOpacity>
                            </View>
                            {this.renderPreviewAndSelectOptions()}

                        </View>



                    </View>

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

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

                </View>
                <View style={{ position: 'absolute', height: height * 0.7, width: 2, backgroundColor: colors.buttonColor, left: width * 0.52, top: 100 }} />

            </MenuProvider >
        );
    }
}))
const styles = StyleSheet.create({
    lineStyle: {
        flex: 1, height: 1, backgroundColor: colors.buttonColor, marginTop: 40, marginBottom: 20
    }
});

export default SuitStyle