import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { AdminUsersFacade } from '../facade/admin-users.facade';
import { AdminUserScope, AdminUserStatus } from '../models/admin-user.model';
import { TranslatePipe } from '../../../../i18n/translate.pipe';
import { TranslateService } from '../../../../i18n/translate.service';
import { ButtonComponent } from '../../../../shared/ui/button/button.component';
import { InputComponent } from '../../../../shared/ui/input/input.component';
import { BadgeComponent } from '../../../../shared/ui/badge/badge.component';
import { TableComponent } from '../../../../shared/ui/table/table.component';
import { DialogComponent } from '../../../../shared/ui/dialog/dialog.component';
import { SkeletonComponent } from '../../../../shared/ui/skeleton/skeleton.component';
import { EmptyStateComponent } from '../../../../shared/ui/empty-state/empty-state.component';
import { ConfirmDialogComponent } from '../../../../shared/ui/confirm-dialog/confirm-dialog.component';

@Component({
  selector: 'app-admin-users-page',
  standalone: true,
  imports: [CommonModule, FormsModule, TranslatePipe, ButtonComponent, InputComponent, BadgeComponent, TableComponent, DialogComponent, SkeletonComponent, EmptyStateComponent, ConfirmDialogComponent],
  templateUrl: './admin-users-page.component.html',
  styleUrls: ['./admin-users-page.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AdminUsersPageComponent {
  readonly facade = inject(AdminUsersFacade);
  private readonly translate = inject(TranslateService);

  readonly inviteEmail = signal('');
  readonly inviteRoleId = signal('viewer');
  readonly inviteScope = signal<AdminUserScope>('office');
  readonly pendingSuspendUserId = signal<string | null>(null);

  constructor() {
    this.facade.loadAll();
  }

  sendInvite(): void {
    this.facade.invite(this.inviteEmail(), this.inviteRoleId(), this.inviteScope());
    this.inviteEmail.set('');
  }

  toggleStatus(userId: string, current: AdminUserStatus): void {
    const next: AdminUserStatus = current === 'suspended' ? 'active' : 'suspended';
    if (next === 'suspended') {
      this.pendingSuspendUserId.set(userId);
      return;
    }
    this.facade.setStatus(userId, next);
  }

  confirmSuspend(): void {
    const userId = this.pendingSuspendUserId();
    if (userId) {
      this.facade.setStatus(userId, 'suspended');
    }
    this.pendingSuspendUserId.set(null);
  }

  private static readonly PERMISSION_KEYS: Record<string, string> = {
    '*': 'all',
    'products.manage': 'productsManage',
    'products.view': 'productsView',
    'categories.manage': 'categoriesManage',
    'orders.manage': 'ordersManage',
    'orders.view': 'ordersView',
    'media.manage': 'mediaManage',
  };

  readonly roleLabel = (roleId: string): string => this.translate.t('adminUsers.roleValue.' + roleId);

  readonly permissionLabel = (code: string): string => {
    const key = AdminUsersPageComponent.PERMISSION_KEYS[code];
    return key ? this.translate.t('adminUsers.permission.' + key) : code;
  };

  auditText(entry: { eventKey: 'roleChanged' | 'statusChanged'; roleId?: string; status?: AdminUserStatus }): string {
    if (entry.eventKey === 'roleChanged' && entry.roleId) {
      return this.translate.t('adminUsers.audit.roleChanged', { role: this.roleLabel(entry.roleId) });
    }
    if (entry.eventKey === 'statusChanged' && entry.status) {
      return this.translate.t('adminUsers.audit.statusChanged', { status: this.translate.t('adminUsers.statusValue.' + entry.status) });
    }
    return '';
  }
}
