import { Component, Inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MAT_DIALOG_DATA, MatDialogRef, MatDialogModule } from '@angular/material/dialog';
import { FormBuilder, FormGroup, FormArray, FormControl, ReactiveFormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';

@Component({
  selector: 'app-field-options-dialog',
  standalone: true,
  imports: [
    CommonModule,
    MatDialogModule,
    ReactiveFormsModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule,
    MatIconModule
  ],
  template: `
    <h2 mat-dialog-title>Editar Opciones</h2>
    <mat-dialog-content>
      <form [formGroup]="optionsForm">
        <div formArrayName="options">
          <div *ngFor="let option of options.controls; let i = index" class="option-row">
            <mat-form-field appearance="outline" class="flex-grow">
              <input matInput [formControlName]="i" placeholder="Opción {{ i + 1 }}">
            </mat-form-field>
            <button mat-icon-button color="warn" (click)="removeOption(i)">
              <mat-icon>delete</mat-icon>
            </button>
          </div>
        </div>
      </form>
      <button mat-button color="primary" (click)="addOption()">
        <mat-icon>add</mat-icon>
        Agregar Opción
      </button>
    </mat-dialog-content>
    <mat-dialog-actions align="end">
      <button mat-button (click)="onCancel()">Cancelar</button>
      <button mat-raised-button color="primary" (click)="onSave()">Guardar</button>
    </mat-dialog-actions>
  `,
  styles: [`
    .option-row {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 8px;
    }

    .flex-grow {
      flex: 1;
    }

    mat-dialog-content {
      max-height: 400px;
      overflow: auto;
    }
  `]
})
export class FieldOptionsDialogComponent {
  optionsForm: FormGroup;

  constructor(
    private fb: FormBuilder,
    private dialogRef: MatDialogRef<FieldOptionsDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: string[] = []
  ) {
    this.optionsForm = this.fb.group({
      options: this.fb.array([])
    });

    if (data?.length) {
      data.forEach(option => this.addOption(option));
    } else {
      this.addOption();
    }
  }

  get options(): FormArray {
    return this.optionsForm.get('options') as FormArray;
  }

  addOption(value: string = ''): void {
    this.options.push(new FormControl(value));
  }

  removeOption(index: number): void {
    this.options.removeAt(index);
  }

  onCancel(): void {
    this.dialogRef.close();
  }

  onSave(): void {
    if (this.optionsForm.valid) {
      this.dialogRef.close(this.options.value);
    }
  }
}
