import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { DialogsModule } from '@progress/kendo-angular-dialog';
import { InputsModule } from '@progress/kendo-angular-inputs';
import { LabelModule } from '@progress/kendo-angular-label';
import { DropDownsModule } from '@progress/kendo-angular-dropdowns';
import { ButtonsModule } from '@progress/kendo-angular-buttons';
import { UserDto, UpdateUserRequest } from '../../models/user.model';
import { LANGUAGE_OPTIONS, ROLE_OPTIONS } from '../../../../shared/i18n/option-lists';

@Component({
  selector: 'app-edit-user-dialog',
  standalone: true,
  imports: [
    CommonModule, ReactiveFormsModule, DialogsModule,
    InputsModule, LabelModule, DropDownsModule, ButtonsModule
  ],
  templateUrl: './edit-user-dialog.component.html',
})
export class EditUserDialogComponent implements OnInit {
  @Input({ required: true }) user!: UserDto;
  @Output() saved     = new EventEmitter<UpdateUserRequest>();
  @Output() cancelled = new EventEmitter<void>();

  form!: FormGroup;
  readonly roleOptions = ROLE_OPTIONS;
  readonly langOptions = LANGUAGE_OPTIONS;

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.form = this.fb.group({
      email:              [this.user.email, [Validators.required, Validators.email]],
      roles:              [this.user.roles, Validators.required],
      isActive:           [this.user.isActive],
      languagePreference: [this.user.languagePreference],
    });
  }

  onSubmit(): void {
    if (this.form.invalid) { this.form.markAllAsTouched(); return; }
    this.saved.emit(this.form.value as UpdateUserRequest);
  }

  onCancel(): void {
    this.cancelled.emit();
  }
}
