import { useState } from 'react';
import { useTranslation, Trans } from 'react-i18next';

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 { t } = useTranslation('userfolder');
  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-surface 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">
            {t('sshPublicKey.title')} {label && <span className="font-normal text-slate-500">— {label}</span>}
          </h3>
          {freshlyGenerated && (
            <p className="text-2xs text-emerald-700 dark:text-emerald-300 mt-1">
              <Trans t={t} i18nKey="sshPublicKey.freshlyGenerated" components={{ code: <code className="font-mono" /> }} />
            </p>
          )}
          {!freshlyGenerated && (
            <p className="text-2xs text-slate-600 mt-1">
              <Trans t={t} i18nKey="sshPublicKey.existing" components={{ code: <code className="font-mono" /> }} />
            </p>
          )}
        </div>

        <div className="px-4 py-3">
          <label className="block text-2xs font-semibold text-slate-500 uppercase tracking-wide mb-1">
            {t('sshPublicKey.lineLabel')}
          </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">
              <Trans t={t} i18nKey="sshPublicKey.troubleshoot" components={{ code: <code className="font-mono" /> }} />
            </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 ? t('sshPublicKey.copied') : t('sshPublicKey.copy')}
            </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-canvas rounded-md hover:bg-surface"
          >
            {t('sshPublicKey.close')}
          </button>
        </div>
      </div>
    </div>
  );
}
