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';
import { ZardCheckboxComponent } from "@shared/components/checkbox/checkbox.component";

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

  limits: AgentLimit[] = [];

  profils = [
    {
    label: "Caissier",
    value: "CAISSIER"
  },
  {
    label: "Agent",
    value: "AGENT"
  },
  {
    label: "Superviseur",
    value: "SUPERVISEUR"
  },
]


 statutOptions = [
  {
    label: "Actif",
    value: "ACTIF"
  },
  {
    label: "Inactif",
    value: "INACTIF"
  }
 ]

  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],
      profil: ['CAISSIER', Validators.required],
      principalCode: ['', Validators.required],
      caisseProfile: ['', Validators.required],
      statut: ['ACTIF', Validators.required],
      zone: [''],
      kiosk: [''],
      fonction: [''],
      dateEmbauche: [''],
      nom: ['', Validators.required],
      prenom: ['', Validators.required],
      autresNoms: [''],
      dateNaissance: [''],
      lieuNaissance: [''],
      ville: [''],
      adresse: [''],
      autoriserAides: [false],

      phone: ['', Validators.required],
      pin: [''],

      limiteInferieure: [''],
      limiteSuperieure: [''],
      limiteParTransaction: [''],
      limiteMinAirtime: [''],
      limiteMaxAirtime: [''],

      maxPeripheriques: [''],

      limitId: ['1'],

      nationalite: [''],
      cni: [''],
      cniDelivreeLe: [''],
      cniDelivreeA: [''],
      residence: [''],
      autreAdresse1: [''],
      statutMarital: [''],
      epoux: [''],
      autreTelephone: [''],

    });

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

  errorMessage(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({
        statut: 'ACTIF',
        autoriserAides: false,
      });
      this.submitted = false;
      return;
    }
    console.log(v);
    this.form.reset({
      code: v.code || '',
      profil: v.profil || '',
      principalCode: v.principalCode || '',
      caisseProfile: v.caisseProfile || '',
      statut: v.statut || 'ACTIF',
      zone: v.zone || '',
      kiosk: v.kiosk || '',
      fonction: v.fonction || '',
      dateEmbauche: v.dateEmbauche || '',
  
      nom: v.nom || '',
      prenom: v.prenom || '',
      autresNoms: v.autresNoms || '',
      dateNaissance: v.dateNaissance || '',
      lieuNaissance: v.lieuNaissance || '',
      ville: v.ville || '',
      adresse: v.adresse || '',
      autoriserAides: v.autoriserAides ?? false,
  
      phone: v.phone || '',
      pin: v.pin || '',
  
      limiteInferieure: v.limiteInferieure || '',
      limiteSuperieure: v.limiteSuperieure || '',
      limiteParTransaction: v.limiteParTransaction || '',
      limiteMinAirtime: v.limiteMinAirtime || '',
      limiteMaxAirtime: v.limiteMaxAirtime || '',
  
      maxPeripheriques: v.maxPeripheriques || '',
  
      limitId: v.limitId || '',
  
      nationalite: v.nationalite || '',
      cni: v.cni || '',
      cniDelivreeLe: v.cniDelivreeLe || '',
      cniDelivreeA: v.cniDelivreeA || '',
      residence: v.residence || '',
      autreAdresse1: v.autreAdresse1 || '',
      statutMarital: v.statutMarital || '',
      epoux: v.epoux || '',
      autreTelephone: v.autreTelephone || '',
    });
  
    this.submitted = false;
  }

  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,
      profil: raw.profil,
      statut: raw.statut,
      principalCode: raw.principalCode || '',
      caisseProfile: raw.caisseProfile || '',
      zone: raw.zone || '',
      kiosk: raw.kiosk || '',
      fonction: raw.fonction || '',
      dateEmbauche: raw.dateEmbauche || '',
    
      nom: raw.nom,
      prenom: raw.prenom,
      autresNoms: raw.autresNoms || '',
      dateNaissance: raw.dateNaissance || '',
      lieuNaissance: raw.lieuNaissance || '',
      ville: raw.ville || '',
      adresse: raw.adresse || '',
      autoriserAides: raw.autoriserAides ?? false,
    
      phone: raw.phone,
      pin: raw.pin || '',
    
      limiteInferieure: +raw.limiteInferieure || 0,
      limiteSuperieure: +raw.limiteSuperieure || 0,
      limiteParTransaction: +raw.limiteParTransaction || 0,
      limiteMinAirtime: +raw.limiteMinAirtime || 0,
      limiteMaxAirtime: +raw.limiteMaxAirtime || 0,
    
      maxPeripheriques: +raw.maxPeripheriques || 0,
      limitId: raw.limitId || '1',
    
      // Légales
      nationalite: raw.nationalite || '',
      cni: raw.cni || '',
      cniDelivreeLe: raw.cniDelivreeLe || '',
      cniDelivreeA: raw.cniDelivreeA || '',
      residence: raw.residence || '',
      autreAdresse1: raw.autreAdresse1 || '',
      statutMarital: raw.statutMarital || '',
      epoux: raw.epoux || '',
      autreTelephone: raw.autreTelephone || ''
    };
    this.save.emit(payload);
  }

  onClose(){
    this.cancel.emit()
  }
}


