import { h } from '../core/dom';
import { store } from '../core/store';
import { modal } from './modal';
import { field, textInput, checkbox } from './controls';
import { icon } from './icons';
import { toast } from './toast';

const MAX_TERMS = 10;

/**
 * Manage the autofill term list (up to 10) and the master on/off toggle.
 * Terms may contain spaces (names like "Barry Allen" are the common case).
 * Today's date is offered automatically and isn't stored here.
 */
export function openAutofillSettings() {
  const m = modal({
    title: 'Autofill',
    subtitle: 'Suggestions appear as you type in text boxes and form fields. Saved on this device only.',
    icon: icon('field', 20),
    width: 480,
  });

  let enabled = store.autofillEnabled;
  const terms: string[] = store.autofillTerms.length ? [...store.autofillTerms] : [''];

  const rows = h('div.autofill-rows');
  const addBtn = h('button.btn btn-soft btn-sm', { onclick: () => addRow() }, icon('plus', 15), 'Add term') as HTMLButtonElement;

  function renderRows() {
    rows.replaceChildren(
      ...terms.map((t, i) => {
        const input = textInput({ value: t, placeholder: 'e.g. Barry Allen', oninput: (v) => { terms[i] = v; } });
        return h('div.autofill-row',
          input,
          h('button.icon-btn autofill-row-del', { title: 'Remove', onclick: () => { terms.splice(i, 1); if (!terms.length) terms.push(''); renderRows(); } }, icon('x', 15)),
        );
      }),
    );
    addBtn.disabled = terms.length >= MAX_TERMS;
  }
  function addRow() {
    if (terms.length >= MAX_TERMS) return;
    terms.push('');
    renderRows();
    (rows.lastElementChild?.querySelector('input') as HTMLInputElement | null)?.focus();
  }
  renderRows();

  m.body.append(
    h('div.autofill-enable',
      checkbox('Enable autofill suggestions', enabled, (v) => { enabled = v; }),
    ),
    field('Your terms', rows, `Up to ${MAX_TERMS}. Spaces are fine — today’s date is offered automatically, no need to add it.`),
    addBtn,
  );

  m.footer.append(
    h('button.btn btn-soft', { onclick: () => m.close() }, 'Cancel'),
    h('button.btn btn-primary', {
      onclick: () => {
        store.setAutofillEnabled(enabled);
        store.setAutofillTerms(terms);
        m.close();
        toast('Autofill settings saved.', { type: 'success' });
      },
    }, 'Save'),
  );
}
