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

@Component({
  selector: 'user-settings-security-phone',
  imports: [
    ReactiveFormsModule,
    TranslatePipe,
    TuiBadge,
    TuiButton,
    TuiButtonLoading,
    TuiDialog,
    TuiErrorComponent,
    TuiIcon,
    TuiInputDirective,
    TuiLabel,
    TuiTextfieldComponent,
    TuiInputPhoneInternationalComponent,
    TuiSortCountriesPipe
  ],
  templateUrl: './phone.html',
  styleUrl: './phone.scss',
})
export class Phone {
  protected readonly countries = getCountries();
  protected countryIsoCode: TuiCountryIsoCode = 'HU';
  breakpoint = inject(TUI_BREAKPOINT)

  serviceManager = inject(ServiceManager)

  step = signal(0)
  changePhoneDialogOpen = signal(false)
  changePhoneRemoveMode = signal(false)
  changePhonePending = signal(false)
  verifyPhonePending = signal(false)
  newNumber = ""

  changePhoneForm = new FormGroup({
    newNumber: new FormControl(""),
    currentPassword: new FormControl(""),
  })

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

  openChangePhoneDialog(modeRemove: boolean) {
    this.changePhoneDialogOpen.set(true)
    this.changePhoneRemoveMode.set(modeRemove)
    this.changePhoneForm.controls["currentPassword"].clearValidators()
    this.changePhoneForm.controls["newNumber"].clearValidators()
    if (!modeRemove) {
      this.changePhoneForm.controls["newNumber"].setValidators([Validators.required])
      this.changePhoneForm.controls["newNumber"].updateValueAndValidity()
    }

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

  async changePhone(currentPassword: string | null, newNumber: string | null) {
    if (this.changePhoneRemoveMode()) {
      newNumber = "remove"
    }
    this.changePhonePending.set(true)
    const service = this.serviceManager.currentSessionHandler
    if (service) {
      try {
        await service.changePhoneNumber(currentPassword ?? "", newNumber ?? "")
        this.step.set(1)
        this.newNumber = newNumber ?? ""
        if (!this.changePhoneRemoveMode()) {
          this.verifyPhoneForm.controls["oldCode"].setValidators([Validators.required])
        }
      } catch (e) {
        this.changePhoneForm.controls["currentPassword"].setErrors({incorrect: true})
        this.changePhonePending.set(false)
      }
    }
  }

  async verifyPhone(newCode: number | null, oldCode: number | null) {
    this.verifyPhonePending.set(true)
    const service = this.serviceManager.currentSessionHandler
    if (service) {
      try {
        await service.verifyPhoneNumberChange(this.newNumber, oldCode ?? 0, newCode ?? 0)
        this.changePhoneDialogOpen.set(false)
      } catch (e) {
        this.verifyPhoneForm.controls["newCode"].setErrors({incorrect: true})
        this.verifyPhonePending.set(false)
      }
    }
  }
}
