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

registerFeature({
  id: 'decrypt',
  title: 'Remove password',
  desc: 'Unlock a password-protected PDF.',
  icon: 'unlock',
  category: 'security',
  run(ctx) {
    let file: LoadedFile | null = null;
    let password = '';

    const m = featureModal('Remove password', 'Unlock a protected PDF — nothing is uploaded.', 'unlock', 520);

    const pwInput = textInput({
      placeholder: 'Current password',
      oninput: (v) => { password = v; },
    });
    pwInput.type = 'password';

    m.body.append(
      pdfSource(ctx, { multiple: false, onChange: (f) => { file = f[0] ?? null; primary.disabled = !file; } }),
      field('Password', pwInput, 'The password currently needed to open this PDF.'),
      h('p.hint', 'The unlocked copy is created entirely in your browser.'),
    );

    const { primary } = footerButtons(m, 'Unlock & download', async () => {
      if (!file) return;
      const t = toast('Unlocking…', { type: 'progress' });
      t.progress(0.3);
      try {
        const res = await decryptPdf(file.bytes, password);
        t.progress(1);
        t.close();
        if (res.ok && res.output) {
          m.close();
          deliver(res.output, baseName(file.name) + '-unlocked.pdf');
        } else {
          toast('Wrong password, or the file could not be unlocked.', { type: 'error' });
        }
      } catch (e) {
        t.close();
        toast('Wrong password, or the file could not be unlocked.', { type: 'error' });
        console.error(e);
      }
    }, 'unlock');
    primary.disabled = true;
  },
});
