import { Component, Input, Output, EventEmitter, forwardRef, OnInit } from '@angular/core';

import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'ccl-textarea',
  standalone: true,
  imports: [],
  templateUrl: './textarea.html',
  styleUrls: ['./textarea.css'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => TextareaComponent),
      multi: true
    }
  ]
})
export class TextareaComponent implements ControlValueAccessor, OnInit {
  @Input() value = '';
  @Input() placeholder = '';
  @Input() disabled = false;
  @Input() readonly = false;
  @Input() error = false;
  @Input() errorMessage = '';
  @Input() helperText = '';
  @Input() rows = 4;
  @Input() cols?: number;
  @Input() maxLength?: number;
  @Input() minLength?: number;
  @Input() resize: 'none' | 'both' | 'horizontal' | 'vertical' = 'vertical';

  @Output() valueChange = new EventEmitter<string>();

  id = 'ccl-textarea-' + Math.random().toString(36).substring(2, 9);

  // ControlValueAccessor implementation
  private onChange = (value: string) => {};
  private onTouched = () => {};

  ngOnInit(): void {
    // Initialize component - ensure value is set
    if (this.value) {
      // Value is already set via @Input() value
    }
  }

  writeValue(value: string): void {
    this.value = value || '';
  }

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

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

  setDisabledState(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }

  onInput(event: Event): void {
    const target = event.target as HTMLTextAreaElement;
    this.value = target.value;
    this.onChange(this.value);
    this.valueChange.emit(this.value);
    this.onTouched();
  }
}


