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

registerFeature({
  id: 'permissions',
  title: 'Set permissions',
  desc: 'Restrict printing, copying or editing with an owner password.',
  icon: 'shield',
  category: 'security',
  run(ctx) {
    let file: LoadedFile | null = null;
    let ownerPassword = '';
    const perms = { printing: true, copy: true, modify: false, annotate: true };
    let keyLength: 128 | 256 = 256;

    const m = featureModal('Set permissions', 'Restrict what readers can do — nothing is uploaded.', 'shield', 560);

    const update = () => { primary.disabled = !file || ownerPassword.length === 0; };

    m.body.append(
      pdfSource(ctx, { multiple: false, onChange: (f) => { file = f[0] ?? null; update(); } }),
      field(
        'Owner password',
        textInput({ placeholder: 'Required to change these settings', oninput: (v) => { ownerPassword = v; update(); } }),
        'Compliant readers require this password to lift the restrictions below.',
      ),
      h('div.field',
        h('label', 'Allowed actions'),
        checkbox('Allow printing', perms.printing, (v) => { perms.printing = v; }),
        checkbox('Allow copying text', perms.copy, (v) => { perms.copy = v; }),
        checkbox('Allow editing', perms.modify, (v) => { perms.modify = v; }),
        checkbox('Allow annotations', perms.annotate, (v) => { perms.annotate = v; }),
      ),
      field(
        'Encryption strength',
        select({
          options: [
            { value: '256', label: '256-bit AES (recommended)' },
            { value: '128', label: '128-bit AES' },
          ],
          value: '256',
          onchange: (v) => { keyLength = v === '128' ? 128 : 256; },
        }),
      ),
      h('p.hint', 'The file still opens without a password — but these actions are restricted in readers that respect PDF permissions.'),
    );

    const { primary } = footerButtons(m, 'Apply & download', async () => {
      if (!file || ownerPassword.length === 0) return;
      const src = file;
      const t = toast('Applying permissions…', { type: 'progress' });
      try {
        t.progress(0.35);
        const res = await setPermissions(src.bytes, {
          ownerPassword,
          allowPrinting: perms.printing,
          allowCopy: perms.copy,
          allowModify: perms.modify,
          allowAnnotate: perms.annotate,
          keyLength,
        });
        t.progress(1);
        t.close();
        if (!res.ok || !res.output) {
          toast('Could not set permissions — the file may be encrypted or damaged.', { type: 'error' });
          console.error(res.log);
          return;
        }
        m.close();
        deliver(res.output, baseName(src.name) + '-restricted.pdf');
      } catch (e) {
        t.close();
        toast('Could not set permissions — something went wrong.', { type: 'error' });
        console.error(e);
      }
    }, 'shield');
    primary.disabled = true;
  },
});
