import { useState } from 'react';
import { useTranslation } from 'react-i18next';
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 { t } = useTranslation('userfolder');
  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-surface 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' ? t('sshHostKey.recordTitle') : t('sshHostKey.replaceTitle')}
          </h3>
          <p className="text-2xs text-slate-500 mt-0.5">
            {test.verdict === 'first_observe'
              ? t('sshHostKey.recordDesc')
              : t('sshHostKey.replaceDesc')}
          </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">
                {t('sshHostKey.reason')}
              </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={t('sshHostKey.reasonPlaceholder')}
              />
            </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-canvas rounded-md hover:bg-surface disabled:opacity-50"
          >
            {t('sshHostKey.cancel')}
          </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 ? t('sshHostKey.saving') : test.verdict === 'first_observe' ? t('sshHostKey.record') : t('sshHostKey.replace')}
          </button>
        </div>
      </div>
    </div>
  );
}
