import React from 'react';
import { View, type ViewStyle, Animated } from 'react-native';
import { initialWindowMetrics } from 'react-native-safe-area-context';
import { getWidgetStyles, getWidgetVisibility } from '../styles/widgetStyles';
import { FIXED_Z_INDEX } from '../constants/Constants';
import { CloseButton } from './CloseButton';
import { useHeightAnimation } from '../hooks/useHeightAnimation';

interface OverlayWidgetProps {
    visible: boolean;
    width: number;
    height: number;
    position: 'top' | 'bottom';
    children?: React.ReactNode;
    onClose?: () => void;
}

export const OverlayWidget: React.FC<OverlayWidgetProps> = ({
    visible,
    width,
    height,
    position,
    children,
    onClose,
}) => {
    const insets =
        initialWindowMetrics?.insets ?? { top: 0, bottom: 0, left: 0, right: 0 };

    const { animatedHeightStyle } = useHeightAnimation(height);

    const containerStyle: ViewStyle = {
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        width: '100%',
        height: '100%',
        zIndex: FIXED_Z_INDEX,
        pointerEvents: 'box-none',
    };

    const contentStyle = [
        getWidgetStyles(position).content,
        {
            width,
            pointerEvents: 'auto' as const,
            ...(position === 'top' && {
                top: insets.top,
            }),
            ...(position === 'bottom' && {
                bottom: insets.bottom,
            }),
        },
    ];

    return (
        <>
            {visible && (
                <View style={[containerStyle, getWidgetVisibility(visible)]}>
                    <Animated.View
                        style={[
                            contentStyle,
                            animatedHeightStyle,
                            getWidgetVisibility(visible),
                        ]}
                    >
                        {children}
                        <CloseButton
                            visible={visible}
                            onPress={onClose}
                        />
                    </Animated.View>
                </View>
            )}
        </>
    );
};
