import { AXPTaskBoardService } from '@acorex/modules/task-management';
import * as i1 from '@acorex/platform/layout/widget-core';
import { AXPWidgetCoreModule } from '@acorex/platform/layout/widget-core';
import * as i2 from '@acorex/components/button';
import { AXButtonModule } from '@acorex/components/button';
import * as i3 from '@acorex/components/dropdown';
import { AXDropdownModule } from '@acorex/components/dropdown';
import { AXPWidgetsList } from '@acorex/modules/common';
import { CommonModule } from '@angular/common';
import * as i0 from '@angular/core';
import { input, inject, signal, computed, effect, CUSTOM_ELEMENTS_SCHEMA, ViewEncapsulation, ChangeDetectionStrategy, Component } from '@angular/core';

//#region ----   Imports   ----
//#endregion
//#region ----   Component   ----
class AXMWorkflowTaskPopoverComponent {
    onFormContextChanged(event) {
        const data = event?.data;
        if (data && typeof data === 'object') {
            const filtered = {};
            for (const [key, value] of Object.entries(data)) {
                if (key !== 'task' && key !== '_fields')
                    filtered[key] = value;
            }
            this.formValues.set(filtered);
        }
    }
    buildWidgetNode(f) {
        const type = (f.type ?? 'string').toLowerCase();
        const path = f.name;
        const defaultValue = f.value;
        switch (type) {
            case 'number':
                return {
                    type: AXPWidgetsList.Editors.NumberBox,
                    path,
                    name: path,
                    defaultValue,
                    options: {},
                };
            case 'date':
                return {
                    type: AXPWidgetsList.Editors.DateTimeBox,
                    path,
                    name: path,
                    defaultValue,
                    options: { showTime: true },
                };
            case 'boolean':
                return {
                    type: AXPWidgetsList.Editors.CheckBox,
                    path,
                    name: path,
                    defaultValue: Boolean(defaultValue),
                    options: {},
                };
            case 'text':
                return {
                    type: AXPWidgetsList.Editors.LargeTextBox,
                    path,
                    name: path,
                    defaultValue,
                    options: { rows: 3, placeholder: f.placeholder },
                };
            default:
                return {
                    type: AXPWidgetsList.Editors.TextBox,
                    path,
                    name: path,
                    defaultValue,
                    options: { placeholder: f.placeholder },
                };
        }
    }
    constructor() {
        //#region ----   Inputs   ----
        this.task = input.required(...(ngDevMode ? [{ debugName: "task" }] : []));
        //#endregion
        //#region ----   Services & Dependencies   ----
        this.taskBoardService = inject(AXPTaskBoardService);
        //#endregion
        //#region ----   Form context (for userInput on resume)   ----
        /** Current form values; passed as userInput when executing an action. */
        this.formValues = signal({}, ...(ngDevMode ? [{ debugName: "formValues" }] : []));
        //#endregion
        //#region ----   Content node from payload.context   ----
        /**
         * Builds a single AXPWidgetNode tree from payload.context._fields.
         * Renders form elements based on workflow requirements (no user-defined layout).
         */
        this.contentNode = computed(() => {
            const t = this.task();
            const taskData = t?.data;
            const payload = taskData?.payload;
            const context = payload?.context;
            const fields = context && typeof context === 'object' && Array.isArray(context._fields)
                ? context._fields
                : null;
            if (!fields || fields.length === 0)
                return null;
            const children = fields.map((f) => ({
                type: 'grid-item-layout',
                name: f.name,
                options: { colSpan: 12 },
                children: [
                    {
                        type: 'form-field',
                        options: {
                            label: f.label ?? f.name,
                            showLabel: true,
                        },
                        children: [
                            this.buildWidgetNode(f),
                        ],
                    },
                ],
            }));
            return {
                type: 'grid-layout',
                mode: 'edit',
                options: {
                    grid: {
                        default: {
                            columns: 'repeat(12, 1fr)',
                            rows: 'repeat(1, 1fr)',
                            gap: '12px',
                        },
                    },
                },
                children,
            };
        }, ...(ngDevMode ? [{ debugName: "contentNode" }] : []));
        /** Context for axp-widgets-container (initial values from payload.context). */
        this.popoverContext = computed(() => {
            const t = this.task();
            const payload = t?.data?.payload;
            const ctx = payload?.context;
            const base = ctx && typeof ctx === 'object' ? { ...ctx } : {};
            base['task'] = t;
            const fields = Array.isArray(base['_fields']) ? base['_fields'] : [];
            for (const f of fields) {
                if (f.name && !(f.name in base))
                    base[f.name] = f.value;
            }
            return base;
        }, ...(ngDevMode ? [{ debugName: "popoverContext" }] : []));
        //#endregion
        //#region ----   Actions   ----
        this.taskActions = signal([], ...(ngDevMode ? [{ debugName: "taskActions" }] : []));
        this.primaryActions = computed(() => this.taskActions().filter((a) => (a.priority ?? 'secondary') === 'primary'), ...(ngDevMode ? [{ debugName: "primaryActions" }] : []));
        this.secondaryActions = computed(() => this.taskActions().filter((a) => (a.priority ?? 'secondary') === 'secondary'), ...(ngDevMode ? [{ debugName: "secondaryActions" }] : []));
        effect(() => {
            const t = this.task();
            if (!t?.provider) {
                this.taskActions.set([]);
                return;
            }
            const provider = this.taskBoardService.getProvider(t.provider);
            if (!provider) {
                this.taskActions.set([]);
                return;
            }
            provider.getActions(t).then((actions) => this.taskActions.set(actions));
        });
    }
    getActionColor(action) {
        return action.color ?? null;
    }
    async executeAction(action) {
        const t = this.task();
        if (!t || !action.command || !t.provider)
            return;
        const userInput = this.formValues();
        const command = {
            ...action.command,
            options: {
                ...action.command.options,
                userInput: userInput && Object.keys(userInput).length > 0 ? userInput : action.command.options?.['userInput'] ?? {},
            },
        };
        try {
            await this.taskBoardService.executeCommand(command, t.provider);
        }
        catch (error) {
            console.error('[WorkflowTaskPopover] executeAction failed:', error);
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMWorkflowTaskPopoverComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "20.3.19", type: AXMWorkflowTaskPopoverComponent, isStandalone: true, selector: "axm-workflow-task-popover", inputs: { task: { classPropertyName: "task", publicName: "task", isSignal: true, isRequired: true, transformFunction: null } }, ngImport: i0, template: `
    <div class="workflow-task-popover">
      <axp-widgets-container
        [context]="popoverContext()"
        (onContextChanged)="onFormContextChanged($event)"
        class="workflow-task-popover__content"
      >
        @if (contentNode(); as node) {
          <ng-container axp-widget-renderer [node]="node" [mode]="'edit'"></ng-container>
        } @else {
          <div class="workflow-task-popover__fallback">
            @if (task().title) {
              <div class="workflow-task-popover__fallback-title">{{ task().title }}</div>
            }
            @if (task().description) {
              <p class="workflow-task-popover__fallback-description">{{ task().description }}</p>
            }
          </div>
        }
      </axp-widgets-container>

      <div class="workflow-task-popover__actions">
        @if (taskActions().length > 0) {
          <div class="workflow-task-popover__actions-group">
            @if (primaryActions().length > 0) {
              @for (action of primaryActions(); track action.name || action.title) {
                <ax-button
                  [look]="'solid'"
                  [color]="getActionColor(action)"
                  (onClick)="executeAction(action)"
                  [disabled]="action.disabled === true"
                  [text]="action.title"
                >
                  @if (action.icon) {
                    <ax-prefix>
                      <ax-icon>
                        <i [class]="action.icon"></i>
                      </ax-icon>
                    </ax-prefix>
                  }
                </ax-button>
              }
            }

            @if (secondaryActions().length > 0) {
              <ax-button [look]="'blank'">
                <ax-prefix>
                  <ax-icon icon="fa-light fa-ellipsis-vertical"></ax-icon>
                </ax-prefix>
                <ax-dropdown-panel>
                  <ax-button-item-list>
                    @for (action of secondaryActions(); track action.name || action.title) {
                      <ax-button-item
                        [text]="action.title"
                        [disabled]="action.disabled === true"
                        (onClick)="executeAction(action)"
                      >
                        @if (action.icon) {
                          <ax-prefix>
                            <ax-icon>
                              <i [class]="action.icon"></i>
                            </ax-icon>
                          </ax-prefix>
                        }
                      </ax-button-item>
                    }
                  </ax-button-item-list>
                </ax-dropdown-panel>
              </ax-button>
            }
          </div>
        }
      </div>
    </div>
  `, isInline: true, styles: [".workflow-task-popover{padding:12px;display:flex;flex-direction:column;gap:12px;min-width:280px;max-width:420px}.workflow-task-popover__content{min-height:0}.workflow-task-popover__fallback{display:flex;flex-direction:column;gap:8px}.workflow-task-popover__fallback-title{font-weight:600;font-size:14px;color:var(--ax-sys-color-text-primary)}.workflow-task-popover__fallback-description{margin:0;font-size:13px;line-height:1.4;color:var(--ax-sys-color-text-neutral-600)}.workflow-task-popover__actions{padding-top:8px;border-top:1px solid var(--ax-sys-color-border)}.workflow-task-popover__actions-group{display:flex;flex-wrap:wrap;gap:6px;align-items:center}\n"], dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "ngmodule", type: AXPWidgetCoreModule }, { kind: "component", type: i1.AXPWidgetContainerComponent, selector: "axp-widgets-container", inputs: ["context", "functions"], outputs: ["onContextChanged"] }, { kind: "directive", type: i1.AXPWidgetRendererDirective, selector: "[axp-widget-renderer]", inputs: ["parentNode", "index", "mode", "node"], outputs: ["onOptionsChanged", "onValueChanged", "onLoad"], exportAs: ["widgetRenderer"] }, { kind: "ngmodule", type: AXButtonModule }, { kind: "component", type: i2.AXButtonComponent, selector: "ax-button", inputs: ["disabled", "size", "tabIndex", "color", "look", "text", "toggleable", "selected", "iconOnly", "type", "loadingText"], outputs: ["onBlur", "onFocus", "onClick", "selectedChange", "toggleableChange", "lookChange", "colorChange", "disabledChange", "loadingTextChange"] }, { kind: "component", type: i2.AXButtonItemComponent, selector: "ax-button-item", inputs: ["color", "disabled", "text", "selected", "divided", "data", "name"], outputs: ["onClick", "onFocus", "onBlur", "disabledChange"] }, { kind: "component", type: i2.AXButtonItemListComponent, selector: "ax-button-item-list", inputs: ["items", "closeParentOnClick", "lockOnLoading"], outputs: ["onItemClick"] }, { kind: "ngmodule", type: AXDropdownModule }, { kind: "component", type: i3.AXDropdownPanelComponent, selector: "ax-dropdown-panel", inputs: ["isOpen", "fitParent", "dropdownWidth", "position", "placement", "_target", "adaptivityEnabled"], outputs: ["onOpened", "onClosed"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.19", ngImport: i0, type: AXMWorkflowTaskPopoverComponent, decorators: [{
            type: Component,
            args: [{ selector: 'axm-workflow-task-popover', template: `
    <div class="workflow-task-popover">
      <axp-widgets-container
        [context]="popoverContext()"
        (onContextChanged)="onFormContextChanged($event)"
        class="workflow-task-popover__content"
      >
        @if (contentNode(); as node) {
          <ng-container axp-widget-renderer [node]="node" [mode]="'edit'"></ng-container>
        } @else {
          <div class="workflow-task-popover__fallback">
            @if (task().title) {
              <div class="workflow-task-popover__fallback-title">{{ task().title }}</div>
            }
            @if (task().description) {
              <p class="workflow-task-popover__fallback-description">{{ task().description }}</p>
            }
          </div>
        }
      </axp-widgets-container>

      <div class="workflow-task-popover__actions">
        @if (taskActions().length > 0) {
          <div class="workflow-task-popover__actions-group">
            @if (primaryActions().length > 0) {
              @for (action of primaryActions(); track action.name || action.title) {
                <ax-button
                  [look]="'solid'"
                  [color]="getActionColor(action)"
                  (onClick)="executeAction(action)"
                  [disabled]="action.disabled === true"
                  [text]="action.title"
                >
                  @if (action.icon) {
                    <ax-prefix>
                      <ax-icon>
                        <i [class]="action.icon"></i>
                      </ax-icon>
                    </ax-prefix>
                  }
                </ax-button>
              }
            }

            @if (secondaryActions().length > 0) {
              <ax-button [look]="'blank'">
                <ax-prefix>
                  <ax-icon icon="fa-light fa-ellipsis-vertical"></ax-icon>
                </ax-prefix>
                <ax-dropdown-panel>
                  <ax-button-item-list>
                    @for (action of secondaryActions(); track action.name || action.title) {
                      <ax-button-item
                        [text]="action.title"
                        [disabled]="action.disabled === true"
                        (onClick)="executeAction(action)"
                      >
                        @if (action.icon) {
                          <ax-prefix>
                            <ax-icon>
                              <i [class]="action.icon"></i>
                            </ax-icon>
                          </ax-prefix>
                        }
                      </ax-button-item>
                    }
                  </ax-button-item-list>
                </ax-dropdown-panel>
              </ax-button>
            }
          </div>
        }
      </div>
    </div>
  `, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, schemas: [CUSTOM_ELEMENTS_SCHEMA], imports: [CommonModule, AXPWidgetCoreModule, AXButtonModule, AXDropdownModule], styles: [".workflow-task-popover{padding:12px;display:flex;flex-direction:column;gap:12px;min-width:280px;max-width:420px}.workflow-task-popover__content{min-height:0}.workflow-task-popover__fallback{display:flex;flex-direction:column;gap:8px}.workflow-task-popover__fallback-title{font-weight:600;font-size:14px;color:var(--ax-sys-color-text-primary)}.workflow-task-popover__fallback-description{margin:0;font-size:13px;line-height:1.4;color:var(--ax-sys-color-text-neutral-600)}.workflow-task-popover__actions{padding-top:8px;border-top:1px solid var(--ax-sys-color-border)}.workflow-task-popover__actions-group{display:flex;flex-wrap:wrap;gap:6px;align-items:center}\n"] }]
        }], ctorParameters: () => [], propDecorators: { task: [{ type: i0.Input, args: [{ isSignal: true, alias: "task", required: true }] }] } });

export { AXMWorkflowTaskPopoverComponent };
//# sourceMappingURL=acorex-modules-workflow-management-workflow-task-popover.component-DQqorIfQ.mjs.map
