/**
 * @aurora-catalyst-generated
 * @source cliter/iam/user.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 { 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 IamUser } from '@src/src/app/aurora.types';
import { USER_DETAIL_CONFIG } from '../data-access/user.detail-config';
import { USER_LIST_CONFIG } from '../data-access/user.list-config';
import { UserFormComponent } from './user-form.component';

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    TranslocoDirective,
    HlmButtonImports,
    HlmCardImports,
    HlmSpinnerImports,
    UserFormComponent,
  ],
  providers: [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">
            {{ mode() === 'new' ? t('Create') : t('Edit') }} {{ t('iam.user.User') }}
          </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 hlmCard>
          <div hlmCardHeader>
            <h3 hlmCardTitle>{{ t('iam.user.UserDetails') }}</h3>
            <p hlmCardDescription>{{ t('iam.user.UserDetailsDescription') }}</p>
          </div>
          <div hlmCardContent>
            <au-user-form
              #form
              [initial]="shell.initial()"
              [mode]="mode()"
              (save)="onSave($event)"
              (cancel)="onCancel()"
            />
          </div>
        </section>
      </div>
    </ng-container>
  `,
})
export default class UserDetailComponent {
  // 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 shell = useAggregateShell<IamUser>({
    listConfig: USER_LIST_CONFIG,
    detailConfig: USER_DETAIL_CONFIG,
  });

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

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

  async onSave(value: IamUser): 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/user']);
    } catch {
      // error displayed by GRAPHQL_ERROR_HANDLER
    }
  }

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