import { CommonModule } from '@angular/common';
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { ZardFormModule } from '@shared/components/form/form.module';
import { ZardInputDirective } from '@shared/components/input/input.directive';
import { ZardSelectComponent } from '@shared/components/select/select.component';
import { ZardSelectItemComponent } from '@shared/components/select/select-item.component';
import { TpeDevice, TpeStatus, TpeType } from 'src/app/core/interfaces/tpe';

@Component({
  selector: 'app-tpe-form',
  standalone: true,
  templateUrl: './tpe-form.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    ZardFormModule,
    ZardInputDirective,
    ZardSelectComponent,
    ZardSelectItemComponent,
  ],
})
export class TpeForm {
  @Output() save = new EventEmitter<TpeDevice>();
  @Output() cancel = new EventEmitter<void>();

  private _value?: TpeDevice;
  private _skipHydration = false;
  @Input() set value(v: TpeDevice | undefined) {
    this._value = v;
    if (!this._skipHydration) {
      this.hydrateFromValue(v);
    }
  }
  get value(): TpeDevice | undefined {
    return this._value;
  }

  form: FormGroup;
  submitted = false;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      imei: ['', [Validators.required, Validators.minLength(10)]],
      serial: ['', Validators.required],
      type: ['POS' as TpeType, Validators.required],
      marque: ['', Validators.required],
      modele: ['', Validators.required],
      statut: ['VALIDE' as TpeStatus, Validators.required],
      assigne: [false],
    });
  }

  isInvalid(control: string): boolean {
    const c = this.form.get(control);
    return !!(c && c.invalid && (c.touched || this.submitted));
  }
  errorMessage(control: string): string {
    const e = this.form.get(control)?.errors;
    if (!e) return '';
    if (e['required']) return 'Ce champ est obligatoire';
    if (e['minlength']) return `Minimum ${e['minlength'].requiredLength} caractères`;
    return '';
  }

  private hydrateFromValue(v?: TpeDevice) {
    if (!v) {
      this.form.reset({
        imei: '',
        serial: '',
        type: 'POS',
        statut: 'VALIDE',
        assigne: false,
        marque: '',
        modele: '',
      });
      this.submitted = false; // Reset submitted flag when form is cleared
      return;
    }
    this.form.reset({
      imei: v.imei,
      serial: v.serial,
      type: v.type,
      statut: v.statut,
      assigne: !!v.assigne,
      marque: v.marque,
      modele: v.modele,
    });
  }

  onSubmit() {
    this.submitted = true;
    if (this.form.invalid) {
      this.form.markAllAsTouched();
      return;
    }
    const raw = this.form.getRawValue() as any;
    const payload: Partial<TpeDevice> = {
      imei: raw.imei,
      serial: raw.serial,
      type: raw.type,
      statut: raw.statut,
      assigne: !!raw.assigne,
      marque: raw.marque,
      modele: raw.modele,
    };
    // Preserve existing id, statut, and assigne if editing
    if (this.value?.id) {
      payload.id = this.value.id;
    }
    this.save.emit(payload as TpeDevice);
  }

  resetForm() {
    this._skipHydration = true; // Prevent hydration when clearing value
    this._value = undefined;
    this.form.reset({
      imei: '',
      serial: '',
      type: 'POS',
      marque: '',
      modele: '',
    });
    this.submitted = false;
    this._skipHydration = false; // Re-enable hydration
  }

  types = [
    { label: 'POS', value: 'POS' as TpeType },
    { label: 'Autre', value: 'OTHER' as TpeType },
  ];

  allStatuses: TpeStatus[] = [
    'VALIDE',
    'INVALIDE',
    'EN_PANNE',
    'BLOQUE',
    'DISPONIBLE',
    'AFFECTE',
    'EN_MAINTENANCE',
    'HORS_SERVICE',
    'VOLE',
  ];
}
