import { Component, Input, Output, EventEmitter, OnInit, forwardRef } from "@angular/core";
import { CommonModule } from "@angular/common";
import {
  ReactiveFormsModule,
  FormArray,
  FormBuilder,
  FormControl,
  ControlValueAccessor,
  NG_VALUE_ACCESSOR
} from "@angular/forms";

@Component({
  selector: "app-checkbox-list",
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
  templateUrl: "./checkbox-list.component.html",
  styleUrls: ["./checkbox-list.component.scss"],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CheckboxListComponent),
      multi: true
    }
  ]
})
export class CheckboxListComponent implements OnInit, ControlValueAccessor {
  @Input() items: { name: string; value: boolean }[] = [];
  checkboxes = new FormArray<FormControl<boolean>>([]);

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

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.initCheckboxes();
  }

  private initCheckboxes() {
    this.checkboxes.clear();
    this.items.forEach((item) => {
      const control = new FormControl(item.value, { nonNullable: true });
      this.checkboxes.push(control);
    });

    this.checkboxes.valueChanges.subscribe((values: boolean[]) => {
      const result = this.items.map((item, index) => ({
        name: item.name,
        value: values[index]
      }));
      this.onChange(result);
      this.onTouched();
    });
  }

  writeValue(value: { name: string; value: boolean }[]): void {
    if (value && Array.isArray(value)) {
      value.forEach((item, index) => {
        if (this.checkboxes.at(index)) {
          this.checkboxes.at(index).setValue(item.value, { emitEvent: false });
        }
      });
    }
  }

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

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

  setDisabledState?(isDisabled: boolean): void {
    if (isDisabled) {
      this.checkboxes.disable();
    } else {
      this.checkboxes.enable();
    }
  }
}