import { Component, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { AdminUserDirectorySummary, AdminUserRoleId } from '../../models/user-directory.model';

export interface UserEditValue {
  firstName: string;
  lastName: string;
  role: AdminUserRoleId;
}

@Component({
  selector: 'app-user-edit',
  imports: [MatButtonModule, MatFormFieldModule, MatInputModule, MatSelectModule],
  template: `
    <form class="user-edit" (submit)="submit(); $event.preventDefault()" aria-label="Benutzer bearbeiten">
      <div class="user-edit__fields">
        <mat-form-field appearance="outline" subscriptSizing="dynamic">
          <mat-label>Vorname</mat-label>
          <input matInput name="firstName" [value]="firstName" (input)="firstName = $any($event.target).value" required />
        </mat-form-field>
        <mat-form-field appearance="outline" subscriptSizing="dynamic">
          <mat-label>Nachname</mat-label>
          <input matInput name="lastName" [value]="lastName" (input)="lastName = $any($event.target).value" required />
        </mat-form-field>
        <mat-form-field appearance="outline" subscriptSizing="dynamic">
          <mat-label>Globale Rolle</mat-label>
          <select matNativeControl name="role" [value]="role" (change)="setRole($any($event.target).value)" [disabled]="self">
            <option value="1">Administrator</option>
            <option value="2">Benutzer</option>
          </select>
        </mat-form-field>
      </div>
      @if (self) {
        <p class="user-edit__hint">Die eigene Administratorrolle kann hier nicht entzogen werden.</p>
      }
      <div class="user-edit__actions">
        <button mat-button type="button" (click)="cancel.emit()" [disabled]="saving">Abbrechen</button>
        <button mat-flat-button type="submit" [disabled]="saving || !firstName.trim() || !lastName.trim()">
          {{ saving ? 'Wird gespeichert …' : 'Änderungen speichern' }}
        </button>
      </div>
    </form>
  `,
  styles: `
    .user-edit { padding: 18px; border-radius: 18px; background: var(--mat-sys-surface-container-low); }
    .user-edit__fields { display: grid; grid-template-columns: 1fr 1fr 180px; gap: 12px; }
    .user-edit__hint { margin: 10px 0 0; color: var(--mat-sys-on-surface-variant); }
    .user-edit__actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 16px; }
    @media (max-width: 700px) {
      .user-edit__fields { grid-template-columns: 1fr; }
      .user-edit__actions { align-items: stretch; flex-direction: column-reverse; }
    }
  `,
})
export class UserEdit implements OnChanges {
  @Input({ required: true }) user!: AdminUserDirectorySummary;
  @Input() self = false;
  @Input() saving = false;
  @Output() readonly saved = new EventEmitter<UserEditValue>();
  @Output() readonly cancel = new EventEmitter<void>();

  protected firstName = '';
  protected lastName = '';
  protected role: AdminUserRoleId = 2;

  ngOnChanges(changes: SimpleChanges): void {
    const userChange = changes['user'];
    if (!userChange) return;
    const previous = userChange.previousValue as AdminUserDirectorySummary | undefined;
    const current = userChange.currentValue as AdminUserDirectorySummary;
    if (
      !userChange.firstChange &&
      previous?.id === current.id &&
      previous.firstName === current.firstName &&
      previous.lastName === current.lastName &&
      previous.role?.id === current.role?.id
    ) {
      return;
    }
    this.firstName = current.firstName ?? '';
    this.lastName = current.lastName ?? '';
    this.role = current.role?.id === 1 ? 1 : 2;
  }

  protected submit(): void {
    const firstName = this.firstName.trim();
    const lastName = this.lastName.trim();
    if (!firstName || !lastName || this.saving) return;
    this.saved.emit({ firstName, lastName, role: this.self ? 1 : this.role });
  }

  protected setRole(value: string): void {
    this.role = value === '1' ? 1 : 2;
  }
}
