import { Component, inject, signal } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { RouterLink } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { AuthApi, UpdateProfileRequest } from '../../../../core/auth/auth-api';
import { AuthStore } from '../../../../core/auth/auth-store';
import { HelpAccessService } from '../../../../core/help/help-access';

@Component({
  selector: 'app-profile',
  imports: [
    ReactiveFormsModule,
    RouterLink,
    MatButtonModule,
    MatCardModule,
    MatFormFieldModule,
    MatIconModule,
    MatInputModule,
    MatSnackBarModule,
    MatSlideToggleModule,
  ],
  templateUrl: './profile.html',
  styleUrl: './profile.scss',
})
export class Profile {
  private readonly authApi = inject(AuthApi);
  private readonly authStore = inject(AuthStore);
  private readonly helpAccess = inject(HelpAccessService);
  private readonly snackBar = inject(MatSnackBar);
  protected readonly saving = signal(false);
  protected readonly canOpenGuide = this.helpAccess.canOpenGuide;
  protected readonly form = inject(FormBuilder).nonNullable.group({
    firstName: [this.authStore.currentUser()?.firstName ?? '', Validators.required],
    lastName: [this.authStore.currentUser()?.lastName ?? '', Validators.required],
    oldPassword: [''],
    password: ['', Validators.minLength(6)],
    helpTextsEnabled: [this.authStore.currentUser()?.helpTextsEnabled !== false],
  });

  protected save(): void {
    if (this.form.invalid || this.saving()) return;
    const value = this.form.getRawValue();
    if (value.password && !value.oldPassword) {
      this.form.controls.oldPassword.setErrors({ required: true });
      return;
    }
    const request: UpdateProfileRequest = {
      firstName: value.firstName.trim(),
      lastName: value.lastName.trim(),
      helpTextsEnabled: value.helpTextsEnabled,
    };
    if (value.password) {
      request.oldPassword = value.oldPassword;
      request.password = value.password;
    }
    this.saving.set(true);
    this.authApi.updateProfile(request).subscribe({
      next: (user) => {
        this.authStore.updateUser(user);
        this.form.patchValue({ oldPassword: '', password: '' });
        this.saving.set(false);
        this.snackBar.open('Profil wurde gespeichert.', undefined, { duration: 4000 });
      },
      error: () => {
        this.saving.set(false);
        this.snackBar.open('Profil konnte nicht gespeichert werden.', undefined, {
          duration: 5000,
        });
      },
    });
  }
}
