import { useState } from 'react';

interface Props {
  publicKey: string;
  /** Optional label shown in the title (e.g. the connection's display name). */
  label?: string;
  /** When true, surface a "newly generated" callout. Default false. */
  freshlyGenerated?: boolean;
  onClose: () => void;
}

/**
 * Modal that shows the OpenSSH-format public key (`ssh-ed25519 AAAA...`)
 * with a one-click copy button. Used both:
 *   - after creating a connection with `keypairSource=generate` (so the user
 *     can paste the key into the remote `authorized_keys`), and
 *   - on demand from any existing connection (so the user can re-verify
 *     that the registered authorized_keys entry matches our stored key).
 */
export function SshPublicKeyDialog({ publicKey, label, freshlyGenerated, onClose }: Props) {
  const [copied, setCopied] = useState(false);

  async function handleCopy() {
    try {
      await navigator.clipboard.writeText(publicKey);
      setCopied(true);
      window.setTimeout(() => setCopied(false), 2000);
    } catch {
      // Clipboard API can fail in non-secure contexts; ignore and let the
      // user select the textarea manually.
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
      <div className="w-full max-w-2xl bg-white rounded-md shadow-lg border border-hairline overflow-hidden">
        <div className="px-4 py-3 border-b border-hairline bg-surface/40">
          <h3 className="text-sm font-semibold text-slate-900">
            公開鍵 {label && <span className="font-normal text-slate-500">— {label}</span>}
          </h3>
          {freshlyGenerated && (
            <p className="text-2xs text-emerald-700 mt-1">
              新しい鍵を Orchestrator で生成しました。下の公開鍵を接続先の
              <code className="font-mono"> ~/.ssh/authorized_keys</code> に追加してください。
            </p>
          )}
          {!freshlyGenerated && (
            <p className="text-2xs text-slate-600 mt-1">
              この接続が保持している秘密鍵に対応する公開鍵です。接続先の
              <code className="font-mono"> ~/.ssh/authorized_keys</code> に同じ行が登録されていない場合、
              認証は失敗します。
            </p>
          )}
        </div>

        <div className="px-4 py-3">
          <label className="block text-2xs font-semibold text-slate-500 uppercase tracking-wide mb-1">
            authorized_keys に貼る 1 行
          </label>
          <textarea
            readOnly
            value={publicKey}
            onClick={(e) => (e.target as HTMLTextAreaElement).select()}
            className="w-full text-xs font-mono px-2 py-1.5 border border-hairline rounded h-24 resize-y bg-surface/40"
            spellCheck={false}
          />
          <div className="flex items-center justify-between mt-2">
            <p className="text-2xs text-slate-500">
              SSH 接続テストで「All configured authentication methods failed」が出る場合は、まずこの値が
              接続先の <code className="font-mono">authorized_keys</code> に登録されているかを確認してください。
            </p>
            <button
              type="button"
              onClick={handleCopy}
              className="px-3 h-7 text-xs font-semibold bg-accent text-accent-fg rounded-md hover:bg-accent-deep ml-2 flex-shrink-0"
            >
              {copied ? 'コピーしました' : 'コピー'}
            </button>
          </div>
        </div>

        <div className="px-4 py-3 border-t border-hairline flex items-center justify-end bg-surface/30">
          <button
            type="button"
            onClick={onClose}
            className="px-3 h-7 text-xs text-slate-700 border border-hairline bg-white rounded-md hover:bg-surface"
          >
            閉じる
          </button>
        </div>
      </div>
    </div>
  );
}
