import {Component, inject, signal} from '@angular/core';
import {ServiceManager} from '../../../../service-manager';
import {
  AbstractControl,
  FormControl,
  FormGroup,
  FormsModule,
  ReactiveFormsModule,
  ValidationErrors,
  Validators
} from '@angular/forms';
import {TranslatePipe} from '@ngx-translate/core';
import {TuiBadge, TuiButtonLoading} from '@taiga-ui/kit';
import {
  TUI_BREAKPOINT,
  TuiButton,
  TuiDialog,
  TuiErrorComponent,
  TuiIcon,
  TuiInputDirective,
  TuiLabel,
  TuiTextfieldComponent
} from '@taiga-ui/core';

@Component({
  selector: 'user-settings-security-password',
  imports: [
    FormsModule,
    ReactiveFormsModule,
    TranslatePipe,
    TuiBadge,
    TuiButton,
    TuiButtonLoading,
    TuiDialog,
    TuiErrorComponent,
    TuiIcon,
    TuiInputDirective,
    TuiLabel,
    TuiTextfieldComponent
  ],
  templateUrl: './password.html',
  styleUrl: './password.scss',
})
export class Password {
  serviceManager = inject(ServiceManager)
  breakpoint = inject(TUI_BREAKPOINT)

  changePasswordDialogOpen = signal(false)
  changePasswordRemoveMode = signal(false)
  changePasswordPending = signal(false)

  changeEmailForm = new FormGroup({
    currentPassword: new FormControl(""),
    newPassword: new FormControl(""),
    newPasswordRepeat: new FormControl("")
  }, {
    validators: [(group) => this.chkPassMatch(group)]
  })

  openChangePasswordDialog(modeRemove: boolean) {
    this.changePasswordDialogOpen.set(true)
    this.changePasswordRemoveMode.set(modeRemove)
    this.changeEmailForm.controls["currentPassword"].clearValidators()
    this.changeEmailForm.controls["newPassword"].clearValidators()
    this.changeEmailForm.controls["newPasswordRepeat"].clearValidators()
    if (!modeRemove) {
      this.changeEmailForm.controls["newPassword"].setValidators([Validators.required])
      this.changeEmailForm.controls["newPasswordRepeat"].setValidators([Validators.required])
      this.changeEmailForm.controls["newPassword"].updateValueAndValidity()
      this.changeEmailForm.controls["newPasswordRepeat"].updateValueAndValidity()
    }

    this.changeEmailForm.controls["currentPassword"].setValidators([Validators.required])
    this.changeEmailForm.controls["currentPassword"].updateValueAndValidity()
  }

  async changePassword(currentPassword: string | null, newPassword: string | null) {
    this.changePasswordPending.set(true)
    const service = this.serviceManager.currentSessionHandler
    if (service) {
      try {
        await service.changePassword(newPassword ?? "", currentPassword ?? "")
      } catch (e) {
        this.changeEmailForm.controls["currentPassword"].setErrors({incorrect: true})
      }
    }
  }

  chkPassMatch(group: AbstractControl): ValidationErrors | null {
    return this.changePasswordRemoveMode() ? null : group.value.newPassword == group.value.newPasswordRepeat
      ? null : {passMatchError: true};
  }
}
