import {
  Component,
  Input,
  forwardRef,
  OnInit,
  ElementRef,
  ViewChild,
  AfterViewInit,
} from "@angular/core";
import {
  ControlValueAccessor,
  NG_VALUE_ACCESSOR,
  FormsModule,
  ReactiveFormsModule,
} from "@angular/forms";
import { CommonModule } from "@angular/common";

@Component({
  selector: "app-textarea-input",
  standalone: true,
  templateUrl: "./textarea-input.component.html",
  styleUrls: ["./textarea-input.component.scss"],
  imports: [CommonModule, FormsModule, ReactiveFormsModule],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => TextareaInputComponent),
      multi: true,
    },
  ],
})
export class TextareaInputComponent implements ControlValueAccessor, OnInit, AfterViewInit {
  @Input() field!: {
    key: string;
    label: string;
    placeholder?: string;
    disabled?: boolean;
    readOnly?: boolean;
    required?: boolean;
    maxLength?: number;
    minLength?: number;
    rows?: number;
    autoResize?: boolean;
    showCharCounter?: boolean;
    resizable?: boolean;
  };

  @ViewChild('textareaElement', { static: false }) textareaElement!: ElementRef<HTMLTextAreaElement>;

  value: string = "";
  disabled = false;
  isFocused = false;
  
  // Configurações padrão
  private defaultRows = 4;
  private defaultMaxLength = 1000;

  private onChange: any = () => {};
  private onTouched: any = () => {};

  ngOnInit() {
    // Configurar valores padrão se não fornecidos
    if (!this.field.rows) {
      this.field.rows = this.defaultRows;
    }
    if (!this.field.maxLength) {
      this.field.maxLength = this.defaultMaxLength;
    }
    if (this.field.autoResize === undefined) {
      this.field.autoResize = true;
    }
    if (this.field.showCharCounter === undefined) {
      this.field.showCharCounter = true;
    }
    if (this.field.resizable === undefined) {
      this.field.resizable = true;
    }
  }

  ngAfterViewInit() {
    // Configurar auto-resize se habilitado
    if (this.field.autoResize && this.textareaElement) {
      this.adjustHeight();
    }
  }

  // Getter para verificar se há valor
  get hasValue(): boolean {
    return this.value !== null && this.value !== undefined && this.value.trim() !== "";
  }

  // Getter para contagem de caracteres
  get characterCount(): number {
    return this.value ? this.value.length : 0;
  }

  // Getter para caracteres restantes
  get charactersRemaining(): number {
    const maxLength = this.field.maxLength || this.defaultMaxLength;
    return maxLength - this.characterCount;
  }

  // Getter para verificar se está próximo do limite
  get isNearLimit(): boolean {
    const maxLength = this.field.maxLength || this.defaultMaxLength;
    return this.characterCount > (maxLength * 0.8); // 80% do limite
  }

  // Getter para verificar se excedeu o limite
  get isOverLimit(): boolean {
    const maxLength = this.field.maxLength || this.defaultMaxLength;
    return this.characterCount > maxLength;
  }

  // Métodos do ControlValueAccessor
  writeValue(value: any): void {
    this.value = value || "";
    
    // Ajustar altura após definir valor
    setTimeout(() => {
      if (this.field.autoResize && this.textareaElement) {
        this.adjustHeight();
      }
    });
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

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

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

  // Eventos do textarea
  onInput(event: Event): void {
    const target = event.target as HTMLTextAreaElement;
    this.value = target.value;
    
    // Validação de comprimento máximo
    if (this.field.maxLength && this.value.length > this.field.maxLength) {
      this.value = this.value.substring(0, this.field.maxLength);
      target.value = this.value;
    }
    
    // Auto-resize
    if (this.field.autoResize) {
      this.adjustHeight();
    }
    
    this.onChange(this.value);
  }

  onFocus(): void {
    this.isFocused = true;
  }

  onBlur(): void {
    this.isFocused = false;
    this.onTouched();
  }

  // Método para ajustar altura automaticamente
  private adjustHeight(): void {
    if (!this.textareaElement) return;
    
    const textarea = this.textareaElement.nativeElement;
    
    // Reset height to auto to get the correct scrollHeight
    textarea.style.height = 'auto';
    
    // Calculate the height based on content
    const scrollHeight = textarea.scrollHeight;
    const minHeight = this.field.rows! * 24; // Aproximadamente 24px por linha
    const maxHeight = Math.max(minHeight * 3, 200); // Máximo 3x o tamanho inicial ou 200px
    
    // Set the height with constraints
    const newHeight = Math.min(Math.max(scrollHeight, minHeight), maxHeight);
    textarea.style.height = `${newHeight}px`;
    
    // Enable/disable scrollbar based on content
    textarea.style.overflowY = scrollHeight > maxHeight ? 'auto' : 'hidden';
  }

  // Método para limpar conteúdo
  clearContent(): void {
    this.value = "";
    this.onChange(this.value);
    
    if (this.field.autoResize && this.textareaElement) {
      this.adjustHeight();
    }
    
    // Focar no textarea após limpar
    if (this.textareaElement) {
      this.textareaElement.nativeElement.focus();
    }
  }

  // Método para obter texto formatado (útil para exibição)
  getFormattedText(): string {
    return this.value || "";
  }

  // Método para verificar se o texto está válido
  isValid(): boolean {
    if (this.field.required && !this.hasValue) {
      return false;
    }
    
    if (this.field.minLength && this.characterCount < this.field.minLength) {
      return false;
    }
    
    if (this.field.maxLength && this.characterCount > this.field.maxLength) {
      return false;
    }
    
    return true;
  }

  // Método para obter mensagem de erro
  getErrorMessage(): string {
    if (this.field.required && !this.hasValue) {
      return 'Este campo é obrigatório';
    }
    
    if (this.field.minLength && this.characterCount < this.field.minLength) {
      return `Mínimo ${this.field.minLength} caracteres (${this.characterCount}/${this.field.minLength})`;
    }
    
    if (this.field.maxLength && this.characterCount > this.field.maxLength) {
      return `Máximo ${this.field.maxLength} caracteres (${this.characterCount}/${this.field.maxLength})`;
    }
    
    return '';
  }
} 