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

// ========================================
// 🎯 INTERFACES PARA CHECKBOX AGRUPADO
// ========================================
export interface CheckboxGroupItem {
  id: string | number;
  name: string;
  value: boolean;
}

export interface CheckboxGroup {
  id: string;
  label: string;
  icon?: string;
  items: CheckboxGroupItem[];
  expanded?: boolean;
}

/**
 * 🎯 CheckboxGroupedComponent - Checkboxes Organizados por Grupos
 * 
 * Baseado no padrão do CheckboxListComponent com agrupamento visual.
 * 
 * ✨ Funcionalidades:
 * - Grupos colapsáveis/expansíveis
 * - Ícones para cada grupo
 * - Valor estruturado por grupo
 * - Compatível com FormControl (ControlValueAccessor)
 */
@Component({
  selector: "app-checkbox-grouped",
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
  templateUrl: "./checkbox-grouped.component.html",
  styleUrls: ["./checkbox-grouped.component.scss"],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CheckboxGroupedComponent),
      multi: true
    }
  ]
})
export class CheckboxGroupedComponent implements OnInit, ControlValueAccessor {
  @Input() groups: CheckboxGroup[] = [];
  @Input() hideLabel: boolean = false;
  
  // FormGroup contendo um FormGroup para cada grupo
  form = new FormGroup({});
  
  private onChange = (value: any) => {};
  private onTouched = () => {};

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.initFormGroups();
  }

  /**
   * 🎯 Inicializa FormGroups para cada grupo de checkboxes
   */
  private initFormGroups() {
    const formConfig: any = {};
    
    this.groups.forEach(group => {
      const groupFormConfig: any = {};
      
      group.items.forEach(item => {
        groupFormConfig[item.id] = new FormControl(item.value, { nonNullable: true });
      });
      
      formConfig[group.id] = this.fb.group(groupFormConfig);
    });
    
    this.form = this.fb.group(formConfig);
    
    // Observar mudanças e emitir valores
    this.form.valueChanges.subscribe(value => {
      this.onChange(value);
      this.onTouched();
    });
  }

  /**
   * 🎯 Alternar expansão/colapso de um grupo
   */
  toggleGroup(group: CheckboxGroup) {
    group.expanded = !group.expanded;
  }

  /**
   * 🎯 Obter FormGroup de um grupo específico
   */
  getGroupFormGroup(groupId: string): FormGroup {
    return this.form.get(groupId) as FormGroup;
  }

  /**
   * 🎯 Obter FormControl de um item específico
   */
  getItemFormControl(groupId: string, itemId: string | number): FormControl {
    return this.getGroupFormGroup(groupId).get(itemId.toString()) as FormControl;
  }

  // ========================================
  // 🔧 IMPLEMENTAÇÃO ControlValueAccessor
  // ========================================
  
  writeValue(value: any): void {
    if (value && typeof value === 'object') {
      Object.keys(value).forEach(groupId => {
        const groupValue = value[groupId];
        if (groupValue && typeof groupValue === 'object') {
          Object.keys(groupValue).forEach(itemId => {
            const control = this.getItemFormControl(groupId, itemId);
            if (control) {
              control.setValue(groupValue[itemId], { emitEvent: false });
            }
          });
        }
      });
    }
  }

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

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

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