import { h, Fragment } from 'preact';
import { useState, useEffect } from 'preact/hooks';
import { logicDialogs, type DialogRequest } from './lib/logic';

// Renders the user-interaction dialogs requested by action.dialog.* logic nodes.
// The engine pushes requests to the `logicDialogs` store and awaits the user's
// response; this component shows each as a modal and calls req.resolve.
export default function LogicDialogs() {
  const [reqs, setReqs] = useState<DialogRequest[]>([]);
  useEffect(() => logicDialogs.subscribe(setReqs), []);
  if (reqs.length === 0) return null;
  return <Fragment>{reqs.map(r => <DialogModal key={r.id} req={r} />)}</Fragment>;
}

function DialogModal({ req }: { req: DialogRequest; key?: string }) {
  const isSetpoint = req.kind === 'setpoint';
  const inputIdx = req.fields
    .map((f, i) => (f.type === 'input' ? i : -1))
    .filter(i => i >= 0);
  // Per-input editable values, keyed by field index, seeded from the prefill.
  const [vals, setVals] = useState<Record<number, string>>(
    () => Object.fromEntries(inputIdx.map(i => [i, req.fields[i].value]))
  );

  function ok() {
    req.resolve(inputIdx.map(i => vals[i] ?? ''));
  }
  function cancel() { req.resolve(null); }

  function onKey(e: KeyboardEvent) {
    if (e.key === 'Enter' && !(e.target instanceof HTMLTextAreaElement)) { e.preventDefault(); ok(); }
    if (e.key === 'Escape') { e.preventDefault(); cancel(); }
  }

  return (
    <div class="logic-dialog-backdrop" onKeyDown={onKey}>
      <div class={`logic-dialog logic-dialog-${req.kind}`} role="dialog">
        <div class="logic-dialog-header">{req.title || (req.kind === 'error' ? 'Error' : isSetpoint ? 'Set value' : 'Info')}</div>
        {req.message && <div class="logic-dialog-message">{req.message}</div>}
        {req.fields.map((f, i) => (
          <div class="logic-dialog-field" key={i}>
            {f.label && <label class="logic-dialog-label">{f.label}</label>}
            {f.type === 'input' ? (
              <input class="prop-input logic-dialog-input" type="number"
                autoFocus={i === inputIdx[0]}
                value={vals[i] ?? ''}
                onInput={(e) => setVals(v => ({ ...v, [i]: (e.target as HTMLInputElement).value }))}
                onKeyDown={onKey} />
            ) : (
              <span class="logic-dialog-value">{f.value}</span>
            )}
          </div>
        ))}
        <div class="logic-dialog-actions">
          {isSetpoint && <button class="panel-btn" onClick={cancel}>Cancel</button>}
          <button class="panel-btn panel-btn-primary" onClick={ok}>OK</button>
        </div>
      </div>
    </div>
  );
}
