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 { PointVente, PointVenteStatut } from 'src/app/core/interfaces/points-ventes';

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

  pointsVenteStatuts = [{
    label: 'Actif',
    value: 'ACTIF'
  },
  {
    label: 'Inactif',
    value: 'INACTIF'
  }
]

  private _value?: PointVente;
  @Input() set value(v: PointVente | undefined) {
    this._value = v;
    this.hydrate(v);
  }
  get value(): PointVente | undefined {
    return this._value;
  }

  form: FormGroup;
  submitted = false;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      nom: ['', Validators.required],
      adresse: ['', Validators.required],
      code: ['', Validators.required],
      ville: ['', Validators.required],
      latitude: [0, [Validators.required, Validators.min(-90), Validators.max(90)]],
      longitude: [0, [Validators.required, Validators.min(-180), Validators.max(180)]],
      statut: ['', Validators.required],
    });
  }

  error(control: string): string {
    const c = this.form.get(control);
    if (!c) return '';
    const invalid = c.invalid && (c.touched || this.submitted);
    if (!invalid) return '';
    const e = c.errors || {};
    if (e['required']) return 'Ce champ est obligatoire';
    if (e['min']) return `Valeur minimale: ${e['min'].min}`;
    if (e['max']) return `Valeur maximale: ${e['max'].max}`;
    return 'Valeur invalide';
  }

  private hydrate(v?: PointVente) {
    if (!v) {
      this.form.reset({
        nom: '',
        adresse: '',
        ville: '',
        latitude: 0,
        longitude: 0,
        statut: 'ACTIF',
      });
      this.submitted = false;
      return;
    }
    this.form.reset({
      nom: v.nom,
      adresse: v.adresse,
      ville: v.ville,
      latitude: v.latitude ?? 0,
      longitude: v.longitude ?? 0,
      statut: v.statut ?? 'ACTIF',
    });
    this.submitted = false;
  }

  onSubmit() {
    this.submitted = true;
    if (this.form.invalid) {
      this.form.markAllAsTouched();
      return;
    }
    const raw = this.form.getRawValue() as any;
    const payload: Partial<PointVente> = {
      ...raw,
      latitude: Number(raw.latitude),
      longitude: Number(raw.longitude),
      ...(this.value?.id ? { id: this.value.id } : {}),
    };
    this.save.emit(payload);
  }

  resetForm() {
    this._value = undefined;
    this.form.reset({
      nom: '',
      adresse: '',
      ville: '',
      latitude: 0,
      longitude: 0,
      statut: 'ACTIVE',
    });
    this.submitted = false;
  }
}
