import { useState } from 'react';
import { buildPageUrlForWechatOpen, copyWechatOpenLink, isIosBrowser } from '../utils/wechat';

export function WechatOpenGuide({
  disabled,
  onCopied,
}: {
  disabled?: boolean;
  onCopied?: () => void;
}) {
  const [guideOpen, setGuideOpen] = useState(false);
  const [copied, setCopied] = useState(false);
  const ios = isIosBrowser();

  const handleOpen = async () => {
    const ok = await copyWechatOpenLink();
    setCopied(ok);
    if (ok) onCopied?.();
    setGuideOpen(true);
  };

  return (
    <>
      <button
        type="button"
        className="login-wechat-secondary"
        onClick={() => void handleOpen()}
        disabled={disabled}
      >
        在微信中打开
      </button>

      {guideOpen && (
        <div
          className="wechat-open-overlay"
          role="dialog"
          aria-modal="true"
          aria-label="在微信中打开"
          onClick={() => setGuideOpen(false)}
        >
          <div className="wechat-open-guide" onClick={(e) => e.stopPropagation()}>
            <button
              type="button"
              className="wechat-open-close"
              aria-label="关闭"
              onClick={() => setGuideOpen(false)}
            >
              ×
            </button>
            <h2>请在微信中打开</h2>
            {copied ? (
              <p className="wechat-open-success">链接已复制</p>
            ) : (
              <p className="wechat-open-warning">未能自动复制，请手动复制下方链接</p>
            )}
            {ios ? (
              <ol className="wechat-open-steps">
                <li>点击浏览器右上角 <strong>···</strong></li>
                <li>选择 <strong>在微信中打开</strong></li>
                <li>打开后即可使用微信一键登录</li>
              </ol>
            ) : (
              <ol className="wechat-open-steps">
                <li>打开微信，将链接发给「文件传输助手」或任意聊天</li>
                <li>在微信里点击该链接</li>
                <li>打开后即可使用微信一键登录</li>
              </ol>
            )}
            <input
              className="wechat-open-url"
              readOnly
              value={buildPageUrlForWechatOpen()}
              onFocus={(e) => e.currentTarget.select()}
            />
            <button
              type="button"
              className="login-btn"
              onClick={() => void copyWechatOpenLink().then((ok) => setCopied(ok))}
            >
              再次复制链接
            </button>
          </div>
        </div>
      )}
    </>
  );
}
