/// Identity: full_name, address (multiline), phone, email, date_of_birth.
/// Detail view shows a "profile card" signature block + plain rows.

import { getState, setState, sendMessage, navigate, escapeHtml, popOutToTab } 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 {
  renderRow, 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;
}

function initials(name: string | undefined): string {
  if (!name) return '?';
  const parts = name.trim().split(/\s+/).slice(0, 2);
  return parts.map((p) => p.charAt(0).toUpperCase()).join('') || '?';
}

function formatDate(iso: string | undefined): string {
  if (!iso) return '';
  const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso);
  if (!m) return iso;
  const d = new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])));
  return d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric', timeZone: 'UTC' });
}

export async function renderDetail(app: HTMLElement, item: Item): Promise<void> {
  if (item.core.type !== 'identity') return;
  const c = item.core;
  const sigInner = `
    <div style="display:flex;align-items:center;gap:12px;">
      <div style="width:36px;height:36px;border-radius:50%;background:#d29922;color:#0d1117;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:13px;">${escapeHtml(initials(c.full_name))}</div>
      <div>
        <div style="font-size:14px;font-weight:600;color:#c9d1d9;">${escapeHtml(c.full_name ?? item.title)}</div>
        ${c.email ? `<div style="font-size:11px;color:#8b949e;">${escapeHtml(c.email)}</div>` : ''}
      </div>
    </div>
  `;

  app.innerHTML = `
    <div class="pad">
      <div style="margin-bottom:12px;">
        ${renderSignatureBlock({ accent: 'amber', children: sigInner })}
      </div>
      ${c.phone   ? renderRow({ label: 'phone',   value: c.phone,   copyable: true }) : ''}
      ${c.email   ? renderRow({ label: 'email',   value: c.email,   copyable: true }) : ''}
      ${c.address ? renderRow({ label: 'address', value: c.address, multiline: true })  : ''}
      ${c.date_of_birth ? renderRow({ label: 'born', value: formatDate(c.date_of_birth) }) : ''}
      ${renderSections(item, 'identity')}
      ${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 c = (existing?.core.type === 'identity') ? existing.core : null;

  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 identity' : 'edit identity' })}
      ${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="Aaron Lee · personal"></div>
      <div class="form-group"><label class="label" for="f-full-name">full name</label>
        <input id="f-full-name" type="text" value="${escapeHtml(c?.full_name ?? '')}" placeholder="Aaron Lee"></div>
      <div class="form-group"><label class="label" for="f-email">email</label>
        <input id="f-email" type="email" value="${escapeHtml(c?.email ?? '')}" placeholder="aaron@example.com"></div>
      <div class="form-group"><label class="label" for="f-phone">phone</label>
        <input id="f-phone" type="tel" value="${escapeHtml(c?.phone ?? '')}" placeholder="+1 555 0100"></div>
      <div class="form-group"><label class="label" for="f-address">address</label>
        <textarea id="f-address" rows="3" placeholder="street, city, postcode...">${escapeHtml(c?.address ?? '')}</textarea></div>
      <div class="form-group"><label class="label" for="f-dob">date of birth</label>
        <input id="f-dob" type="date" value="${escapeHtml(c?.date_of_birth ?? '')}"></div>
      ${renderSectionsEditor(sectionsDraft, sectionsExpanded)}
      ${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);

  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 saveIdentity(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 saveIdentity(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();
  if (!title) { setState({ error: 'Title is required' }); return; }

  const get = (id: string) => (document.getElementById(id) as HTMLInputElement | HTMLTextAreaElement).value.trim();

  const core = {
    type: 'identity' as const,
    full_name: get('f-full-name') || undefined,
    email:     get('f-email')     || undefined,
    phone:     get('f-phone')     || undefined,
    address:   get('f-address')   || undefined,
    date_of_birth: get('f-dob')   || undefined,
  };

  const now = Math.floor(Date.now() / 1000);
  const item: Item = {
    id: existing?.id ?? '',
    title, type: 'identity',
    tags: existing?.tags ?? [],
    favorite: existing?.favorite ?? false,
    group: existing?.group, notes: existing?.notes,
    created: existing?.created ?? now,
    modified: now, trashed_at: undefined,
    core,
    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 });
  }
}
