import {
    useImperativeHandle,
    forwardRef,
    useEffect,
    useRef
} from "react";
import {
    Animated,
    Easing,
    View
} from "react-native";
import type IModalProps from "./type";
import {
    type IModalRef
} from "./type";
import stylesheet from "./stylesheet";
import {
    NCoreUIKitTheme
} from "../../core/hooks";
import {
    type RefForwardingComponent
} from "../../types";
import {
    Portal
} from "react-native-portalize";

/**
 * A generic modal
 * @param props {@link IModalProps}
 * @returns Element
 */
const Modal: RefForwardingComponent<IModalRef, IModalProps> = ({
    isDisabledOverlay = false,
    isOverlayVisible = true,
    alignContent = "center",
    onOverlayPress,
    contentStyle,
    children,
    style
}, ref) => {
    const {
        colors
    } = NCoreUIKitTheme.useContext();

    const scaleAnim = useRef(new Animated.Value(0)).current;

    useEffect(() => {
        Animated.timing(scaleAnim, {
            easing: Easing.out(Easing.back(1.5)),
            useNativeDriver: true,
            duration: 350,
            toValue: 1
        }).start();
    }, []);

    useImperativeHandle(
        ref,
        () => ({
            closeAnimation
        }),
        []
    );

    const closeAnimation = (onClosed?: () => void) => {
        Animated.timing(scaleAnim, {
            easing: Easing.in(Easing.ease),
            useNativeDriver: true,
            duration: 250,
            toValue: 0
        }).start(({
            finished
        }) => {
            if(finished) {
                if(onClosed) onClosed();
            }
        });
    };

    const renderOverlay = () => {
        if(!isOverlayVisible) {
            return null;
        }

        return <View
            style={[
                stylesheet.overlay
            ]}
            onClick={() => {
                if(isDisabledOverlay) {
                    return;
                }

                if(onOverlayPress) onOverlayPress({
                    closeAnimation
                });
            }}
        />;
    };

    const renderContent = () => {
        if(!children) {
            return null;
        }

        return <View
            style={[
                contentStyle,
                stylesheet.content
            ]}
        >
            {children}
        </View>;
    };

    return <Portal>
        <Animated.View
            style={[
                style,
                {
                    justifyContent: alignContent === "center" ? "center" : undefined,
                    alignItems: alignContent === "center" ? "center" : "baseline",
                    backgroundColor: colors.system.scrim,
                    transform: [{
                        scale: scaleAnim
                    }]
                }
            ]}
        >
            {renderOverlay()}
            {renderContent()}
        </Animated.View>
    </Portal>;
};
export default forwardRef(Modal);
