import * as React from 'react';

// Custom Code CONTROL source. Paste into Code editor, not a Form Action step.
// Bind activePanelIndex to the VALUE of Temp variables > ActivePanelIndex.
// Place this control and the Toggle at the same level, preferably siblings in one Container.
// Keep it outside the Toggle panels and conditionally hidden containers.
// Classic layout: -1 opens all; 0 closes all; 1..N selects one; "2,3" selects several.
// Empty/invalid commands leave the current state unchanged.

interface ToggleControllerProps {
  cssId: string;
  command: string;
}

function unwrap(value: any): any {
  for (var depth = 0; depth < 5 && value && typeof value === 'object'; depth++) {
    if (Array.isArray(value)) return value;
    if (Object.prototype.hasOwnProperty.call(value, 'value')) value = value.value;
    else if (Object.prototype.hasOwnProperty.call(value, 'Value')) value = value.Value;
    else return null;
  }
  return value;
}

function panelCommand(value: any): string {
  value = unwrap(value);
  if (value === null || value === undefined || typeof value === 'boolean') return '';
  var parts: any[];
  if (Array.isArray(value)) parts = value;
  else if (typeof value === 'string') parts = value.split(/[,，]/);
  else if (typeof value === 'number') parts = [value];
  else return '';
  if (!parts.length) return '';
  var positions: number[] = [];
  for (var i = 0; i < parts.length; i++) {
    var part = unwrap(parts[i]);
    if (typeof part !== 'string' && typeof part !== 'number') return '';
    if (typeof part === 'string' && part.trim() === '') return '';
    var position = Number(part);
    if (!isFinite(position) || Math.floor(position) !== position || position < -1) return '';
    // -1 and 0 are complete commands; never mix them with panel positions.
    if (position <= 0) return parts.length === 1 ? String(position) : '';
    if (positions.indexOf(position) < 0) positions.push(position);
  }
  return positions.sort(function (a, b) { return a - b; }).join(',');
}

class ToggleController extends React.Component<ToggleControllerProps, {}> {
  private marker: HTMLSpanElement | null = null;
  private timer: any = null;
  private mounted = false;
  private attempts = 0;

  componentDidMount() {
    this.mounted = true;
    this.start();
  }

  componentDidUpdate(previous: ToggleControllerProps) {
    if (previous.command !== this.props.command || previous.cssId !== this.props.cssId) {
      this.start();
    }
  }

  componentWillUnmount() {
    this.mounted = false;
    this.cancel();
  }

  private cancel() {
    if (this.timer !== null) clearTimeout(this.timer);
    this.timer = null;
  }

  private start() {
    this.cancel();
    this.attempts = 0;
    if (!this.props.command) return;
    // Restrict the configurable ID so it can safely be used as a CSS selector.
    if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(this.props.cssId)) {
      console.warn('[Toggle controller] Use a CSS ID such as approval-toggle.');
      return;
    }
    var self = this;
    // Wait until React has committed the sibling controls.
    this.timer = setTimeout(function () { self.tick(); }, 0);
  }

  private findTarget(): HTMLElement | null {
    if (!this.marker) return null;
    // Use the closest shared container so Designer/Preview duplicate IDs do not
    // accidentally cause this instance to operate on the other form instance.
    var scope: HTMLElement | null = this.marker.parentElement;
    while (scope) {
      var matches = scope.querySelectorAll('#' + this.props.cssId);
      if (matches.length === 1) return matches[0] as HTMLElement;
      if (matches.length > 1) return null;
      scope = scope.parentElement;
    }
    return null;
  }

  private headers(root: HTMLElement): HTMLElement[] {
    var collapse: Element | null = null;
    var result: HTMLElement[] = [];
    for (var i = 0; i < root.children.length; i++) {
      if (root.children[i].classList.contains('ant-collapse')) {
        collapse = root.children[i];
        break;
      }
    }
    if (!collapse) return result;
    for (var itemIndex = 0; itemIndex < collapse.children.length; itemIndex++) {
      var item = collapse.children[itemIndex];
      if (!item.classList.contains('ant-collapse-item')) continue;
      for (var childIndex = 0; childIndex < item.children.length; childIndex++) {
        var child = item.children[childIndex];
        if (child.classList.contains('ant-collapse-header')) {
          result.push(child as HTMLElement);
          break;
        }
      }
    }
    return result;
  }

  private apply(): boolean {
    var root = this.findTarget();
    if (!root) return false;
    var headers = this.headers(root);
    var command = this.props.command;
    if (!headers.length || !command) return false;
    var positions = command.split(',').map(function (part) { return Number(part); });
    // Validate the whole selection before changing anything: "1,99" must not
    // partially apply if the 99th panel does not exist.
    if (command !== '-1' && command !== '0') {
      for (var p = 0; p < positions.length; p++) {
        if (positions[p] < 1 || positions[p] > headers.length) return false;
      }
    }
    // Use native handlers, not CSS overrides. Classic layout supports several
    // open panels, while positive single values still close unselected panels.
    for (var i = 0; i < headers.length; i++) {
      var shouldOpen = command === '-1' || (command !== '0' && positions.indexOf(i + 1) >= 0);
      var isOpen = headers[i].getAttribute('aria-expanded') === 'true';
      if (shouldOpen !== isOpen) {
        headers[i].click();
        return false;
      }
    }
    return true;
  }

  private tick() {
    this.timer = null;
    if (!this.mounted) return;
    this.attempts++;
    try {
      if (this.apply()) return;
    } catch (error) {
      console.warn('[Toggle controller] Could not switch panel.', error);
      return;
    }
    // Bounded retries for initial mounting/animation; never continually enforce
    // the variable after success, so manual panel selection remains usable.
    if (this.attempts >= 50) {
      console.warn('[Toggle controller] Panel command did not complete within 5 seconds. Check CSS ID, panel positions, Classic layout, same-level placement and visibility rules.');
      return;
    }
    var self = this;
    this.timer = setTimeout(function () { self.tick(); }, 100);
  }

  render() {
    return <span aria-hidden="true" style={{ display: 'none' }}
      ref={(node) => { this.marker = node; }} />;
  }
}

export class CodeInApplication implements CodeInComp {
  description() { return 'Control one, several or all native Toggle panels from a temporary-variable value.'; }
  requiredFields(params?: any) { return []; }
  inputParameters() {
    return [
      { id: 'toggleCssId', type: 'string', desc: 'Toggle CSS ID, without #: approval-toggle' },
      { id: 'activePanelIndex', type: 'variable', desc: 'Bind a temporary-variable value. Classic layout: -1 opens all; 0 closes all; 1..N selects one position; text "2,3" or "1,5" opens exactly those positions.' }
    ];
  }
  render(context: any, fieldsValues: any, readonly: boolean) {
    var params = context.params || {};
    var cssId = String(unwrap(params.toggleCssId) || 'approval-toggle').trim().replace(/^#/, '');
    return <ToggleController cssId={cssId} command={panelCommand(params.activePanelIndex)} />;
  }
}
