import { Component, inject, signal } from '@angular/core';
import { User } from '../../../models/user-management.api.models';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { FormControl, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { merge } from 'rxjs';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { CommonModule } from '@angular/common';
import { MatTabsModule } from '@angular/material/tabs';
import { UserGroupDirImportComponent } from "../../user-group-dir-import/user-group-dir-import.component";
import { UserService } from '../../../services/api/user.service';
import { RefreshService } from '../../../services/button/refresh.service';
import Swal from 'sweetalert2';

@Component({
  selector: 'app-user-update-form',
  standalone: true,
  imports: [MatFormFieldModule, MatInputModule, FormsModule, ReactiveFormsModule, MatIconModule, MatButtonModule, CommonModule, MatTabsModule, UserGroupDirImportComponent],
  templateUrl: './user-update-form.component.html',
  styleUrl: './user-update-form.component.scss'
})
export class UserUpdateFormComponent {

  readonly dialogRef: MatDialogRef<UserUpdateFormComponent> = inject(MatDialogRef<UserUpdateFormComponent>);

  readonly user: User = inject(MAT_DIALOG_DATA);

  readonly username = new FormControl(this.user.username, [Validators.required]);
  readonly name = new FormControl(this.user.prename, [Validators.required]);
  readonly surname = new FormControl(this.user.name, [Validators.required]);
  readonly shortname = new FormControl(this.user.shortname);
  readonly email = new FormControl(this.user.email, [Validators.required, Validators.email]);
  readonly comment = new FormControl(this.user.comment);

  mailErrorMessage = signal('');
  errorMessage = signal('');

  constructor(private uService: UserService, private rService: RefreshService) {
    merge(
      this.email.statusChanges, this.email.valueChanges)
      .pipe(takeUntilDestroyed())
      .subscribe(() => this.updateMailErrorMessage());

    merge(
      this.username.statusChanges, this.username.valueChanges,
      this.name.statusChanges, this.name.valueChanges,
      this.surname.statusChanges, this.surname.valueChanges)
      .pipe(takeUntilDestroyed())
      .subscribe(() => this.updateErrorMessage());
  }

  updateMailErrorMessage() {
    if (this.email.hasError('required')) {
      this.mailErrorMessage.set('Wert eingeben');
    } else if (this.email.hasError('email')) {
      this.mailErrorMessage.set('Ungültige E-Mail');
    } else {
      this.mailErrorMessage.set('');
    }
  }

  updateErrorMessage() {
    if (this.email.hasError('required')) {
      this.errorMessage.set('Wert eingeben');
    } else {
      this.errorMessage.set('');
    }
  }

  update() {
    if (this.email.valid && this.username.valid && this.name.valid && this.surname.valid) {
      this.user.email = this.email.value!;
      this.user.prename = this.name.value!;
      this.user.username = this.username.value!;
      this.user.name = this.surname.value!;
      this.user.shortname = this.shortname.value!;
      this.user.comment = this.comment.value!;

      this.uService.update(this.user).subscribe({
        next: () => {
          this.rService.executeAll();
        },
        error: err => {
          console.error(err)
          Swal.fire({
            title: "Interner Dienstfehler",
            text: "Bitte wenden Sie sich an das IT-Team, um den Fehler zu beheben.",
            icon: "error"
          });
        }
      })
    }
  }

  delete() {
    Swal.fire({
      text: "Sind Sie sicher, dass Sie diesen Datensatz löschen wollen?",
      icon: "question",
      showDenyButton: true,
      confirmButtonText: "Ja",
      denyButtonText: `Nein`
    }).then((result) => {
      if (result.isConfirmed) {
        if (this.user.id) {
          this.uService.delete(this.user.id).subscribe({
            next: () => {
              this.rService.executeAll();
              this.dialogRef.close();
            },
            error: err => {
              Swal.fire({
                title: "Interner Dienstfehler",
                text: "Bitte wenden Sie sich an das IT-Team, um den Fehler zu beheben.",
                icon: "error"
              });
            },
          })
        }
        else
          Swal.fire({
            title: "Ein unerwarteter Fehler",
            text: "Die Benutzer-ID existiert nicht (Nullwert).",
            icon: "error"
          });
      }
    });
  }
}