import { CommonModule } from '@angular/common';
import {
  ChangeDetectionStrategy,
  Component,
  effect,
  input,
  OnDestroy,
  output,
  signal,
} from '@angular/core';
import {
  FormBuilder,
  ReactiveFormsModule,
  Validators,
  FormGroup,
  FormControl,
} from '@angular/forms';
import { Subscription } from 'rxjs';
import { Hippodrome } from 'src/app/core/interfaces/hippodrome';

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

@Component({
  selector: 'app-hippodrome-form',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    ZardFormModule,
    ZardInputDirective,
    ZardSelectComponent,
    ZardSelectItemComponent,
    ZardButtonComponent,
  ],
  templateUrl: './hippodrome-form.html',
  styleUrls: ['./hippodrome-form.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class HippodromeForm implements OnDestroy {
  // Inputs
  value = input<Partial<Hippodrome> | null>(null);
  showInternalActions = input<boolean>(false);

  // Outputs
  save = output<Partial<Hippodrome>>();
  cancel = output<void>();

  submitting = signal(false);
  initializing = signal(false);
  submitted = signal(false);
  paysInteracted = signal(false);

  form!: FormGroup;
  private subs = new Subscription();

  countries = [
    { value: 'France', label: 'France' },
    { value: 'Mali', label: 'Mali' },
    { value: 'Sénégal', label: 'Sénégal' },
    { value: 'Maroc', label: 'Maroc' },
    { value: 'Tunisie', label: 'Tunisie' },
    { value: 'Algérie', label: 'Algérie' },
    { value: 'Côte d’Ivoire', label: 'Côte d’Ivoire' },
    { value: 'Belgique', label: 'Belgique' },
    { value: 'Suisse', label: 'Suisse' },
    { value: 'Canada', label: 'Canada' },
    { value: 'Mauritanie', label: 'Mauritanie' },
  ];

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      nom: ['', Validators.required],
      ville: ['', Validators.required],
      pays: new FormControl<string | null>(null, { validators: [Validators.required] }),
      capacite: new FormControl<number | null>(null, {
        validators: [Validators.min(1)],
      }),
      actif: new FormControl<boolean>(true),
      description: new FormControl<string | null>(null),
    });

    // Auto-update form when editing
    effect(
      () => {
        const v = this.value();
        this.initializing.set(true);

        this.form.reset(
          { nom: '', ville: '', pays: null, capacite: null, actif: true, description: null },
          { emitEvent: false }
        );

        if (v)
          this.form.patchValue(
            {
              nom: v.nom ?? '',
              ville: v.ville ?? '',
              pays: v.pays ?? null,
              capacite: v.capacite ?? null,
              actif: v.actif ?? true,
              description: v.description ?? null,
            },
            { emitEvent: false }
          );

        this.form.markAsPristine();
        this.form.markAsUntouched();
        this.paysInteracted.set(false);
        queueMicrotask(() => this.initializing.set(false));
      },
      { allowSignalWrites: true }
    );

    const pays = this.form.get('pays')!;
    this.subs.add(pays.valueChanges.subscribe(() => this.paysInteracted.set(true)));
  }

  invalid(name: keyof Hippodrome) {
    const c = this.form.get(name as string);
    return !!((this.submitted() || c?.touched || c?.dirty) && c?.invalid);
  }

  showPaysError(): boolean {
    const c = this.form.get('pays');
    if (!c || this.initializing()) return false;
    return (this.submitted() || this.paysInteracted()) && c.hasError('required');
  }

  onSubmit() {
    this.submitted.set(true);
    if (this.form.invalid) {
      this.form.markAllAsTouched();
      return;
    }
    this.submitting.set(true);
    this.save.emit(this.form.value as Partial<Hippodrome>);

    // Reset form state after emitting (parent will handle actual form reset via value input)
    // But reset submitting state so button is enabled again
    this.submitting.set(false);
    this.submitted.set(false);
  }

  ngOnDestroy() {
    this.subs.unsubscribe();
  }
}
