import { registerFeature } from '../registry';
import { featureModal, pdfSource, footerButtons, deliver, type LoadedFile } from '../common';
import { field, textInput, select, checkbox } from '../../ui/controls';
import { encryptPdf } from '../../core/qpdf';
import { baseName } from '../../core/util';
import { toast } from '../../ui/toast';
import { h } from '../../core/dom';

registerFeature({
  id: 'encrypt',
  title: 'Password protect',
  desc: 'Encrypt a PDF with a password.',
  icon: 'lock',
  category: 'security',
  run(ctx) {
    let file: LoadedFile | null = null;
    let userPassword = '';
    let ownerPassword = '';
    let keyLength: 40 | 128 | 256 = 256;
    let allowPrinting = true;
    let allowCopy = true;
    let allowModify = false;
    let allowAnnotate = true;

    const m = featureModal('Password protect', 'Encrypt a PDF with a password — all in your browser.', 'lock', 560);

    const userInput = textInput({ placeholder: 'Required to open the file', oninput: (v) => { userPassword = v; refresh(); } });
    userInput.type = 'password';
    const ownerInput = textInput({ placeholder: 'Optional — controls permissions', oninput: (v) => { ownerPassword = v; } });
    ownerInput.type = 'password';

    m.body.append(
      pdfSource(ctx, { multiple: false, onChange: (f) => { file = f[0] ?? null; refresh(); } }),
      field('Open password', userInput, 'Anyone opening the PDF will need this password.'),
      field('Owner password', ownerInput, 'Optional. Lets you set permissions separately from the open password.'),
      field('Encryption strength', select({
        options: [
          { value: '256', label: 'AES-256 (strongest)' },
          { value: '128', label: 'AES-128' },
        ],
        value: '256',
        onchange: (v) => { keyLength = (v === '128' ? 128 : 256); },
      })),
      h('div.field',
        h('label', 'Permissions'),
        checkbox('Allow printing', allowPrinting, (v) => { allowPrinting = v; }),
        checkbox('Allow copying text', allowCopy, (v) => { allowCopy = v; }),
        checkbox('Allow editing', allowModify, (v) => { allowModify = v; }),
        checkbox('Allow annotations', allowAnnotate, (v) => { allowAnnotate = v; }),
      ),
    );

    const { primary } = footerButtons(m, 'Protect & download', async () => {
      if (!file || !userPassword.trim()) return;
      const src = file;
      const t = toast('Encrypting…', { type: 'progress' });
      t.progress(0.3);
      try {
        const res = await encryptPdf(src.bytes, {
          userPassword,
          ownerPassword: ownerPassword || undefined,
          keyLength,
          allowPrinting,
          allowCopy,
          allowModify,
          allowAnnotate,
        });
        if (!res.ok || !res.output) {
          t.close();
          toast(res.log?.trim() || 'Encryption failed — the file may be damaged.', { type: 'error' });
          console.error(res.log);
          return;
        }
        t.progress(1);
        t.close();
        m.close();
        deliver(res.output, baseName(src.name) + '-protected.pdf');
      } catch (e) {
        t.close();
        toast('Encryption failed — the file may be damaged.', { type: 'error' });
        console.error(e);
      }
    }, 'lock');

    const refresh = () => { primary.disabled = !file || !userPassword.trim(); };
    refresh();
  },
});
