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 { ZardButtonComponent } from '@shared/components/button/button.component';
import { Agent, AgentStatus } from 'src/app/core/interfaces/agent';
import { AgentLimit } from 'src/app/core/interfaces/agent-limit';
import { AgentLimitService } from 'src/app/core/services/agent-limit';

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

  limits: AgentLimit[] = [];

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

  form: FormGroup;
  submitted = false;

  constructor(private fb: FormBuilder, private limitService: AgentLimitService) {
    this.form = this.fb.group({
      code: ['', Validators.required],
      profile: ['', Validators.required],
      statut: ['ACTIF' as AgentStatus, Validators.required],
      zone: [''],
      kiosk: [''],
      fonction: [''],
      dateEmbauche: [''],

      nom: ['', Validators.required],
      prenom: ['', Validators.required],
      phone: ['', [Validators.required, Validators.minLength(6)]],

      limiteInferieure: [0, [Validators.min(0)]],
      limiteSuperieure: [0, [Validators.min(0)]],
      limiteParTransaction: [0, [Validators.min(0)]],
      limiteMinAirtime: [0, [Validators.min(0)]],
      limiteMaxAirtime: [0, [Validators.min(0)]],
      maxPeripheriques: [0, [Validators.min(0)]],

      limitId: ['', Validators.required],
    });

    this.limitService
      .list({ page: 1, perPage: 100, search: '', sortKey: 'nom', sortDir: 'asc' } as any)
      .subscribe((res) => (this.limits = res.content));
  }

  error(control: string): string {
    const e = this.form.get(control)?.errors; if (!e) return ''; if (e['required']) return 'Requis'; return '';
  }

  private hydrateFromValue(v?: Agent) {
    if (!v) {
      this.form.reset({
        code: '', profile: '', statut: 'ACTIF', zone: '', kiosk: '', fonction: '', dateEmbauche: '', nom: '', prenom: '', phone: '', limiteInferieure: 0, limiteSuperieure: 0, limiteParTransaction: 0, limiteMinAirtime: 0, limiteMaxAirtime: 0, maxPeripheriques: 0, limitId: '',
      });
      return;
    }
    this.form.reset({
      code: v.code, profile: v.profile, statut: v.statut, zone: v.zone ?? '', kiosk: v.kiosk ?? '', fonction: v.fonction ?? '', dateEmbauche: v.dateEmbauche ?? '', nom: v.nom, prenom: v.prenom, phone: v.phone, limiteInferieure: v.limiteInferieure ?? 0, limiteSuperieure: v.limiteSuperieure ?? 0, limiteParTransaction: v.limiteParTransaction ?? 0, limiteMinAirtime: v.limiteMinAirtime ?? 0, limiteMaxAirtime: v.limiteMaxAirtime ?? 0, maxPeripheriques: v.maxPeripheriques ?? 0, limitId: v.limitId ?? '',
    });
  }

  onSubmit() {
    this.submitted = true;
    if (this.form.invalid) { this.form.markAllAsTouched(); return; }
    const raw = this.form.getRawValue() as any;
    const payload: Agent = { id: this.value?.id ?? '', code: raw.code, profile: raw.profile, statut: raw.statut, zone: raw.zone, kiosk: raw.kiosk, fonction: raw.fonction, dateEmbauche: raw.dateEmbauche, nom: raw.nom, prenom: raw.prenom, phone: raw.phone, limiteInferieure: +raw.limiteInferieure, limiteSuperieure: +raw.limiteSuperieure, limiteParTransaction: +raw.limiteParTransaction, limiteMinAirtime: +raw.limiteMinAirtime, limiteMaxAirtime: +raw.limiteMaxAirtime, maxPeripheriques: +raw.maxPeripheriques, limitId: raw.limitId };
    this.save.emit(payload);
  }
}


