import { AfterViewInit, ChangeDetectionStrategy, Component, inject, model, output, signal } from '@angular/core';
import { PasswordService } from '../services/password.service';
import { FastButtonComponent } from './fast-button.component';
import { FAST_KENDO_COMMON } from '../../app.config';
import { FastTextboxComponent } from "./fast-textbox.component";
import { FastWindowComponent } from "./fast-window.component";
import { NotifyService } from '../services/notify.service';
import * as util from '../utils/util';
import { ReactiveFormsModule } from '@angular/forms';

@Component({
  imports: [FAST_KENDO_COMMON, FastButtonComponent, FastTextboxComponent, FastWindowComponent, ReactiveFormsModule],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
<fast-window [height]="140" [width]="400" [minWidth]="300" [minHeight]="140" title="Password required" [hasMinMaxActions]="false" (close)="onCancel()">
  <form onsubmit="return false;">
    <div class="grow flex-col p-3">
        <fast-textbox class="inputFocusTarget" type="password" [(value)]="password" (keydown.enter)="onSubmit()"/>
    </div>
    <div class="flex gap-2 m-3 justify-end">
      <fast-button (click)="onCancel()">Cancel</fast-button>
      <fast-button type="primary" (click)="onSubmit()" [disabled]="busy()">
        {{ busy() ? 'Checking…' : 'Continue' }}
      </fast-button>
    </div>
  </form>
</fast-window>
  `,
  styles: `
:host { @apply absolute w-full h-full }
  `
})
export class FastPassPromptComponent implements AfterViewInit {
  private passwordService = inject(PasswordService);
  private notify = inject(NotifyService);

  password = model('');
  busy = signal(false);
  closed = output<boolean>();

  ngAfterViewInit(): void {
    util.focusInputTarget();
  }

  async onSubmit() {
    const value = this.password().trim();
    if (!value) {
      this.notify.error('Please enter a password.');
      return;
    }

    this.busy.set(true);
    try {
      const ok = await this.passwordService.validateWithServer(value);
      if (!ok) {
        this.notify.error('Incorrect password. Please try again.');
        return;
      }
      this.passwordService.setPassword(value); // Persist only after server says it's valid
      this.closed.emit(true); // true for success
    }
    catch (e) {
      console.log(e)
      this.notify.error('Network/server error. Try again.');
    }
    finally {
      this.busy.set(false);
    }
  }

  onCancel() {
    this.closed.emit(false); // false for cancel
  }
}
