import { Component, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { ApiService } from '../../core/api.service';
import { AuthService } from '../../core/auth.service';
import { LangService } from '../../core/lang.service';

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [FormsModule],
  template: `
    <div class="wrap">
      <button class="lang" (click)="lang.toggle()">{{ lang.lang() === 'ar' ? 'EN' : 'عربي' }}</button>
      <img src="assets/askar-logo.png" class="login-logo fade-in" [alt]="lang.t('brand')" />
      <div class="card panel fade-in">
        <h2>{{ lang.t('login_title') }}</h2>
        <p class="muted">{{ lang.t('login_sub') }}</p>

        <form (ngSubmit)="submit()">
          <div class="field">
            <label>{{ lang.t('username') }}</label>
            <input type="text" [(ngModel)]="username" name="username" autocomplete="username" />
          </div>
          <div class="field">
            <label>{{ lang.t('password') }}</label>
            <input type="password" [(ngModel)]="password" name="password" autocomplete="current-password" />
          </div>
          @if (error()) { <p class="err">{{ lang.t('sign_in_error') }}</p> }
          <button type="submit" class="btn btn--gold btn--block" [disabled]="busy() || !username || !password">
            {{ busy() ? lang.t('loading') : lang.t('sign_in') }}
          </button>
        </form>

        @if (roles().length) {
          <div class="test-panel">
            <div class="test-h">🧪 {{ lang.t('test_signin') }}</div>
            <div class="role-btns">
              @for (r of roles(); track r.role) {
                <button type="button" class="role-btn" [disabled]="busy()" (click)="quick(r.role)">
                  {{ lang.lang() === 'ar' ? r.name_ar : r.name }}
                </button>
              }
            </div>
          </div>
        }
      </div>
    </div>
  `,
  styles: [`
    .wrap { min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 22px;
      background: radial-gradient(900px 500px at 70% -10%, rgba(184,154,94,.16), transparent 60%), var(--brand); position: relative; }
    .lang { position: absolute; top: 22px; inset-inline-end: 24px; border: 1px solid rgba(255,255,255,.25);
      background: transparent; color: #fff; border-radius: 999px; padding: 6px 14px; font-weight: 600; cursor: pointer; font-family: inherit; }
    .login-logo { width: 200px; max-width: 60vw; height: auto; }
    .panel { width: 100%; max-width: 400px; padding: 38px 36px; }
    h2 { margin-bottom: 4px; }
    .muted { margin-bottom: 24px; }
    .err { color: var(--danger); font-size: .9rem; margin: 0 0 14px; }
    .test-panel { margin-top: 22px; padding: 14px 16px; border: 1px dashed var(--gold, #b8965e); border-radius: 12px; }
    .test-h { font-weight: 700; color: var(--gold-deep, #8a6d33); margin-bottom: 10px; font-size: .9rem; }
    .role-btns { display: flex; flex-wrap: wrap; gap: 8px; }
    .role-btn { border: 1px solid var(--line); background: #fff; border-radius: 999px; padding: 7px 13px;
      font-size: .82rem; font-weight: 600; cursor: pointer; font-family: inherit; color: var(--ink-soft); }
    .role-btn:hover { border-color: var(--gold); color: var(--gold-deep); }
  `],
})
export class LoginComponent {
  lang = inject(LangService);
  private api = inject(ApiService);
  private auth = inject(AuthService);
  private router = inject(Router);

  username = '';
  password = '';
  busy = signal(false);
  error = signal(false);
  roles = signal<{ role: string; name: string; name_ar: string; username: string }[]>([]);

  constructor() {
    // Offer one-tap role sign-in when the backend exposes it (404s otherwise).
    this.api.devStaff().subscribe({
      next: (r) => this.roles.set(r.data.roles),
      error: () => {},
    });
  }

  submit(): void {
    this.busy.set(true); this.error.set(false);
    this.api.login(this.username, this.password).subscribe({
      next: (r) => { this.auth.set(r.data.token, r.data.user, r.data.permissions); this.busy.set(false); this.router.navigate(['/dashboard']); },
      error: () => { this.busy.set(false); this.error.set(true); },
    });
  }

  quick(role: string): void {
    this.busy.set(true); this.error.set(false);
    this.api.devStaffLogin(role).subscribe({
      next: (r) => { this.auth.set(r.data.token, r.data.user, r.data.permissions); this.busy.set(false); this.router.navigate(['/dashboard']); },
      error: () => { this.busy.set(false); this.error.set(true); },
    });
  }
}
