/**
 * @aurora-catalyst-generated
 * @source cliter/iam/bounded-context.aurora.yaml
 */
import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { useAggregateShell, useBreadcrumbs } from '@aurora';
import { provideTranslocoScope, TranslocoDirective, TranslocoService } from '@jsverse/transloco';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucidePuzzle } from '@ng-icons/lucide';
import { toast } from '@spartan-ng/brain/sonner';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmCardImports } from '@spartan-ng/helm/card';
import { HlmSpinnerImports } from '@spartan-ng/helm/spinner';
import { type IamBoundedContext } from '@src/src/app/aurora.types';
import PermissionListComponent from '../../permission/features/permission-list.component';
import { BOUNDED_CONTEXT_DETAIL_CONFIG } from '../data-access/bounded-context.detail-config';
import { BOUNDED_CONTEXT_LIST_CONFIG } from '../data-access/bounded-context.list-config';
import { BoundedContextFormComponent } from './bounded-context-form.component';

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    TranslocoDirective,
    NgIcon,
    HlmButtonImports,
    HlmCardImports,
    HlmSpinnerImports,
    BoundedContextFormComponent,
    PermissionListComponent,
  ],
  providers: [provideIcons({ lucidePuzzle }), provideTranslocoScope('iam')],
  template: `
    <ng-container *transloco="let t; scope: 'iam'">
      <div class="space-y-3 px-6 pt-2 pb-6">
        <!-- Header -->
        <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="lucidePuzzle"
              class="text-[1em]"
            />
            {{ mode() === 'new' ? t('Create') : t('Edit') }}
            {{ t('iam.bounded-context.BoundedContext') }}
          </h1>
        </div>

        <!-- Toolbar -->
        <div class="flex items-center justify-end gap-2">
          <button
            hlmBtn
            variant="outline"
            size="sm"
            (click)="onCancel()"
          >
            {{ t('Cancel') }}
          </button>
          <button
            [disabled]="form.signalForm.invalid || form.signalForm.pristine || shell.loading()"
            hlmBtn
            size="sm"
            (click)="form.submit()"
          >
            @if (shell.loading()) {
              <hlm-spinner class="text-sm" />
            }
            {{ mode() === 'new' ? t('Create') : t('Save') }}
          </button>
        </div>

        <!-- Form card -->
        <section
          class="max-w-lg"
          hlmCard
        >
          <div hlmCardHeader>
            <h3 hlmCardTitle>{{ t('iam.bounded-context.BoundedContextDetails') }}</h3>
            <p hlmCardDescription>
              {{ t('iam.bounded-context.BoundedContextDetailsDescription') }}
            </p>
          </div>
          <div hlmCardContent>
            <au-bounded-context-form
              #form
              [initial]="shell.initial()"
              [mode]="mode()"
              (save)="onSave($event)"
              (cancel)="onCancel()"
            />
          </div>
        </section>

        @if (mode() === 'edit') {
          <section
            class="mt-4"
            hlmCard
          >
            <div hlmCardHeader>
              <h3 hlmCardTitle>{{ t('iam.permission.Title') }}</h3>
            </div>
            <div hlmCardContent>
              <au-permission-list
                [parentFilter]="{ field: 'boundedContextId', value: parentId() ?? '' }"
                mode="embed"
              />
            </div>
          </section>
        }
      </div>
    </ng-container>
  `,
})
export default class BoundedContextDetailComponent {
  // injections
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);
  private readonly transloco = inject(TranslocoService);

  // signals
  readonly mode = signal<'new' | 'edit'>(this.route.snapshot.data['mode']);
  readonly parentId = signal<string | null>(this.route.snapshot.paramMap.get('id'));

  readonly shell = useAggregateShell<IamBoundedContext>({
    listConfig: BOUNDED_CONTEXT_LIST_CONFIG,
    detailConfig: BOUNDED_CONTEXT_DETAIL_CONFIG,
  });

  // breadcrumb
  private readonly breadcrumb = useBreadcrumbs([
    { translation: 'navigation.BoundedContexts', link: '/iam/bounded-context' },
    { translation: this.mode() === 'new' ? 'Create' : 'Edit' },
  ]);

  constructor() {
    const item = this.route.snapshot.data['item'] as IamBoundedContext | null | undefined;
    if (item) {
      this.shell.setInitial(item);
    }
  }

  async onSave(value: IamBoundedContext): Promise<void> {
    try {
      await this.shell.save(value, this.mode());
      const verb = this.mode() === 'new' ? 'Created.M' : 'Saved.M';
      toast.success(
        `${this.transloco.translate(verb)} ${this.transloco.translate('Successfully')}`,
      );
      this.router.navigate(['/iam/bounded-context']);
    } catch {
      // error displayed by GRAPHQL_ERROR_HANDLER
    }
  }

  onCancel(): void {
    this.router.navigate(['/iam/bounded-context']);
  }
}
