import React, { useEffect, useMemo } from 'react';
import { Share as RNShare, Platform } from 'react-native';

export interface ShareSheetProps {
  visible: boolean;
  postUrl?: string;
  postTitle?: string;
  onClose: () => void;
  onShareAction?: (actionKey: string) => void;
}

const ShareSheet: React.FC<ShareSheetProps> = ({
  visible,
  postUrl,
  postTitle,
  onClose,
  onShareAction,
}) => {

  const shareText = useMemo(() => {
    const title = postTitle || '胡萝卜BBS帖子';
    return `${title} ${postUrl || ''}`;
  }, [postTitle, postUrl]);

  useEffect(() => {
    if (!visible) return;

    const doShare = async () => {
      try {
        await RNShare.share(
          {
            message: shareText,
            url: Platform.OS === 'ios' ? postUrl : undefined,
            title: postTitle || '分享帖子',
          },
          {
            subject: postTitle,
            dialogTitle: '分享到',
          }
        );
        onShareAction?.('system_share');
      } catch {
        // User cancelled
      } finally {
        onClose();
      }
    };

    doShare();
  }, [visible, shareText, postUrl, postTitle, onShareAction, onClose]);

  return null;
};

export default ShareSheet;
