import { Component, Inject, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, ValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { ShiftDefinition } from '../../services/shift-definition.service'; // Importa l'interfaccia

// Validatore custom per assicurare che end_time sia dopo start_time
export const timeRangeValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
  const start = control.get('start_time');
  const end = control.get('end_time');

  // Confronta solo se entrambi i valori sono presenti e sembrano orari validi (HH:MM o HH:MM:SS)
  const timeRegex = /^\d{2}:\d{2}(:\d{2})?$/;
  if (start?.value && end?.value && timeRegex.test(start.value) && timeRegex.test(end.value)) {
    // Confronto semplice delle stringhe funziona per HH:MM o HH:MM:SS
    return start.value < end.value ? null : { timeRange: true }; // Errore se start >= end
  }
  return null;
};


@Component({
  selector: 'app-shift-definition-dialog',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    MatDialogModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule
  ],
  templateUrl: './shift-definition-dialog.component.html',
  styleUrl: './shift-definition-dialog.component.scss'
})
export class ShiftDefinitionDialogComponent implements OnInit {
  shiftForm: FormGroup;
  isEditMode: boolean;
  title: string;

  constructor(
    public dialogRef: MatDialogRef<ShiftDefinitionDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: { shift?: ShiftDefinition },
    private fb: FormBuilder
  ) {
    this.isEditMode = !!data?.shift;
    this.title = this.isEditMode ? 'Modifica Definizione Turno' : 'Aggiungi Nuova Definizione Turno';

    // Validatore per formato HH:MM o HH:MM:SS
    const timePattern = Validators.pattern(/^([01]\d|2[0-3]):([0-5]\d)(:([0-5]\d))?$/);

    this.shiftForm = this.fb.group({
      name: ['', Validators.required],
      start_time: ['', [Validators.required, timePattern]],
      end_time: ['', [Validators.required, timePattern]],
      notes: ['']
    }, { validators: timeRangeValidator }); // Applica validatore custom al gruppo
  }

  ngOnInit(): void {
    if (this.isEditMode && this.data.shift) {
      this.shiftForm.patchValue(this.data.shift);
    }
  }

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

  onSave(): void {
    if (this.shiftForm.valid) {
      this.dialogRef.close(this.shiftForm.value);
    } else {
       console.log('Shift Form Invalid:', this.shiftForm.errors);
       Object.keys(this.shiftForm.controls).forEach(key => {
         const control = this.shiftForm.get(key);
         if (control && control.errors) {
           console.log(`Control Error - ${key}:`, control.errors);
         }
       });
      this.shiftForm.markAllAsTouched();
    }
  }
}
