/**
 * @aurora-catalyst-generated
 * @source cliter/iam/account.aurora.yaml
 */
import { ChangeDetectionStrategy, Component, inject, signal, viewChild } from '@angular/core';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import {
  ColumnToggle,
  DataTable,
  DEFAULT_PAGE_SIZE,
  getExportableColumns,
  getFilterableColumns,
  getRelationIncludes,
  getSearchableColumnIds,
  getToggleableColumns,
  HeadSelection,
  listContainerClass,
  RowSelection,
  TableExport,
  TableFilters,
  TablePagination,
  TableSearch,
  useBreadcrumbs,
  useGraphqlList,
  usePaginatedDataTable,
  type DataTableColumnDef,
  type DataTableData,
} from '@aurora';
import { provideTranslocoScope, TranslocoDirective, TranslocoService } from '@jsverse/transloco';
import { NgIcon, provideIcons } from '@ng-icons/core';
import {
  lucideBuilding2,
  lucidePlus,
  lucideTag,
  lucideTarget,
  lucideUserCog2,
} from '@ng-icons/lucide';
import { toast } from '@spartan-ng/brain/sonner';
import { HlmAlertDialog, HlmAlertDialogImports } from '@spartan-ng/helm/alert-dialog';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmIconImports } from '@spartan-ng/helm/icon';
import { type IamAccount, type IamTenant } from '@src/src/app/aurora.types';
import { flexRenderComponent } from '@tanstack/angular-table';
import { lastValueFrom } from 'rxjs';
import { getAccountStandaloneColumns } from '../account.columns';
import { ACCOUNT_LIST_CONFIG } from '../data-access/account.list-config';
import { AccountListActionsCell } from './account-list-actions-cell.component';

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    RouterLink,
    TranslocoDirective,
    NgIcon,
    ColumnToggle,
    DataTable,
    TableExport,
    TableFilters,
    TablePagination,
    TableSearch,
    HlmAlertDialogImports,
    HlmButtonImports,
    HlmIconImports,
  ],
  providers: [
    provideIcons({ lucideBuilding2, lucidePlus, lucideTag, lucideTarget, lucideUserCog2 }),
    provideTranslocoScope('iam'),
  ],
  host: { class: 'block' },
  template: `
    <div
      *transloco="let t; scope: 'iam'"
      [class]="containerClass"
    >
      <div class="mb-2 flex items-center justify-between">
        <h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight">
          <ng-icon
            name="lucideUserCog2"
            class="text-[1em]"
          />
          {{ t('iam.account.Title') }}
        </h1>
      </div>

      <!-- Toolbar -->
      <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
        <au-table-search
          [placeholder]="t('FilterPlaceholder')"
          [value]="paginated.search.value()"
          (search)="paginated.setSearch($event)"
        />
        <div class="flex items-center gap-2">
          <a
            hlmBtn
            size="sm"
            routerLink="new"
          >
            <ng-icon
              name="lucidePlus"
              class="sm:mr-1"
              hlm
              size="sm"
            />
            <span class="hidden sm:inline">{{ t('New.M') }} {{ t('iam.account.Account') }}</span>
          </a>
          <au-table-filters
            [columns]="filterableColumns()"
            (filtersChange)="paginated.setFilters($event)"
          />
          <au-column-toggle
            [table]="paginated.table"
            [columns]="toggleableColumns()"
          />
          <au-table-export
            [table]="paginated.table"
            [columns]="exportableColumns()"
            filename="accounts"
          />
        </div>
      </div>

      <!-- Table -->
      <au-data-table
        [table]="paginated.table"
        [loading]="paginated.loading()"
        [emptyMessage]="t('iam.account.NoAccountsFound')"
      />

      <!-- Pagination -->
      <au-table-pagination [table]="paginated.table" />

      <!-- Delete confirmation dialog -->
      <hlm-alert-dialog>
        <hlm-alert-dialog-content *hlmAlertDialogPortal="let ctx">
          <hlm-alert-dialog-header>
            <h2 hlmAlertDialogTitle>{{ t('Delete') }} {{ t('iam.account.Account') }}</h2>
            <p hlmAlertDialogDescription>
              {{ t('DeleteConfirmation', { name: accountToDelete()?.email }) }}
            </p>
          </hlm-alert-dialog-header>
          <hlm-alert-dialog-footer>
            <button
              hlmAlertDialogCancel
              (click)="ctx.close()"
            >
              {{ t('Cancel') }}
            </button>
            <button
              hlmAlertDialogAction
              (click)="onConfirmDelete(); ctx.close()"
            >
              {{ t('Delete') }}
            </button>
          </hlm-alert-dialog-footer>
        </hlm-alert-dialog-content>
      </hlm-alert-dialog>
    </div>
  `,
})
export default class AccountListComponent {
  // injections
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);
  private readonly transloco = inject(TranslocoService);

  // widgets
  private readonly deleteDialog = viewChild(HlmAlertDialog);

  // layout
  protected readonly containerClass = listContainerClass('standalone');

  // state
  private readonly dataResolved = this.route.snapshot.data['pagination'] as
    | {
        pagination: DataTableData<IamAccount>;
        tenantOptions: IamTenant[];
      }
    | undefined;
  readonly accountToDelete = signal<IamAccount | null>(null);

  // columns
  private readonly baseColumns = getAccountStandaloneColumns({ translator: this.transloco });
  protected readonly filterableColumns = () => getFilterableColumns(this.baseColumns);
  protected readonly exportableColumns = () => getExportableColumns(this.baseColumns);
  protected readonly toggleableColumns = () => getToggleableColumns(this.baseColumns);
  private readonly searchColumns = getSearchableColumnIds(this.baseColumns);
  private readonly relationIncludes = getRelationIncludes(this.baseColumns);
  protected readonly columns: DataTableColumnDef<IamAccount>[] = [
    {
      id: 'actions',
      sticky: 'left',
      size: 50,
      enableHiding: false,
      enableSorting: false,
      header: '',
      cell: () =>
        flexRenderComponent(AccountListActionsCell, {
          inputs: {
            onRequestEdit: (account: IamAccount) => this.onEdit(account),
            onRequestDelete: (account: IamAccount) => this.onDelete(account),
          },
        }),
    },
    {
      id: 'select',
      sticky: 'left',
      size: 40,
      enableHiding: false,
      enableSorting: false,
      header: () => flexRenderComponent(HeadSelection),
      cell: () => flexRenderComponent(RowSelection),
    },
    ...this.baseColumns,
  ];

  // composables
  private readonly breadcrumb = useBreadcrumbs([{ translation: 'navigation.Accounts' }]);
  private readonly list = useGraphqlList<IamAccount>(ACCOUNT_LIST_CONFIG);
  protected readonly paginated = usePaginatedDataTable<IamAccount>({
    paginate: (input) => this.list.paginate(input),
    columns: this.columns,
    searchableColumnIds: this.searchColumns,
    defaultPageSize: DEFAULT_PAGE_SIZE,
    relationIncludes: () => (this.relationIncludes.length > 0 ? this.relationIncludes : []),
  });

  constructor() {
    if (this.dataResolved?.pagination) {
      this.paginated.seed(this.dataResolved.pagination);
    }
  }

  // ─── methods ────────────────────────────────────────────────

  onEdit(account: IamAccount) {
    this.router.navigate(['/iam/account/edit', account.id]);
  }

  onDelete(account: IamAccount) {
    this.accountToDelete.set(account);
    this.deleteDialog()?.open();
  }

  async onConfirmDelete() {
    const account = this.accountToDelete();
    if (!account) return;

    try {
      await lastValueFrom(this.list.deleteById(account.id));
      toast.success(
        `${this.transloco.translate('Deleted.M')} ${this.transloco.translate('Successfully')}`,
      );
      await this.paginated.refetch();
    } catch {
      // error displayed by GRAPHQL_ERROR_HANDLER
    } finally {
      this.accountToDelete.set(null);
    }
  }
}
