import { useState } from 'react';
import {
  SHARE_CHANNELS,
  canUseNativeShare,
  copyShareText,
  nativeShare,
  type ShareChannel,
  type SharePayload,
} from '../utils/shareChannels';

export function ShareSheet({
  payload,
  onClose,
}: {
  payload: SharePayload;
  onClose: () => void;
}) {
  const [message, setMessage] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  const handleChannel = async (channel: ShareChannel) => {
    setBusy(true);
    setMessage(null);
    try {
      const text = channel.buildText(payload);
      await copyShareText(text);
      setMessage(channel.hint);
    } catch {
      setMessage('复制失败，请手动复制链接');
    } finally {
      setBusy(false);
    }
  };

  const handleNativeShare = async () => {
    setBusy(true);
    setMessage(null);
    try {
      await nativeShare(payload);
      onClose();
    } catch (err) {
      if (err instanceof DOMException && err.name === 'AbortError') return;
      setMessage('系统分享不可用，请选择其他平台');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="share-sheet-backdrop" role="presentation" onClick={onClose}>
      <section
        className="share-sheet-panel"
        role="dialog"
        aria-modal="true"
        aria-labelledby="share-sheet-title"
        onClick={(event) => event.stopPropagation()}
      >
        <header className="share-sheet-header">
          <div>
            <p className="share-sheet-eyebrow">SHARE</p>
            <h2 id="share-sheet-title">分享到</h2>
            <p className="share-sheet-subtitle">{payload.title}</p>
          </div>
          <button type="button" className="share-sheet-close" onClick={onClose} aria-label="关闭">
            ×
          </button>
        </header>

        <div className="share-sheet-grid">
          {SHARE_CHANNELS.map((channel) => (
            <button
              key={channel.id}
              type="button"
              className={`share-sheet-option share-sheet-option-${channel.id}`}
              disabled={busy}
              onClick={() => void handleChannel(channel)}
            >
              <span className="share-sheet-option-icon" aria-hidden="true">
                {channel.label.slice(0, 1)}
              </span>
              <span className="share-sheet-option-label">{channel.label}</span>
            </button>
          ))}
          {canUseNativeShare() && (
            <button
              type="button"
              className="share-sheet-option share-sheet-option-system"
              disabled={busy}
              onClick={() => void handleNativeShare()}
            >
              <span className="share-sheet-option-icon" aria-hidden="true">
                ···
              </span>
              <span className="share-sheet-option-label">更多</span>
            </button>
          )}
        </div>

        <div className="share-sheet-link">
          <span className="muted">分享链接</span>
          <code>{payload.url}</code>
        </div>

        {message && <p className="share-sheet-message">{message}</p>}
      </section>
    </div>
  );
}
