import { Component, Input } from '@angular/core';
import { BaseFieldComponent, FieldConfig } from './base-field.component';

@Component({
  selector: 'app-phone-field',
  template: `
    <div class="field-container">
      <label [for]="field.name" class="sq-form-label">
        <span class="label-text">{{ field.label }}</span>
        <span *ngIf="field.required" class="required-indicator">*</span>
      </label>
      <div class="phone-input-container">
        <div class="country-code-selector" (click)="toggleCountryCodeSelector()" *ngIf="field.showCountryCodeSelector">
          <span class="country-flag">🇺🇸</span>
          <span class="country-code">{{ selectedCountryCode }}</span>
          <span class="dropdown-icon">▼</span>
        </div>
        <input 
          [id]="field.name"
          type="tel"
          class="sq-form-input phone-input"
          [placeholder]="field.placeholder || 'Enter ' + field.label.toLowerCase()"
          [value]="value"
          (input)="onPhoneChange($event.target.value)"
          [required]="field.required"
          [pattern]="field.pattern || '.*'"
          [readonly]="field.readonly"
          [disabled]="field.disabled"
        />
        <button 
          *ngIf="field.showCountryCodeSelector" 
          class="sq-btn sq-btn-outline sq-btn-sm country-code-btn"
          type="button"
          (click)="toggleCountryCodeSelector()"
        >
          {{ selectedCountryCode }}
        </button>
      </div>
      <div *ngIf="errorMessage" class="sq-error-message">
        {{ errorMessage }}
      </div>
      <div *ngIf="field.description" class="field-description">
        {{ field.description }}
      </div>
    </div>
  `
})
export class PhoneFieldComponent extends BaseFieldComponent {
  @Input() field: FieldConfig;
  @Input() value: string;
  
  selectedCountryCode = '+91';
  errorMessage = '';
  
  onPhoneChange(value: string) {
    // Validate phone number format
    if (this.field.pattern) {
      const regex = new RegExp(this.field.pattern);
      if (!regex.test(value)) {
        this.errorMessage = this.field.errorMessage || 'Please enter a valid phone number';
      } else {
        this.errorMessage = '';
      }
    }
    this.onChange(value);
  }
  
  toggleCountryCodeSelector() {
    // Implementation for country code selector
    // This would typically open a modal or dropdown
  }
}