import { Component, OnInit, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { ToastrService } from 'ngx-toastr';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { ConfigService } from '@services/config.service';

@Component({
  selector: 'app-create-command-group',
  templateUrl: './create-command-group.component.html',
  styleUrls: ['./create-command-group.component.css']
})
export class CreateCommandGroupComponent implements OnInit {
  baseUrl: string;
  availableCommands: any[] = [];
  selectedCommands: any[] = [];
  groupName: string = '';
  enabled: boolean = true;
  editing: boolean = false;
  loading: boolean = false;
  private apiUrl: string;

  constructor(
    private http: HttpClient,
    private dialogRef: MatDialogRef<CreateCommandGroupComponent>,
    private toastService: ToastrService,
    private configService: ConfigService,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    this.baseUrl = this.configService.apiUrl;
    this.apiUrl = `${this.baseUrl}/commands`;
  }

  ngOnInit(): void {
    this.loadAvailableCommands();

    if (this.data && this.data.group) {
      this.editing = true;
      this.loadGroupData(this.data.group);
    }
  }

  loadAvailableCommands(): void {
    this.loading = true;
    this.http.get<any>(this.apiUrl).subscribe(
      (data) => {
        this.availableCommands = data['hydra:member'];
        this.loading = false;
      },
      (error) => {
        console.error('Error fetching available commands', error);
        this.loading = false;
      }
    );
  }

  loadGroupData(group: any): void {
    this.groupName = group.name;
    this.enabled = group.enabled;
    this.selectedCommands = group.commands;
  }

  addCommand(command: any): void {
    if (!this.selectedCommands.includes(command)) {
      this.selectedCommands.push(command);
    }
  }

  removeCommand(command: any): void {
    const index = this.selectedCommands.indexOf(command);
    if (index >= 0) {
      this.selectedCommands.splice(index, 1);
    }
  }

  drop(event: CdkDragDrop<any[]>): void {
    moveItemInArray(this.selectedCommands, event.previousIndex, event.currentIndex);
  }

  onSubmit(): void {
    const payload = {
      name: this.groupName,
      commands: this.selectedCommands.map(cmd => cmd['@id']),
      enabled: this.enabled
    };

    if (this.editing) {
      const groupId = this.data.group.uuid;
      this.http.patch(`${this.baseUrl}/command-groups/${groupId}`, payload).subscribe({
        next: () => {
          this.toastService.success('Grupo de comandos actualizado con éxito');
          this.dialogRef.close();
        },
        error: (error) => {
          console.error('Error actualizando el grupo de comandos', error);
          this.toastService.error('Error al actualizar el grupo de comandos');
        }
      });
    } else {
      this.http.post(`${this.baseUrl}/command-groups`, payload).subscribe({
        next: () => {
          this.toastService.success('Grupo de comandos creado con éxito');
          this.dialogRef.close();
        },
        error: (error) => {
          console.error('Error creando el grupo de comandos', error);
          this.toastService.error('Error al crear el grupo de comandos');
        }
      });
    }
  }

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