import { forwardRef, useEffect } from 'react';
import { Text, View } from 'react-native';
import type { RsSkinlessToastProps } from '../../types/props';

type ViewRef = View;

const RsToast = forwardRef<ViewRef, RsSkinlessToastProps>(
  ({ visible, message, duration = 3000, position = 'bottom', onDismiss, style }, ref) => {
    useEffect(() => {
      if (visible && duration > 0 && onDismiss) {
        const timer = setTimeout(onDismiss, duration);
        return () => clearTimeout(timer);
      }
      return undefined;
    }, [visible, duration, onDismiss]);

    if (!visible) return null;

    return (
      <View
        ref={ref}
        style={[
          {
            position: 'absolute',
            left: 0,
            right: 0,
            ...(position === 'top' ? { top: 0 } : { bottom: 0 }),
          },
          style,
        ]}
        accessibilityRole="alert"
      >
        <Text>{message}</Text>
      </View>
    );
  }
);

RsToast.displayName = 'RsToast';

export default RsToast;
