import { CommonModule } from '@angular/common';
import { ChangeDetectionStrategy, Component, effect, EventEmitter, Input, Output, signal } 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, TpeType } from 'src/app/core/interfaces/tpe';
import { PointsVenteService } from 'src/app/core/services/points-vente';
import { ListParams } from '@shared/paging/paging';
import { PointVente } from 'src/app/core/interfaces/points-ventes';

@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;


  pointDeVenteText = signal('');

  pointDeVenteLoading = signal<boolean>(false);


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

  osList = ['Windows', 'Linux', 'Mac Os'];

  pointsDevente:PointVente[] = [];


  statuts = [
    {
      label: 'Actif',
      value: 'ACTIF'
    },
    {
      label: 'Hors service',
      value: 'HORS_SERVICE'
    }
  ]

  form: FormGroup;
  submitted = false;

  constructor(private fb: FormBuilder, private pointsVenteService: PointsVenteService) {
    this.form = this.fb.group({
      numeroSerie: ['', [Validators.required, Validators.minLength(10)]],
      pointDeVenteId: ['', Validators.required],
      statut: ['', Validators.required],
      versionLogicielle: ['', Validators.required],
      typeTerminal: ['', Validators.required],
      plateforme: ['', Validators.required],
      modeleAppareil: ['', Validators.required],
      systemeExploitation: ['', Validators.required],
      versionOs: ['', Validators.required],
      adresseIp: ['', Validators.required],
      adresseMac: ['', Validators.required],
      agentConnecteId: ['1'],
      journalSession: ['1'],
    });
  }

  
  

  pointDeVenteTextChange =(event: Event)=>{
    const value = (event.target as HTMLInputElement).value;
    this.pointDeVenteText.set(value);
    const text = this.pointDeVenteText();
      const params: ListParams = {
        page: 0,
        size: 10,
        search: text
      }
      this.getPointDeventeFromText(text, params);
  }

  getPointDeventeFromText=(text: string, params: ListParams)=>{
    if(text.length < 2) return;
    this.pointDeVenteLoading.set(true);
    this.pointsVenteService.list(params).subscribe({
      next: res =>{
        this.pointsDevente = res.content;
        this.pointDeVenteLoading.set(false);
      },
      error: err =>{
        this.pointDeVenteLoading.set(false);
        return console.error(err);
      }
    })
  }


  selectPointDeVente =(pvt:PointVente):void=>{
    this.form.patchValue({
      pointDeVenteId: pvt.id
    })
    this.pointsDevente = [];
    this.pointDeVenteText.set(`${pvt.nom}/${pvt.code} `)
  }

  onClose(){
    this.pointsDevente = [];
  }


  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({
        numeroSerie: '',
        pointDeVenteId: 0,
        statut: 'ACTIF',
        versionLogicielle: '',
        typeTerminal: '',
        plateforme: '',
        modeleAppareil: '',
        systemeExploitation: '',
        versionOs: '',
        adresseIp: '',
        adresseMac: '',
        agentConnecteId: '',
        journalSession: '',
      });
      this.submitted = false; // Reset submitted flag when form is cleared
      return;
    }
    this.form.reset({
      numeroSerie: v.numeroSerie,
      pointDeVenteId: v.pointDeVenteId,
      statut: 'ACTIF',
      versionLogicielle: v.versionLogicielle,
      typeTerminal: v.typeTerminal,
      plateforme: v.plateforme,
      modeleAppareil: v.modeleAppareil,
      systemeExploitation: v.systemeExploitation,
      versionOs: v.versionOs,
      adresseIp: v.adresseIp,
      adresseMac: v.adresseMac,
      agentConnecteId: v.agentConnecteId,
      journalSession: v.journalSession,
    });
  }

  onSubmit() {
    this.submitted = true;
    if (this.form.invalid) {
      this.form.markAllAsTouched();
      return;
    }
    const raw = this.form.getRawValue() as Partial<TpeDevice>;
    const payload: Partial<TpeDevice> = {
      ...raw
    };
    // 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({
      numeroSerie: '',
      pointDeVenteId: 0,
      statut: 'ACTIF',
      versionLogicielle: '',
      typeTerminal: '',
      plateforme: '',
      modeleAppareil: '',
      systemeExploitation: '',
      versionOs: '',
      adresseIp: '',
      adresseMac: '',
      agentConnecteId: '',
      journalSession: '',
    });
    this.submitted = false;
    this._skipHydration = false; // Re-enable hydration
  }

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