/**
 * Account detail page — combined account+user form.
 * Overrides the codegen scaffold (excludedFiles in cliter/iam/account.aurora.yaml).
 * See `openspec/specs/iam-account-management-ui/spec.md`.
 */
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 { lucideUserCog2 } 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 CoreLang,
  type IamAccount,
  type IamRole,
  type IamTag,
  type IamTenant,
  type OAuthClient,
} from '@src/src/app/aurora.types';
import { ACCOUNT_DETAIL_CONFIG } from '../data-access/account.detail-config';
import { ACCOUNT_LIST_CONFIG } from '../data-access/account.list-config';
import { AccountFormComponent } from './account-form.component';

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    TranslocoDirective,
    NgIcon,
    HlmButtonImports,
    HlmCardImports,
    HlmSpinnerImports,
    AccountFormComponent,
  ],
  providers: [provideIcons({ lucideUserCog2 }), 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="lucideUserCog2"
              class="text-[1em]"
            />
            {{ mode() === 'new' ? t('Create') : t('Edit') }} {{ t('iam.account.Account') }}
          </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.account.AccountDetails') }}</h3>
            <p hlmCardDescription>{{ t('iam.account.AccountDetailsDescription') }}</p>
          </div>
          <div hlmCardContent>
            <au-account-form
              #form
              [initial]="shell.initial()"
              [mode]="mode()"
              [tenantOptions]="tenantOptions()"
              [roleOptions]="roleOptions()"
              [tagOptions]="tagOptions()"
              [clientOptions]="clientOptions()"
              [langOptions]="langOptions()"
              (save)="onSave($event)"
              (cancel)="onCancel()"
            />
          </div>
        </section>
      </div>
    </ng-container>
  `,
})
export default class AccountDetailComponent {
  // 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<IamAccount>({
    listConfig: ACCOUNT_LIST_CONFIG,
    detailConfig: ACCOUNT_DETAIL_CONFIG,
  });

  readonly tenantOptions = signal<IamTenant[]>([]);
  readonly roleOptions = signal<IamRole[]>([]);
  readonly tagOptions = signal<IamTag[]>([]);
  readonly clientOptions = signal<OAuthClient[]>([]);
  readonly langOptions = signal<CoreLang[]>([]);

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

  constructor() {
    const resolved = (this.route.snapshot.data['item'] ?? this.route.snapshot.data['init']) as
      | {
          item?: IamAccount | null;
          tenantOptions?: IamTenant[];
          roleOptions?: IamRole[];
          tagOptions?: IamTag[];
          clientOptions?: OAuthClient[];
          langOptions?: CoreLang[];
        }
      | null
      | undefined;
    if (resolved?.item) {
      this.shell.setInitial(resolved.item);
    }
    this.tenantOptions.set(resolved?.tenantOptions ?? []);
    this.roleOptions.set(resolved?.roleOptions ?? []);
    this.tagOptions.set(resolved?.tagOptions ?? []);
    this.clientOptions.set(resolved?.clientOptions ?? []);
    this.langOptions.set(resolved?.langOptions ?? []);
  }

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

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