import * as React from "react";
import {Animated, StyleProp, StyleSheet, TextStyle, View} from 'react-native';
import {reduxTools} from '@yoronsoft/js-utils';
import {LoadingEmitterParams} from "./loading";
import {configEmitterParams, loadingOperate, configName} from "./config";
import PopupLayerView, {popupLayer} from "../popupLayer";
import app from "../app";
import Basic from '../basicPage';
import {ThemeCss} from "../app";

const useEmitterParams = () => {
    const [isAnimated, setIsAnimated] = React.useState(false);
    const [value, setValue] = React.useState(undefined);
    const [content, setContent] = React.useState(undefined);
    React.useLayoutEffect(() => {
        let contentArr = '';
        const emitterData = app.emitter.get(configEmitterParams, (res: LoadingEmitterParams) => {
            if (res.type === loadingOperate.show) {
                if (res.value) setValue(res.value);
                if (res.content) contentArr = res.content;
            } else if (res.type === loadingOperate.content) {
                contentArr += `|${res.content}`;
            } else if (res.type === loadingOperate.hide) {
                contentArr = undefined;
                setValue(undefined)
            }
            setContent(contentArr);
            setIsAnimated(res.display);
        });
        return () => emitterData.remove();
    }, [])
    return {isAnimated, value, content}
}

const LoadingInit: React.FC = () => {
    const css = app.theme.useGet<ThemeCss>();
    const styles = styleSheet(css);
    const [animatedOpacity] = React.useState(new Animated.Value(0));
    const [animatedTextStartOpacity] = React.useState(new Animated.Value(0));
    const [animatedTextEndOpacity] = React.useState(new Animated.Value(0));
    const [animatedTextStartXY] = React.useState(new Animated.ValueXY({x: 0, y: 20}));
    const [animatedTextEndXY] = React.useState(new Animated.ValueXY({x: 0, y: 0}));
    // const [display, setDisplay] = React.useState(false);
    const paramsData = useEmitterParams();
    const contentList = paramsData.content ? paramsData.content.split('|') : [];
    React.useLayoutEffect(() => {
        const emitterData = app.emitter.get(configEmitterParams, (res: LoadingEmitterParams) => {
            reduxTools.update(configEmitterParams, res);
            // if (res.display) setDisplay(true);
            if (res.display) popupLayer.show(configName);
            else popupLayer.hide(configName);
        });
        return () => emitterData.remove();
    }, [])

    React.useEffect(() => {
        const defaultParams = {duration: 150, useNativeDriver: true};
        if (paramsData.isAnimated) {
            //  show
            Animated.parallel([
                Animated.timing(animatedOpacity, {
                    toValue: 1, ...defaultParams
                })
            ]).start();
        } else {
            //  hide
            Animated.parallel([
                Animated.timing(animatedOpacity, {
                    toValue: 0, ...defaultParams
                })
            ]).start();
        }
    }, [paramsData.isAnimated])

    React.useEffect(() => {
        const defaultParams = {duration: 150, useNativeDriver: true};
        if (contentList.length > 0) {
            //  show
            Animated.parallel([
                Animated.timing(animatedTextStartOpacity, {
                    toValue: 1, ...defaultParams
                }),
                Animated.timing(animatedTextStartXY, {
                    toValue: {x: 0, y: 0}, ...defaultParams
                })
            ]).start();
        }
        if (contentList.length > 1) {
            //  hide
            Animated.parallel([
                Animated.timing(animatedTextEndOpacity, {
                    toValue: 0, ...defaultParams
                }),
                Animated.timing(animatedTextEndXY, {
                    toValue: {x: 0, y: 20}, ...defaultParams
                })
            ]).start();
        }

    }, [paramsData.content])

    // if (!display) return <View/>;

    const loadingStyle: StyleProp<TextStyle> = {
        width: css.loading.width, height: css.loading.height,
        backgroundColor: css.loading.bg, borderRadius: css.loading.borderRadius ?? 10,
        justifyContent: 'center', alignItems: 'center',
    }

    return <PopupLayerView name={configName} width={css.width} height={css.height} bg={'rgba(0,0,0,0)'}
                           direction={popupLayer.direction.none} animated={popupLayer.animated.fade}>
        <View style={[styles.view, css.rowAroundCenter, css.colAroundCenter]}>
            <Animated.View style={[loadingStyle, {opacity: animatedOpacity}]}>
                {paramsData.value ?? <View/>}
                <View style={[styles.contentStyle, {flex: 1}]}>
                    {
                        contentList.map((item, key) => {
                            if (contentList.length - 2 === key) {
                                const anStyle = {
                                    opacity: animatedTextEndOpacity,
                                    transform: [{translateY: animatedTextEndXY.y}]
                                }
                                return <Animated.View key={key} style={[styles.contentItem, anStyle]}>
                                    <Basic.Text text={item[contentList.length - 1] ?? ''} style={styles.contentText}
                                                size={12}/>
                                </Animated.View>
                            }
                            if (contentList.length - 1 === key) {
                                const anStyle = {
                                    opacity: animatedTextStartOpacity,
                                    transform: [{translateY: animatedTextStartXY.y}]
                                }
                                return <Animated.View key={key} style={[styles.contentItem, anStyle]}>
                                    <Basic.Text text={item ?? ''} style={styles.contentText} width={css.loading.width}
                                                size={12} line={2} textAlign={'center'}/>
                                </Animated.View>
                            }
                        })
                    }
                </View>
            </Animated.View>
        </View>
    </PopupLayerView>
    //
    // return <Animated.View style={[styles.view, css.rowAroundCenter, css.colAroundCenter, {
    //     backgroundColor: css.loading.mask,
    //     opacity: animatedOpacity
    // }]}>
    //
    // </Animated.View>
}

const styleSheet = (css: ThemeCss) => StyleSheet.create({
    view: {
        flex: 1,
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        zIndex: 30,
        width: css.width,
    },
    contentStyle: {
        position: 'absolute', left: 0, right: 0, bottom: 0, height: 40,
        justifyContent: 'center', alignItems: 'center', overflow: 'hidden'
    },
    contentItem: {
        position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, height: 40,
        ...css.colAroundCenter,
    },
    contentText: {color: '#fff', lineHeight: 20, fontSize: 12},
});

export default LoadingInit
