import { Component, EventEmitter, Input, Output } from '@angular/core';
import { Subject, debounceTime, distinctUntilChanged } from 'rxjs';

@Component({
  selector: 'app-textarea',
  templateUrl: './textarea.component.html',
  styleUrls: ['./textarea.component.scss'],
})
export class TextareaComponent {
  @Input() value = '';
  @Input() placeholder?: string = '';
  @Input() errorMessage?: string = '';
  @Input() label?: string = '';
  @Input() identifier = '';
  @Input() maxLength?: number;
  @Input() isDisabled = false;
  @Input() regex?: RegExp;
  @Input() debounceTimer = 300;

  @Output() valueChange = new EventEmitter<string>();
  @Output() onError = new EventEmitter<string>();
  @Output() onValidityChange = new EventEmitter<boolean>();
  @Output() onDebounce = new EventEmitter<string>();

  debouncedValue = new Subject<string>();

  isValid = true;

  ngOnInit() {
    this.debouncedValue
      .pipe(debounceTime(this.debounceTimer), distinctUntilChanged())
      .subscribe((value) => {
        this.onDebounce.emit(value);
      });
  }

  onChanges(event: Event) {
    const input = event.target as HTMLInputElement;
    const newValue: string = input.value;

    if (this?.maxLength && newValue.length > this.maxLength) {
      input.value = this.value;
      return;
    }

    this.value = newValue;
    this.checkInputPattern();

    this.debouncedValue.next(newValue.trim());
    this.valueChange.emit(newValue);
  }

  checkInputPattern() {
    if (!this.regex) return;

    this.isValid = this.regex.test(this.value);
    this.onValidityChange.emit(this.isValid);

    if (!this.isValid) {
      this.onError.emit('Por favor, insira um valor válido.');
    }
  }
}
