// import { CatalogRoleTagComponent } from '@/shared/catalog/roles';
import { Maybe } from '@/core';
import { AppCardComponent } from '@/shared/components';
import pageParamsUtils from '@/utils/page-params.utils';
import { Component, computed, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { ButtonDirective } from 'primeng/button';
import { Message } from 'primeng/message';
import { ProgressSpinner } from 'primeng/progressspinner';
import { ToggleSwitch } from 'primeng/toggleswitch';
import { finalize } from 'rxjs';
import { IPermissionRequest, IPermissionResponse } from '../../models';
import { PermissionsService } from '../../services/permissions.service';
import { AccountStore } from '../../store/account.store';

@Component({
  selector: 'consumer-account-permission-list',
  templateUrl: './list.component.html',
  imports: [AppCardComponent, ProgressSpinner, ToggleSwitch, FormsModule, Message, ButtonDirective],
})
export class ConsumerAccountPermissionListComponent {
  private readonly route = inject(ActivatedRoute);

  private readonly service = inject(PermissionsService);
  private readonly accountStore = inject(AccountStore);

  pageParams = computed(() => pageParamsUtils(this.route));
  accountId = signal<string>(this.pageParams()['accountId']);
  permissions = signal<Maybe<IPermissionResponse>>(null);
  loading = signal<boolean>(true);
  submitLoading = signal<boolean>(false);

  account = computed(() => this.accountStore.entity());
  isOwner = computed(() => this.account()?.role === 'OWNER');

  getData() {
    this.loading.set(true);
    this.permissions.set(null);
    this.service
      .getAll(this.accountId())
      .pipe(
        finalize(() => {
          this.loading.set(false);
        }),
      )
      .subscribe((res) => {
        if (res) {
          this.permissions.set(res);
        }
      });
  }

  submit() {
    const dataToSet: IPermissionRequest = {};
    const posPermissions = this.permissions()
      ?.poses?.filter((pos) => pos.hasAccess)
      .map((pos) => pos.id);
    const complexPermissions = this.permissions()
      ?.complexes?.filter((complex) => complex.hasAccess)
      .map((pos) => pos.id);
    const baPermissions = this.permissions()
      ?.business_activities?.filter((ba) => ba.hasAccess)
      .map((ba) => ba.id);

    if (posPermissions?.length) {
      dataToSet.poses = posPermissions;
    }
    if (complexPermissions?.length) {
      dataToSet.complexes = complexPermissions;
    }
    if (baPermissions?.length) {
      dataToSet.business_activities = baPermissions;
    }

    this.submitLoading.set(true);

    this.service
      .update(this.accountId(), dataToSet)
      .pipe(
        finalize(() => {
          this.submitLoading.set(false);
        }),
      )
      .subscribe((res) => {
        this.getData();
      });
  }

  ngOnInit() {
    if (!this.isOwner()) {
      this.getData();
    }
  }
}
