import { Component, Input, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'app-chip-input',
  templateUrl: './chip-input.component.html',
  styleUrls: ['./chip-input.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => ChipInputComponent),
      multi: true,
    },
  ],
})
export class ChipInputComponent implements ControlValueAccessor {
  @Input() type: string = 'text';
  @Input() placeholder?: string;
  chips: string[] = [];
  inputValue: string = '';

  protected onChange: (value: string[]) => void = () => {};
  protected onTouched: () => void = () => {};

  writeValue(value: string[]): void {
    this.chips = value || [];
  }

  registerOnChange(fn: (value: string[]) => void): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: () => void): void {
    this.onTouched = fn;
  }

  addChip(): void {
    if (!this.inputValue.trim()) {
      return;
    }

    if (this.type === 'number' && isNaN(Number(this.inputValue.trim()))) {
      return; // Invalid number, do not add
    }
    if (
      this.type === 'email' &&
      !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.inputValue.trim())
    ) {
      return; // Invalid email, do not add
    }
    this.chips.push(this.inputValue.trim());
    this.inputValue = '';
    this.onChange(this.chips);
  }
}
