import { useEffect, useState } from 'react';
import QRCode from 'qrcode';

interface Props {
  otpauthUrl: string;
  issuer?: string;
  account?: string;
}

export function TotpQrPanel({ otpauthUrl, issuer, account }: Props) {
  const [dataUrl, setDataUrl] = useState('');
  const [err, setErr] = useState('');

  useEffect(() => {
    if (!otpauthUrl) {
      setDataUrl('');
      return;
    }
    let cancelled = false;
    QRCode.toDataURL(otpauthUrl, { width: 220, margin: 2, errorCorrectionLevel: 'M' })
      .then((url) => {
        if (!cancelled) setDataUrl(url);
      })
      .catch(() => {
        if (!cancelled) setErr('無法產生 QR Code');
      });
    return () => {
      cancelled = true;
    };
  }, [otpauthUrl]);

  if (!otpauthUrl) return null;

  return (
    <div className="totp-qr-panel">
      {dataUrl ? (
        <img src={dataUrl} alt="TOTP QR Code" width={220} height={220} />
      ) : err ? (
        <p className="form-error">{err}</p>
      ) : (
        <p className="hint">產生 QR Code 中…</p>
      )}
      <div className="totp-qr-meta">
        {issuer && (
          <p>
            <span className="muted">Issuer</span> {issuer}
          </p>
        )}
        {account && (
          <p>
            <span className="muted">帳號</span> {account}
          </p>
        )}
        <p className="hint">
          用 Google Authenticator、1Password 等 App 掃描 QR，或手動輸入密鑰（進階設定）。
        </p>
        <details className="totp-manual">
          <summary>無法掃描？顯示 otpauth 連結</summary>
          <code className="otpauth-url">{otpauthUrl}</code>
        </details>
      </div>
    </div>
  );
}
