import { Component, forwardRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatTelInput } from 'mat-tel-input';
import { parsePhoneNumberFromString } from 'libphonenumber-js';

import { FieldBase } from '@pega/angular-sdk-components';
import { ComponentMapperComponent } from '@pega/angular-sdk-components';
import { handleEvent } from '@pega/angular-sdk-components';
import { PConnFieldProps } from '@pega/angular-sdk-components';

interface {{COMPONENT_CLASS_NAME}}Props extends PConnFieldProps {
  // If any, enter additional props that only exist on Phone here
}

@Component({
  selector: 'app-{{COMPONENT_CLASS_NAME_KEBAB}}',
  templateUrl: './{{COMPONENT_CLASS_NAME_KEBAB}}.component.html',
  styleUrls: ['./{{COMPONENT_CLASS_NAME_KEBAB}}.component.scss'],
  imports: [CommonModule, ReactiveFormsModule, MatFormFieldModule, MatTelInput, forwardRef(() => ComponentMapperComponent)]
})
export class {{COMPONENT_CLASS_NAME}}Component extends FieldBase {
  configProps$: {{COMPONENT_CLASS_NAME}}Props;

  preferredCountries: string[] = ['us'];

  /**
   * Updates the component when there are changes in the state.
   */
  override updateSelf(): void {
    // Resolve config properties
    this.configProps$ = this.pConn$.resolveConfigProps(this.pConn$.getConfigProps()) as {{COMPONENT_CLASS_NAME}}Props;

    // Update component common properties
    this.updateComponentCommonProperties(this.configProps$);

    // Extract and normalize the value property
    const { value } = this.configProps$;
    if (value) {
      this.value$ = value;
      this.fieldControl.setValue(this.value$);
      this.updatePreferredCountries();
    }
  }

  fieldOnBlur() {
    // 'blur' isn't getting fired
  }

  fieldOnChange() {
    const oldVal = this.value$ ?? '';
    const newVal = this.formGroup$.controls[this.controlName$].value;
    const isValueChanged = newVal?.toString() !== oldVal.toString();

    if (isValueChanged) {
      const value = this.formGroup$.controls[this.controlName$].value;
      handleEvent(this.actionsApi, 'changeNblur', this.propName, value);
    }
  }

  updatePreferredCountries() {
    if (this.value$ && typeof this.value$ === 'string') {
      const phoneNumber = parsePhoneNumberFromString(this.value$);
      this.preferredCountries =
        phoneNumber?.country && !this.preferredCountries.includes(phoneNumber?.country.toLowerCase())
          ? [phoneNumber?.country?.toLowerCase(), ...this.preferredCountries]
          : this.preferredCountries;
    }
  }

  override getErrorMessage() {
    // look for validation messages for json, pre-defined or just an error pushed from workitem (400)
    if (this.fieldControl.hasError('message')) {
      return this.angularPConnectData.validateMessage ?? '';
    }

    if (this.fieldControl.hasError('required')) {
      return 'You must enter a value';
    }

    if (this.fieldControl.errors) {
      return 'Invalid Phone';
    }

    return '';
  }
}
