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

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

  step = signal(0)
  changeEmailDialogOpen = signal(false)
  changeEmailRemoveMode = signal(false)
  changeEmailPending = signal(false)
  verifyEmailPending = signal(false)
  newAddress = ""

  changeEmailForm = new FormGroup({
    newAddress: new FormControl(""),
    currentPassword: new FormControl(""),
  })

  verifyEmailForm = new FormGroup({
    oldCode: new FormControl(0),
    newCode: new FormControl(0, {validators: [Validators.required]})
  })

  openChangeEmailDialog(modeRemove: boolean) {
    this.changeEmailDialogOpen.set(true)
    this.changeEmailRemoveMode.set(modeRemove)
    this.changeEmailForm.controls["currentPassword"].clearValidators()
    this.changeEmailForm.controls["newAddress"].clearValidators()
    if (!modeRemove) {
      this.changeEmailForm.controls["newAddress"].setValidators([Validators.required])
      this.changeEmailForm.controls["newAddress"].updateValueAndValidity()
    }

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

  async changeEmail(currentPassword: string | null, newMail: string | null) {
    this.changeEmailPending.set(true)
    const service = this.serviceManager.currentSessionHandler
    if (service) {
      try {
        await service.changeEmail(newMail ?? "", currentPassword ?? "")
        if (!this.changeEmailRemoveMode()) {
          this.newAddress = newMail ?? ""
          this.verifyEmailForm.controls["oldCode"].setValidators([Validators.required])
          this.step.set(1)
        }
      } catch (e) {
        this.changeEmailForm.controls["currentPassword"].setErrors({incorrect: true})
      }
    }
  }

  async verifyEmail(newCode: number | null, oldCode: number | null) {
    this.verifyEmailPending.set(true)
    const service = this.serviceManager.currentSessionHandler
    if (service) {
      try {
        await service.verifyEmailChange(oldCode ?? 0, newCode ?? 0, this.newAddress)
        this.changeEmailDialogOpen.set(false)
      } catch (e) {
        this.verifyEmailForm.controls["newCode"].setErrors({incorrect: true})
      }
    }
  }
}
