/// SecureNote: a single multiline body field. Concealed by default in the
/// detail view; the form is just a big <textarea>.

import { getState, setState, sendMessage, navigate, escapeHtml, popOutToTab, isInTab } from '../../../shared/state';
import { renderFormHeader } from '../form-header';
import { REQUIRED_PILL_HTML } from '../../../shared/glyphs';
import type { Item, ItemId, ManifestEntry, Section, AttachmentRef } from '../../../shared/types';
import {
  renderConcealedRow, renderSignatureBlock, wireFieldHandlers, renderSections,
  renderSectionsEditor, wireSectionsEditor,
} from '../fields';
import {
  renderAttachmentsDisclosure,
  wireAttachmentsDisclosure,
  teardownAttachmentsDisclosure,
} from '../attachments-disclosure';

let activeKeyHandler: ((e: KeyboardEvent) => void) | null = null;
let activeFormEscHandler: ((e: KeyboardEvent) => void) | null = null;
let sectionsExpanded = false;

export function teardown(): void {
  teardownAttachmentsDisclosure();
  if (activeKeyHandler) {
    document.removeEventListener('keydown', activeKeyHandler);
    activeKeyHandler = null;
  }
  if (activeFormEscHandler) {
    document.removeEventListener('keydown', activeFormEscHandler);
    activeFormEscHandler = null;
  }
  sectionsExpanded = false;
}

export async function renderDetail(app: HTMLElement, item: Item): Promise<void> {
  if (item.core.type !== 'secure_note') return;
  const body = item.core.body ?? '';

  const sigInner = `
    <div style="font-size:14px;font-weight:600;color:#c9d1d9;">${escapeHtml(item.title)}</div>
  `;

  app.innerHTML = `
    <div class="pad">
      <div style="margin-bottom:12px;">
        ${renderSignatureBlock({ accent: 'green', children: sigInner })}
      </div>
      ${renderConcealedRow({ id: 'note-body', label: 'body', value: body, multiline: true })}
      ${renderSections(item, 'secure-note')}
      ${renderAttachmentsDisclosure({ itemId: item.id, attachments: item.attachments, mode: 'view' })}
      <div class="form-actions" style="margin-top:14px;">
        <button class="btn" id="back-btn">back</button>
        <button class="btn" id="edit-btn">edit</button>
        <button class="btn danger" id="trash-btn">trash</button>
      </div>
    </div>
  `;

  wireFieldHandlers(app);
  wireAttachmentsDisclosure(app, { itemId: item.id, attachments: item.attachments, mode: 'view' });

  document.getElementById('back-btn')?.addEventListener('click', () => { teardown(); navigate('list'); });
  document.getElementById('edit-btn')?.addEventListener('click', () => { teardown(); navigate('edit'); });
  document.getElementById('trash-btn')?.addEventListener('click', async () => {
    if (!confirm(`Move "${item.title}" to trash?`)) return;
    teardown();
    const resp = await sendMessage({ type: 'delete_item', id: item.id });
    if (!resp.ok) { setState({ error: resp.error }); return; }
    const listResp = await sendMessage({ type: 'list_items' });
    if (listResp.ok) {
      const data = listResp.data as { items: Array<[ItemId, ManifestEntry]> };
      navigate('list', { entries: data.items, selectedId: null, selectedItem: null });
    } else navigate('list');
  });

  const handler = async (e: KeyboardEvent) => {
    const t = e.target;
    if (t instanceof HTMLElement) {
      const tag = t.tagName;
      if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || t.isContentEditable) return;
    }
    switch (e.key) {
      case 'Escape': teardown(); navigate('list'); break;
      case 'e':      teardown(); navigate('edit'); break;
      case 'd':
        e.preventDefault();
        if (confirm(`Move "${item.title}" to trash?`)) {
          teardown();
          const resp = await sendMessage({ type: 'delete_item', id: item.id });
          if (!resp.ok) { setState({ error: resp.error }); return; }
          const listResp = await sendMessage({ type: 'list_items' });
          if (listResp.ok) {
            const data = listResp.data as { items: Array<[ItemId, ManifestEntry]> };
            navigate('list', { entries: data.items, selectedId: null, selectedItem: null });
          } else navigate('list');
        }
        break;
    }
  };
  activeKeyHandler = handler;
  document.addEventListener('keydown', handler);
}

