import { ChangeDetectionStrategy, Component, computed, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { ActivatedRoute, Router } from '@angular/router';
import { map } from 'rxjs';
import { ButtonComponent } from '../../../shared/ui/button/button.component';
import { EmptyStateComponent } from '../../../shared/ui/empty-state/empty-state.component';
import { AuthErrorCode } from '@marketplaces/auth';

interface AuthErrorCopy {
  title: string;
  description: string;
  actionLabel: string;
}

const COPY: Record<AuthErrorCode, AuthErrorCopy> = {
  'session-expired': {
    title: 'Session expired',
    description: 'Your admin session has expired. Sign in again to continue.',
    actionLabel: 'Sign in again'
  },
  'invalid-signature': {
    title: 'Invalid signature',
    description: "The signed challenge could not be verified. Your device's key may not be registered, or the challenge expired before signing.",
    actionLabel: 'Try again'
  },
  unauthorized: {
    title: 'Unauthorized',
    description: 'You need to sign in with an authorized admin key to access this area.',
    actionLabel: 'Sign in'
  },
  forbidden: {
    title: 'Forbidden',
    description: 'Your account role does not have permission to access this page.',
    actionLabel: 'Back to dashboard'
  },
  'backend-unavailable': {
    title: 'Backend unavailable',
    description: 'The authentication service could not be reached. Check your connection and try again shortly.',
    actionLabel: 'Retry'
  }
};

/**
 * Single component renders all five error screens from Requirement §7,
 * keyed by the `:code` route param - avoids five near-identical files for
 * what is purely copy variation.
 */
@Component({
  selector: 'app-auth-error-page',
  standalone: true,
  imports: [EmptyStateComponent, ButtonComponent],
  templateUrl: './auth-error-page.component.html',
  styleUrl: './auth-error-page.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AuthErrorPageComponent {
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);

  private readonly code = toSignal(
    this.route.paramMap.pipe(map(params => (params.get('code') as AuthErrorCode) ?? 'unauthorized')),
    { initialValue: 'unauthorized' as AuthErrorCode }
  );

  readonly copy = computed<AuthErrorCopy>(() => COPY[this.code()] ?? COPY.unauthorized);
  readonly isForbidden = computed(() => this.code() === 'forbidden');

  retry(): void {
    if (this.isForbidden()) {
      this.router.navigateByUrl('/backoffice');
    } else {
      this.router.navigateByUrl('/admin-login');
    }
  }
}
