import { useState, type ReactNode } from 'react';
import { IconButton } from './IconButton';
import { IconCopy } from './icons';

type TotpCardProps = {
  label: string;
  issuer: string | null;
  code: string;
  expiresInSeconds: number;
  period: number;
  toolbar?: ReactNode;
};

export function TotpCard({
  label,
  issuer,
  code,
  expiresInSeconds,
  period,
  toolbar,
}: TotpCardProps) {
  const pct = Math.max(0, Math.min(100, (expiresInSeconds / period) * 100));
  const [codeCopied, setCodeCopied] = useState(false);

  async function onCopyCode() {
    try {
      await navigator.clipboard.writeText(code);
      setCodeCopied(true);
      setTimeout(() => setCodeCopied(false), 1500);
    } catch {
      /* ignore */
    }
  }

  return (
    <div className="card totp-card">
      <div className="totp-card-head">
        <div className="totp-card-meta">
          <span className="totp-card-label" title={label}>
            {label}
          </span>
          {issuer ? <span className="totp-card-issuer">{issuer}</span> : null}
        </div>
        {toolbar ? <div className="icon-toolbar">{toolbar}</div> : null}
      </div>

      <div className="totp-code-row">
        <button type="button" className="totp-code-hit" onClick={() => void onCopyCode()} title="点击复制验证码">
          <span className="totp-code">{code}</span>
        </button>
        <IconButton label="复制验证码" copied={codeCopied} onClick={() => void onCopyCode()}>
          <IconCopy />
        </IconButton>
      </div>

      <div className="totp-card-foot">
        <div className="progress" aria-hidden>
          <i style={{ width: `${pct}%` }} />
        </div>
        <span className="totp-card-timer">{expiresInSeconds}s</span>
      </div>
    </div>
  );
}