export function renderForm(app: HTMLElement, mode: 'add' | 'edit', existing: Item | null): void {
  const state = getState();
  const title = existing?.title ?? '';
  const body = (existing?.core.type === 'secure_note') ? existing.core.body ?? '' : '';

  const sectionsDraft: Section[] = existing
    ? JSON.parse(JSON.stringify(existing.sections)) as Section[]
    : [];
  let attachmentsDraft: AttachmentRef[] = existing?.attachments ?? [];

  app.innerHTML = `
    <div class="pad">
      ${renderFormHeader({ titleText: mode === 'add' ? 'new secure note' : 'edit secure note' })}
      ${state.error ? `<div class="error">${escapeHtml(state.error)}</div>` : ''}
      <div class="form-group"><label class="label" for="f-title">title ${REQUIRED_PILL_HTML}</label>
        <input id="f-title" type="text" value="${escapeHtml(title)}" placeholder="My recovery codes"></div>
      <div class="form-group"><label class="label" for="f-body">body</label>
        <textarea id="f-body" rows="10" placeholder="paste secrets here">${escapeHtml(body)}</textarea></div>
      ${renderSectionsEditor(sectionsDraft, sectionsExpanded)}
      ${isInTab() ? renderAttachmentsDisclosure({ itemId: existing?.id ?? '', attachments: attachmentsDraft, mode: 'edit' }) : ''}
      <div class="form-actions">
        <button class="btn" id="cancel-btn">cancel</button>
        <button class="btn btn-primary" id="save-btn">save</button>
      </div>
    </div>
  `;

  const rerender = (): void => {
    const disclosure = app.querySelector('.disclosure');
    if (!disclosure) return;
    sectionsExpanded = disclosure.getAttribute('data-expanded') === 'true';
    disclosure.outerHTML = renderSectionsEditor(sectionsDraft, sectionsExpanded);
    wireSectionsEditor(app, sectionsDraft, rerender);
  };
  wireSectionsEditor(app, sectionsDraft, rerender);

  if (isInTab()) {
    const wireDisclosure = (): void => {
      wireAttachmentsDisclosure(app, {
        itemId: existing?.id ?? '',
        attachments: attachmentsDraft,
        mode: 'edit',
        onChange: (next) => {
          attachmentsDraft = next;
          const disc = app.querySelector('.attachments-disclosure');
          if (disc) {
            disc.outerHTML = renderAttachmentsDisclosure({
              itemId: existing?.id ?? '',
              attachments: attachmentsDraft,
              mode: 'edit',
            });
            wireDisclosure();
          }
        },
      });
    };
    wireDisclosure();
  }

  document.getElementById('cancel-btn')?.addEventListener('click', () => {
    setState({ error: null });
    navigate(mode === 'edit' ? 'detail' : 'list');
  });
  document.getElementById('popout-btn')?.addEventListener('click', popOutToTab);
  document.getElementById('save-btn')?.addEventListener('click', async () => {
    await saveSecureNote(mode, existing, sectionsDraft, attachmentsDraft);
  });

  const escHandler = (e: KeyboardEvent) => {
    if (e.key === 'Escape') {
      setState({ error: null });
      navigate(mode === 'edit' ? 'detail' : 'list');
    }
  };
  activeFormEscHandler = escHandler;
  document.addEventListener('keydown', escHandler);

  (document.getElementById('f-title') as HTMLInputElement | null)?.focus();
}

async function saveSecureNote(mode: 'add' | 'edit', existing: Item | null, sectionsDraft: Section[], attachmentsDraft: AttachmentRef[]): Promise<void> {
  const state = getState();
  const title = (document.getElementById('f-title') as HTMLInputElement).value.trim();
  const body = (document.getElementById('f-body') as HTMLTextAreaElement).value;
  if (!title) { setState({ error: 'Title is required' }); return; }

  const now = Math.floor(Date.now() / 1000);
  const item: Item = {
    id: existing?.id ?? '',
    title, type: 'secure_note',
    tags: existing?.tags ?? [],
    favorite: existing?.favorite ?? false,
    group: existing?.group,
    notes: existing?.notes,
    created: existing?.created ?? now,
    modified: now,
    trashed_at: undefined,
    core: { type: 'secure_note', body },
    sections: sectionsDraft,
    attachments: attachmentsDraft,
    field_history: existing?.field_history ?? {},
  };

  setState({ loading: true, error: null });
  const resp = mode === 'add'
    ? await sendMessage({ type: 'add_item', item })
    : await sendMessage({ type: 'update_item', id: state.selectedId!, item });
  if (resp.ok) {
    const listResp = await sendMessage({ type: 'list_items' });
    if (listResp.ok) {
      const data = listResp.data as { items: Array<[ItemId, ManifestEntry]> };
      navigate('list', { entries: data.items, selectedId: null, selectedItem: null });
    } else navigate('list');
  } else {
    setState({ loading: false, error: resp.error });
  }
}
