import { useState } from 'react';
import type { TestResponse } from '../../lib/ssh-types';

interface SshHostKeyDialogProps {
  /** Test response that produced this dialog (contains verdict + fingerprint + token). */
  test: TestResponse;
  /** True when an existing verified host key already differs from the observed one. */
  replaceMode: boolean;
  onClose: () => void;
  onVerify: (args: { fingerprint: string; token: string; reason?: string }) => Promise<void>;
}

/**
 * Shown after POST /test returns a pending verdict (first_observe or mismatch).
 * The user must confirm the observed fingerprint to persist it as the verified
 * host key. For mismatch the API requires a `reason` (≥ 8 chars) and routes
 * through /replace-host-key, which writes a ssh.connection.host_key.replace
 * audit row.
 */
export function SshHostKeyDialog({ test, replaceMode, onClose, onVerify }: SshHostKeyDialogProps) {
  const [reason, setReason] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  if (test.pendingToken === null) {
    return null;
  }

  const needsReason = replaceMode || test.verdict === 'mismatch';
  const reasonValid = !needsReason || reason.trim().length >= 8;

  async function handleConfirm() {
    if (test.pendingToken === null) return;
    setSubmitting(true);
    setError(null);
    try {
      await onVerify({
        fingerprint: test.fingerprint,
        token: test.pendingToken,
        reason: needsReason ? reason.trim() : undefined,
      });
      onClose();
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e));
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
      <div className="w-full max-w-lg bg-white rounded-md shadow-lg border border-hairline overflow-hidden">
        <div className="px-5 py-3 border-b border-hairline">
          <h3 className="text-sm font-semibold text-slate-900">
            {test.verdict === 'first_observe' ? 'ホストキーを記録' : 'ホストキーを置き換え'}
          </h3>
          <p className="text-2xs text-slate-500 mt-0.5">
            {test.verdict === 'first_observe'
              ? '初回観測したホストキーを確認してください。'
              : '⚠️ 記録済みのホストキーと異なります。MITM の可能性も含めて慎重に確認してください。'}
          </p>
        </div>
        <div className="px-5 py-3 space-y-3">
          <div>
            <div className="text-2xs font-semibold text-slate-500 uppercase tracking-wide mb-1">
              Fingerprint
            </div>
            <div className="font-mono text-xs text-slate-900 bg-surface px-2 py-1.5 rounded border border-hairline break-all select-all">
              {test.fingerprint}
            </div>
          </div>
          <div>
            <div className="text-2xs font-semibold text-slate-500 uppercase tracking-wide mb-1">
              Host Key Type
            </div>
            <div className="font-mono text-xs text-slate-700">{test.hostKeyType}</div>
          </div>
          {needsReason && (
            <div>
              <label className="block text-2xs font-semibold text-slate-500 uppercase tracking-wide mb-1">
                Reason (≥ 8 chars)
              </label>
              <input
                type="text"
                value={reason}
                onChange={e => setReason(e.target.value)}
                className="w-full text-xs px-2 py-1.5 border border-hairline rounded font-mono"
                placeholder="ホスト OS 再構築のため差し替え"
              />
            </div>
          )}
          {error && (
            <div className="text-xs text-red-600">{error}</div>
          )}
        </div>
        <div className="px-5 py-3 border-t border-hairline flex items-center justify-end gap-2 bg-surface/50">
          <button
            type="button"
            onClick={onClose}
            disabled={submitting}
            className="px-3 h-7 text-xs text-slate-700 border border-hairline bg-white rounded-md hover:bg-surface disabled:opacity-50"
          >
            キャンセル
          </button>
          <button
            type="button"
            onClick={handleConfirm}
            disabled={submitting || !reasonValid}
            className="px-3 h-7 text-xs font-semibold bg-accent text-accent-fg rounded-md hover:bg-accent-deep disabled:opacity-50"
          >
            {submitting ? '保存中…' : test.verdict === 'first_observe' ? '記録する' : '置き換える'}
          </button>
        </div>
      </div>
    </div>
  );
}
