import { __decorate, __metadata } from "tslib";
import { LitElement, html, css } from 'lit';
import { customElement, property, state } from 'lit/decorators.js';
import { getPowerPlantGroups } from '../../entities/power-plant-group/queries/query';
import { deletePowerPlantGroup, updatePowerPlantGroup, applyPowerPlantGroup } from '../../entities/power-plant-group/queries/mutation';
import { showToast } from '../../shared/utils/alert';
import { getPowerPlants } from '../../entities/power-plant/queries/query';
import { getPowerPlantListByPowerPlantGroupId } from '../../entities/power-plant-group/queries/query';
let PopupGroupManegement = class PopupGroupManegement extends LitElement {
    constructor() {
        super(...arguments);
        this.isOpen = false;
        this.newGroupName = '';
        this.powerPlantList = [];
        this.powerPlantGroupList = [];
        this.powerPlantFilter = '';
        this.selectedGroupId = '';
        this.selectedPowerPlantIds = [];
    }
    static { this.styles = css `
    .dimmed {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.5);
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 1000;
    }
    .popup {
      border:2px solid var(--md-sys-color-tertiary);
      background-color: #111;
      display: flex;
      flex-direction: column;
      gap:var(--padding-wide);
      border-radius: 8px;
      padding: var(--padding-wide);
      width: 350px;
      height: 80%;
      box-shadow: 4px 4px 5px rgba(0, 0, 0, 0.4);
      position: relative;
      color: var(--md-sys-color-on-secondary);
    }
    .header {
      font-size:1.2em;
      font-weight: bold;
    }
    .input-container {
      display: flex;
      gap:var(--padding-default);
    }
    input[type='text'] {
      flex: 1;
      border-radius: 5px;
      border: 1px solid #555;
      padding: var(--padding-narrow) var(--padding-default);
      background-color: #2c2c2c;
      color: white;
      font-size:1.1em;
    }
    input:focus {
      outline: none;
      box-shadow: none;
    }
    button.create {
      margin-left: 8px;
      background-color: #4caf50;
      border: none;
      color: white;
      border-radius: 4px;
      padding: 8px 16px;
      cursor: pointer;
    }
    .group-list {
      overflow-y: auto;
      display: flex;
      flex:1;
      flex-direction: column;
      gap:var(--padding-default);
    }
    .group-list label{
      color:var(--md-sys-color-surface-tint)
    }
    .group-item {
      display: flex;
      gap:var(--padding-narrow);
      align-items: center;
      justify-content: space-between;

      &[active]{
        background-color:rgba(255,255,255,.1);
      }

      &[active] span{
        border-left:3px solid var(--status-success-color);
        font-weight:700;
        text-indent:var(--padding-narrow);
      }
      span{
        flex:1;

        strong{
          color:var(--md-sys-color-surface-tint);
        }
      }
      input{
        flex: 1;
        font-size: 1em;
        border-radius: 5px;
        border: none;
        flex-basis: fit-content;
        padding: var(--padding-narrow);
      }

      button{
        padding: var(--padding-narrow) var(--padding-default);
      }  
    }
    button {
      border: none;
      border-radius: 5px;
      padding: var(--padding-default);
      font-size: 1em;
      color:var(--md-sys-color-on-secondary);
      cursor: pointer;
      background-color: var(--md-sys-color-tertiary);

      &.delete {
        background-color: var(--status-danger-color);
      }
      &.cancel {
        background-color: var(--md-sys-color-on-secondary-container);
        color:var(--md-sys-color-on-secondary);
      }
    }
    .close-btn {
      position: relative;
      float: right;
      top: 2px;
      cursor: pointer;
    }
    hr{
      width:99%;
      height: 1px;
      background-color: var(--md-sys-color-on-tertiary-container);
      border:0;
    }
    .power-plant-list{
      flex:1;
      display: flex;
      flex-direction: column;
      gap:var(--padding-narrow);
    }
    .power-plant-item label{
      color: var(--md-sys-color-on-secondary);
    }
    @media screen and (max-width: 768px) {
      .popup {
        width:280px
      }
    }
  `; }
    render() {
        return this.isOpen
            ? html `
          <div class="dimmed" @click="${this.close}">
            <div class="popup" @click="${e => e.stopPropagation()}">
              <div class="header">발전소 그룹 관리
                <md-icon class="close-btn"  @click="${this.close}">close</md-icon>
              </div>

              <div class="group-list">
                <label>발전소 그룹 (총 <strong>${this.powerPlantGroupList.length}</strong>개)</label>

                ${this.powerPlantGroupList.map(item => html `
                    <div
                      class="group-item"
                      ?active=${this.selectedGroupId === item.id}
                      @click="${() => this.onSelectGroup(item.id)}"
                    >
                      ${item.editing
                ? html `
                            <input
                              .value=${item.tempName}
                              @input=${(e) => this.onInputGroupNameChange(e, item.id)}
                              @keydown=${(e) => this.onKeyDownGroupNameChange(e, item.id)}
                            />
                            <button class="cancel" @click=${(e) => this.onClickCancelUpdateGroup(e, item.id)}>
                              취소
                            </button>
                            <button class="modify" @click=${(e) => this.onClickConfirmUpdateGroup(e, item.id)}>
                              확인
                            </button>
                          `
                : html `
                            <span>${item.name} <strong>${item.powerPlantCount}</strong></span>
                            <button class="modify" @click=${(e) => this.onClickModifyGroup(e, item.id)}>
                              수정
                            </button>
                          `}

                      <button class="delete" @click=${(e) => this.onClickDeleteGroup(e, item.id)}>삭제</button>
                    </div>
                  `)}
                <hr>
                <label>발전소 추가</label>
                <div class="input-container">
                  <input
                    type="text"
                    placeholder="발전소 명을 입력하세요"
                    .value=${this.powerPlantFilter}
                    @input=${this.onInputPowerPlantFilter}
                  />
                </div>

                <div class="power-plant-list">
                  ${this.powerPlantList.map(item => {
                const filter = this.powerPlantFilter.trim().toLowerCase();
                const name = item.name?.toLowerCase() || '';
                const isMatch = filter === '' || name.includes(filter);
                return html `
                      <div class="power-plant-item" style=${isMatch ? '' : 'display: none;'}>
                        <input
                          id=${'pp-checkbox-' + item.id}
                          type="checkbox"
                          .checked=${this.selectedPowerPlantIds.includes(item.id)}
                          @change=${(e) => this.onTogglePowerPlant(e, item.id)}
                        />
                        <label for=${'pp-checkbox-' + item.id}>${item.name}</label>
                      </div>
                    `;
            })}
                </div>

                <button @click=${() => this.onClickApplyGroup()}>적용</button>
              </div>
            </div>
          </div>
        `
            : '';
    }
    async onClickDeleteGroup(e, id) {
        e.stopPropagation();
        if (!confirm('삭제하시겠습니까?'))
            return;
        const { status } = await deletePowerPlantGroup(id);
        if (status) {
            this.powerPlantGroupList = this.powerPlantGroupList.filter(item => item.id !== id);
            showToast('발전소 그룹이 삭제되었습니다');
        }
    }
    // 수정 버튼 누르면 편집모드로 전환 및 임시 이름 넣어주기
    onClickModifyGroup(e, id) {
        e.stopPropagation();
        const group = this.powerPlantGroupList.find((item) => item.id === id);
        if (group) {
            group.editing = true;
            group.tempName = group.name;
            this.requestUpdate();
        }
    }
    // 임시 이름 input 변경 이벤트
    onInputGroupNameChange(e, id) {
        const input = e.target;
        const group = this.powerPlantGroupList.find((item) => item.id === id);
        if (group) {
            group.tempName = input.value;
            this.requestUpdate();
        }
    }
    // 편집모드일때 엔터 누르면 수정
    onKeyDownGroupNameChange(e, id) {
        if (e.key === 'Enter') {
            this.onClickConfirmUpdateGroup(e, id);
        }
    }
    // 수정 확인 버튼 누르면 수정 완료
    async onClickConfirmUpdateGroup(e, id) {
        e.stopPropagation();
        const group = this.powerPlantGroupList.find((item) => item.id === id);
        if (!group)
            return;
        try {
            const { status, data } = await updatePowerPlantGroup(id, group.tempName);
            if (status) {
                group.name = data.name;
                group.tempName = data.name;
                group.editing = false;
                this.requestUpdate();
                showToast('발전소 그룹이 수정되었습니다');
            }
        }
        catch (error) {
            console.error(error);
        }
    }
    // 발전소 그룹 적용
    async onClickApplyGroup() {
        if (!this.selectedGroupId)
            return;
        const { status } = await applyPowerPlantGroup(this.selectedGroupId, this.selectedPowerPlantIds);
        if (status) {
            await this.getPowerPlantGroupList();
            showToast('발전소 그룹이 적용되었습니다');
        }
    }
    // 그룹 선택 시 active 처리 및 해당 그룹의 발전소 목록 불러오기
    async onSelectGroup(groupId) {
        this.selectedGroupId = groupId;
        const { data: powerPlantListOfGroup } = await getPowerPlantListByPowerPlantGroupId(groupId);
        // 그룹에 속한 발전소 id를 selectedPowerPlantIds에 저장하여 체크 상태로 표시
        this.selectedPowerPlantIds = powerPlantListOfGroup?.map((item) => item.domain.id) || [];
        this.requestUpdate();
    }
    // 발전소 체크박스 토글 이벤트
    onTogglePowerPlant(e, powerPlantId) {
        const checkbox = e.target;
        if (checkbox.checked) {
            if (!this.selectedPowerPlantIds.includes(powerPlantId)) {
                this.selectedPowerPlantIds = [...this.selectedPowerPlantIds, powerPlantId];
            }
        }
        else {
            this.selectedPowerPlantIds = this.selectedPowerPlantIds.filter((id) => id !== powerPlantId);
        }
        this.requestUpdate();
    }
    // 취소 버튼 누르면 편집 모드를 취소하고, 임시 이름을 원래 값으로 복원
    onClickCancelUpdateGroup(e, id) {
        e.stopPropagation();
        const group = this.powerPlantGroupList.find((item) => item.id === id);
        if (group) {
            group.editing = false;
            group.tempName = group.name;
            this.requestUpdate();
        }
    }
    // 필터 입력창 이벤트 핸들러: 입력값을 상태로 저장
    onInputPowerPlantFilter(e) {
        this.powerPlantFilter = e.target.value;
    }
    async open() {
        // 그룹 리스트 가져오기
        await this.getPowerPlantGroupList();
        // 발전소 리스트 가져오기
        await this.getPowerPlantList();
        // 데이터 초기화
        this.selectedPowerPlantIds = [];
        this.selectedGroupId = '';
        this.powerPlantFilter = '';
        this.isOpen = true;
    }
    async getPowerPlantGroupList() {
        const { data: powerPlantGroupList } = await getPowerPlantGroups();
        this.powerPlantGroupList = powerPlantGroupList.items.map(item => ({
            ...item,
            editing: false,
            tempName: item.name
        }));
    }
    async getPowerPlantList() {
        const { data: powerPlantList } = await getPowerPlants({ pagination: { page: 1, limit: 99999 } });
        this.powerPlantList = powerPlantList.items;
    }
    close() {
        this.isOpen = false;
        this.dispatchEvent(new CustomEvent('close'));
    }
};
__decorate([
    property({ type: Boolean }),
    __metadata("design:type", Object)
], PopupGroupManegement.prototype, "isOpen", void 0);
__decorate([
    state(),
    __metadata("design:type", String)
], PopupGroupManegement.prototype, "newGroupName", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], PopupGroupManegement.prototype, "powerPlantList", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], PopupGroupManegement.prototype, "powerPlantGroupList", void 0);
__decorate([
    state(),
    __metadata("design:type", String)
], PopupGroupManegement.prototype, "powerPlantFilter", void 0);
__decorate([
    state(),
    __metadata("design:type", String)
], PopupGroupManegement.prototype, "selectedGroupId", void 0);
__decorate([
    state(),
    __metadata("design:type", Array)
], PopupGroupManegement.prototype, "selectedPowerPlantIds", void 0);
PopupGroupManegement = __decorate([
    customElement('popup-group-manegement')
], PopupGroupManegement);
export { PopupGroupManegement };
//# sourceMappingURL=popup-group-manegement.js.map