import { Component, Inject, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { CreateCommandComponent } from '../create-command/create-command.component';
import { HttpClient } from '@angular/common/http';
import { ToastrService } from 'ngx-toastr';
import { ConfigService } from '@services/config.service';

@Component({
  selector: 'app-command-detail',
  templateUrl: './command-detail.component.html',
  styleUrls: ['./command-detail.component.css']
})
export class CommandDetailComponent implements OnInit {
  baseUrl: string;
  form!: FormGroup;
  clients: any[] = [];
  showClientSelect = false;
  showDatePicker = false;
  canExecute = false;

  constructor(
    private fb: FormBuilder,
    private configService: ConfigService,
    private http: HttpClient,
    public dialogRef: MatDialogRef<CommandDetailComponent>,
    private dialog: MatDialog,
    private toastService: ToastrService,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    this.baseUrl = this.configService.apiUrl;
  }

  ngOnInit(): void {
    this.form = this.fb.group({
      selectedClients: [[this.data.importedClients], Validators.required],
      scheduleExecution: [false],
      scheduleDate: [''],
      scheduleTime: ['']
    });

    this.http.get<any>(`${this.baseUrl}/clients?page=1&itemsPerPage=30`).subscribe(response => {
      this.clients = response['hydra:member'];
    });
  }

  onClientSelectionChange(event: any): void {
    this.canExecute = this.form.get('selectedClients')?.value.length > 0;
  }

  edit(): void {
    const dialogRef = this.dialog.open(CreateCommandComponent, {
      width: '600px',
      data: { command: this.data.command }
    });

    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        this.toastService.success('Comando editado');
        this.data.command = result;
      }
    });
  }

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