var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { html, customElement, property, css, repeat, state, query } from '../../../../../external/lit/index.js';
import { UmbTextStyles } from '../../../../core/style/index.js';
import { UmbLitElement } from '../../../../core/lit-element/index.js';
import { generateAlias } from '../../../../core/utils/index.js';
import { UmbSorterController } from '../../../../core/sorter/index.js';
import { UmbChangeEvent } from '../../../../core/event/index.js';
let UmbPropertyEditorUIImageCropsElement = class UmbPropertyEditorUIImageCropsElement extends UmbLitElement {
    constructor() {
        super(...arguments);
        this._value = [];
        this._isCreating = false;
        this.editCropAlias = '';
        this.#oldInputValue = '';
        this.#sorter = new UmbSorterController(this, {
            getUniqueOfElement: (element) => element.dataset['alias'],
            getUniqueOfModel: (modelEntry) => modelEntry.alias,
            identifier: 'Umb.SorterIdentifier.ImageCrops',
            itemSelector: '.crop',
            containerSelector: '.crops',
            onChange: ({ model }) => {
                const oldValue = this._value;
                this._value = model;
                this.requestUpdate('_value', oldValue);
                this.dispatchEvent(new UmbChangeEvent());
            },
        });
    }
    set value(value) {
        this._value = value ?? [];
        this.#sorter.setModel(this.value);
    }
    get value() {
        return this._value;
    }
    #oldInputValue;
    #sorter;
    #onRemove(alias) {
        this.value = [...this.value.filter((item) => item.alias !== alias)];
        this.dispatchEvent(new UmbChangeEvent());
    }
    #onEdit(crop) {
        this.editCropAlias = crop.alias;
        this._isCreating = false;
    }
    #onEditCancel() {
        this.editCropAlias = '';
        this._isCreating = false;
    }
    #onSubmit(event) {
        event.preventDefault();
        const form = event.target;
        if (!form || !form.checkValidity())
            return;
        const formData = new FormData(form);
        const label = formData.get('label');
        const alias = formData.get('alias');
        const width = formData.get('width');
        const height = formData.get('height');
        if (!label || !alias || !width || !height)
            return;
        const newCrop = {
            label,
            alias,
            width: parseInt(width),
            height: parseInt(height),
        };
        if (this.editCropAlias) {
            const index = this.value.findIndex((item) => item.alias === this.editCropAlias);
            if (index === -1)
                return;
            const temp = [...this.value];
            temp[index] = newCrop;
            this.value = [...temp];
            this.editCropAlias = '';
        }
        else {
            this.value = [...this.value, newCrop];
        }
        this.dispatchEvent(new UmbChangeEvent());
        form.reset();
        this._labelInput?.focus();
        this._isCreating = false;
    }
    #renderForm(initial) {
        return html `
			<uui-form>
				<form @submit=${this.#onSubmit}>
					<div class="input">
						<uui-label for="label">Label</uui-label>
						<uui-input
							@input=${this.#onLabelInput}
							label="Label"
							id="label"
							name="label"
							type="text"
							required
							.value=${initial?.label ?? ''}></uui-input>
					</div>
					<div class="input">
						<uui-label for="alias">Alias</uui-label>
						<uui-input
							label="Alias"
							id="alias"
							name="alias"
							type="text"
							autocomplete="false"
							required
							.value=${initial?.alias ?? ''}></uui-input>
					</div>
					<div class="input">
						<uui-label for="width">Width</uui-label>
						<uui-input
							label="Width"
							id="width"
							name="width"
							type="number"
							autocomplete="false"
							required
							.value=${initial?.width ?? ''}
							min="0">
							<span class="append" slot="append">px</span>
						</uui-input>
					</div>
					<div class="input">
						<uui-label for="height">Height</uui-label>
						<uui-input
							label="Height"
							id="height"
							name="height"
							type="number"
							autocomplete="false"
							required
							.value=${initial?.height ?? ''}
							min="0">
							<span class="append" slot="append">px</span>
						</uui-input>
					</div>
					<div class="action-wrapper">
						${this.editCropAlias
            ? html `<uui-button @click=${this.#onEditCancel}>Cancel</uui-button>
									<uui-button look="secondary" type="submit" label=${this.localize.term('general_edit')}></uui-button>`
            : html `<uui-button
									look="secondary"
									type="submit"
									label=${this.localize.term('general_create')}></uui-button>`}
					</div>
				</form>
			</uui-form>
		`;
    }
    #onLabelInput() {
        const value = this._labelInput.value ?? '';
        const aliasValue = generateAlias(value);
        const alias = this.shadowRoot?.querySelector('#alias');
        if (!alias)
            return;
        const oldAliasValue = generateAlias(this.#oldInputValue);
        if (alias.value === oldAliasValue || !alias.value) {
            alias.value = aliasValue;
        }
        this.#oldInputValue = value;
    }
    render() {
        return html `
			<uui-ref-list class="crops">
				${repeat(this.value, (item) => item.alias, (item) => html `
						${this.editCropAlias === item.alias
            ? html `<div class="crop-form">${this.#renderForm(item)}</div>`
            : html `
									<uui-ref-node
										class="crop"
										data-alias="${item.alias}"
										detail="${item.width} x ${item.height}px"
										name="${item.label} (${item.alias})">
										<uui-icon slot="icon" name="icon-crop"></uui-icon>
										<uui-action-bar slot="actions">
											<uui-button
												label=${this.localize.term('general_edit')}
												data-mark="action:crop-edit"
												@click=${() => this.#onEdit(item)}></uui-button>
											<uui-button
												label=${this.localize.term('general_remove')}
												data-mark="action:crop-remove"
												@click=${() => this.#onRemove(item.alias)}></uui-button>
										</uui-action-bar>
									</uui-ref-node>
								`}
					`)}
			</uui-ref-list>
			${!this._isCreating && !this.editCropAlias
            ? html `<uui-button
						id="create"
						data-mark="action:crop-create"
						look="placeholder"
						@click=${() => (this._isCreating = true)}
						label=${this.localize.term('general_create')}></uui-button>`
            : ''}
			${this._isCreating ? this.#renderForm() : ''}
		`;
    }
    static { this.styles = [
        UmbTextStyles,
        css `
			:host {
				display: block;
			}
			.crops {
				display: flex;
				flex-direction: column;
				gap: var(--uui-size-space-2);
				margin-top: var(--uui-size-space-4);
			}
			.crop {
				display: flex;
				align-items: center;
			}
			form {
				display: flex;
				gap: var(--uui-size-space-2);
				flex-wrap: wrap;
			}
			.input {
				display: flex;
				flex-direction: column;
				flex: 1 1 200px;
			}
			uui-input[type='number'] {
				text-align: right;
			}
			.append {
				padding-inline: var(--uui-size-space-4);
				background: var(--uui-color-disabled);
				border-left: 1px solid var(--uui-color-border);
				color: var(--uui-color-disabled-contrast);
				font-size: var(--uui-type-small-size);
				display: flex;
				align-items: center;
				height: 100%;
			}
			.action-wrapper {
				display: flex;
				align-items: flex-end;
			}
			#create {
				width: 100%;
			}
		`,
    ]; }
};
__decorate([
    query('#label')
], UmbPropertyEditorUIImageCropsElement.prototype, "_labelInput", void 0);
__decorate([
    state()
], UmbPropertyEditorUIImageCropsElement.prototype, "_value", void 0);
__decorate([
    state()
], UmbPropertyEditorUIImageCropsElement.prototype, "_isCreating", void 0);
__decorate([
    property({ type: Array })
], UmbPropertyEditorUIImageCropsElement.prototype, "value", null);
__decorate([
    state()
], UmbPropertyEditorUIImageCropsElement.prototype, "editCropAlias", void 0);
UmbPropertyEditorUIImageCropsElement = __decorate([
    customElement('umb-property-editor-ui-image-crops')
], UmbPropertyEditorUIImageCropsElement);
export { UmbPropertyEditorUIImageCropsElement };
export default UmbPropertyEditorUIImageCropsElement;
