import { PDFDocument } from '@cantoo/pdf-lib';
import { registerFeature } from '../registry';
import { featureModal, pdfSource, footerButtons, deliver, type LoadedFile } from '../common';
import { bufferOf, baseName } from '../../core/util';
import { toast } from '../../ui/toast';
import { h } from '../../core/dom';

registerFeature({
  id: 'flatten',
  title: 'Flatten PDF',
  desc: 'Bake form fields and their values into static content.',
  icon: 'flatten',
  category: 'optimize',
  run(ctx) {
    let files: LoadedFile[] = [];
    const m = featureModal('Flatten PDF', 'Bake form values into the page — nothing is uploaded.', 'flatten', 520);
    m.body.append(
      pdfSource(ctx, { multiple: false, onChange: (f) => { files = f; primary.disabled = files.length < 1; } }),
      h('p.hint', 'Flattening merges each form field and its current value into the page as static content. Fields become non-editable afterwards.'),
    );
    const { primary } = footerButtons(m, 'Flatten & download', async () => {
      const file = files[0];
      if (!file) return;
      m.setBusy(true, 'Flattening…');
      try {
        const doc = await PDFDocument.load(bufferOf(file.bytes), { ignoreEncryption: true });
        const form = doc.getForm();
        const fieldCount = form.getFields().length;
        try {
          form.flatten();
        } catch (e) {
          console.error(e);
        }
        const bytes = await doc.save({ useObjectStreams: true });
        m.close();
        deliver(bytes, baseName(file.name) + '-flattened.pdf');
        if (fieldCount === 0) {
          toast('No form fields found — saved a clean copy.', { type: 'info' });
        } else {
          toast(`Flattened ${fieldCount} field${fieldCount === 1 ? '' : 's'}.`, { type: 'success' });
        }
      } catch (e) {
        m.setBusy(false);
        toast('Flatten failed — the file may be damaged.', { type: 'error' });
        console.error(e);
      }
    }, 'flatten');
    primary.disabled = true;
  },
});
