import {
  Component,
  Input,
  forwardRef,
  ViewChild,
  AfterViewInit,
} from "@angular/core";
import { CommonModule } from "@angular/common";
import {
  ControlValueAccessor,
  NG_VALUE_ACCESSOR,
  FormsModule,
  ReactiveFormsModule,
} from "@angular/forms";
import { NgxMaskDirective, provideNgxMask } from "ngx-mask";

@Component({
  selector: "app-custom-input",
  standalone: true,
  templateUrl: "./custom-input.component.html",
  styleUrls: ["./custom-input.component.scss"],
  imports: [CommonModule, NgxMaskDirective, FormsModule, ReactiveFormsModule],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CustomInputComponent),
      multi: true,
    },
    provideNgxMask(),
  ],
})
export class CustomInputComponent
  implements ControlValueAccessor, AfterViewInit
{
  @Input() field!: {
    key: string;
    type: string;
    label: string;
    placeholder?: string;
    mask?: string;
    readOnly?: boolean;
    required?: boolean;
  };

  @ViewChild(NgxMaskDirective) maskDirective?: NgxMaskDirective;

  value: any = "";
  disabled = false;

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

  ngAfterViewInit() {
    if (this.value && this.maskDirective) {
      this.maskDirective.writeValue(this.value);
    }
  }

  writeValue(value: any): void {
    if (this.field?.type === "date" && value) {
      const parsed = new Date(value);
      if (!isNaN(parsed.getTime())) {
        this.value = parsed.toISOString().substring(0, 10); // transforma em 'YYYY-MM-DD'
      } else {
        this.value = value || "";
      }
    } else {
      this.value = value || "";
    }

    if (this.maskDirective) {
      this.maskDirective.writeValue(this.value);
    }
  }


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

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

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

  onInput(event: Event): void {
    const target = event.target as HTMLInputElement;
    const value = target.value;
    this.value = value;
    this.onChange(value);
  }

  onBlur(): void {
    this.onTouched();
  }

  onKeyPress(event: KeyboardEvent): void {
    if (this.field.type === "number" && !/[0-9]/.test(event.key)) {
      event.preventDefault();
    }
  }
}
