import { Component, inject, effect, signal, OnInit } from '@angular/core';
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { InputComponent } from '../../../../../../shared/components/input/input.component';
import { ButtonComponent } from '../../../../../../shared/components/button/button.component';
import { AuthService } from '../../../../../../core/services/auth/auth.service';
import { ToastService } from '../../../../../../core/services/toast.service';

@Component({
  selector: 'app-profile-form',
  standalone: true,
  imports: [ReactiveFormsModule, InputComponent, ButtonComponent],
  templateUrl: './profile-form.html',
  styleUrl: './profile-form.scss',
})
export class ProfileForm implements OnInit {
  profileForm: FormGroup;
  private authService = inject(AuthService);
  private toastService = inject(ToastService);
  isSubmitting = signal(false);

  constructor(private fb: FormBuilder) {
    this.profileForm = this.fb.group({
      fullName: ['', [Validators.required, Validators.maxLength(255)]],
      email: ['', [Validators.required, Validators.email, Validators.maxLength(255)]],
      dni: ['', [Validators.pattern(/^[0-9]{7,8}$/)]],
      phone: ['', [Validators.pattern(/^\+?[0-9\s\-]{10,20}$/)]],
      password: ['', [Validators.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_]).{8,}$/)]]
    });

    effect(() => {
      const user = this.authService.user();
      if (user) {
        this.profileForm.patchValue({
          fullName: user.nombre_apellido,
          email: user.email,
          dni: user.dni || '',
          phone: user.telefono || ''
        });
      }
    });
  }

  ngOnInit() {
    // Refresh user data directly from the API to ensure consistency
    this.authService.loadCurrentUser().subscribe();
  }

  getControlError(controlName: string): string | null {
    const control = this.profileForm.get(controlName);
    if (!control || !control.errors || (!control.touched && !this.isSubmitting())) return null;

    if (control.errors['required']) return 'Este campo es obligatorio.';
    if (control.errors['email']) return 'Ingresa un email válido.';
    if (control.errors['maxlength']) return 'Excede el largo máximo.';
    if (controlName === 'dni' && control.errors['pattern']) return 'DNI inválido (7-8 números).';
    if (controlName === 'phone' && control.errors['pattern']) return 'Teléfono inválido.';
    if (controlName === 'password' && control.errors['pattern']) return 'Debe contener mayúscula, minúscula, carácter especial y mínimo 8 caracteres.';
    
    return 'Valor inválido.';
  }

  onSubmit() {
    if (this.profileForm.invalid) {
      this.profileForm.markAllAsTouched();
      return;
    }
    
    this.isSubmitting.set(true);
    const formValue = this.profileForm.value;
    const payload: any = {
      nombre_apellido: formValue.fullName,
      email: formValue.email,
    };
    if (formValue.dni) payload.dni = formValue.dni;
    if (formValue.phone) payload.telefono = formValue.phone;
    if (formValue.password) payload.password = formValue.password;

    this.authService.updateProfile(payload).subscribe({
      next: () => {
        this.isSubmitting.set(false);
        this.toastService.success('Perfil actualizado correctamente.');
      },
      error: (error: any) => {
        this.isSubmitting.set(false);
        const errorMessage = error.error?.message || 'Error al actualizar el perfil.';
        this.toastService.danger(errorMessage);
      }
    });
  }

  onCancel() {
    const user = this.authService.user();
    if (user) {
      this.profileForm.reset({
        fullName: user.nombre_apellido,
        email: user.email,
        dni: user.dni || '',
        phone: user.telefono || '',
        password: ''
      });
    } else {
      this.profileForm.reset();
    }
  }
}
