import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpErrorResponse } from '@angular/common/http';
import {
  AbstractControl,
  FormBuilder,
  FormGroup,
  ReactiveFormsModule,
  ValidationErrors,
  Validators
} from '@angular/forms';

import { ProfileService } from '../../services/profile.service';
import { AuthService } from '../../services/auth.service';

@Component({
  selector: 'app-perfil',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
  templateUrl: './perfil.html',
  styleUrls: ['./perfil.scss'],
})
export class Perfil implements OnInit {
  profileForm: FormGroup;
  passwordForm: FormGroup;

  loadingProfile = false;
  savingProfile = false;
  savingPassword = false;

  profileSuccess = '';
  profileError = '';
  passwordSuccess = '';
  passwordError = '';

  constructor(
    private fb: FormBuilder,
    private profileService: ProfileService,
    private authService: AuthService
  ) {
    this.profileForm = this.fb.group({
      nome: ['', [Validators.required, Validators.minLength(2)]],
      email: ['', [Validators.required, Validators.email]],
    });

    this.passwordForm = this.fb.group(
      {
        credencialAtual: ['', [Validators.required]],
        novaCredencial: ['', [Validators.required, Validators.minLength(8)]],
        confirmarNovaCredencial: ['', [Validators.required]],
      },
      { validators: this.passwordsMatchValidator }
    );
  }

  ngOnInit(): void {
    this.loadProfile();
  }

  onSaveProfile(): void {
    if (this.savingProfile) return;
    this.profileSuccess = '';
    this.profileError = '';

    if (this.profileForm.invalid) {
      this.profileForm.markAllAsTouched();
      return;
    }

    this.savingProfile = true;
    this.setProfileFormDisabled(true);
    const payload = {
      nome: String(this.profileForm.get('nome')?.value ?? '').trim(),
      email: String(this.profileForm.get('email')?.value ?? '').trim(),
    };

    this.profileService.updateProfile(payload).subscribe({
      next: (updated) => {
        this.savingProfile = false;
        this.setProfileFormDisabled(false);
        this.profileSuccess = 'Perfil atualizado com sucesso.';
        this.profileForm.patchValue({
          nome: updated.nome ?? '',
          email: updated.email ?? '',
        });
        this.profileForm.markAsPristine();
        this.authService.updateUserProfile({
          nome: updated.nome ?? '',
          email: updated.email ?? '',
        });
      },
      error: (err: HttpErrorResponse) => {
        this.savingProfile = false;
        this.setProfileFormDisabled(false);
        this.profileError = this.extractErrorMessage(err, 'Não foi possível atualizar o perfil.');
      },
    });
  }

  onChangePassword(): void {
    if (this.savingPassword) return;
    this.passwordSuccess = '';
    this.passwordError = '';

    if (this.passwordForm.invalid) {
      this.passwordForm.markAllAsTouched();
      return;
    }

    this.savingPassword = true;
    this.setPasswordFormDisabled(true);
    const payload = {
      credencialAtual: String(this.passwordForm.get('credencialAtual')?.value ?? ''),
      novaCredencial: String(this.passwordForm.get('novaCredencial')?.value ?? ''),
      confirmarNovaCredencial: String(this.passwordForm.get('confirmarNovaCredencial')?.value ?? ''),
    };

    this.profileService.changePassword(payload).subscribe({
      next: () => {
        this.savingPassword = false;
        this.setPasswordFormDisabled(false);
        this.passwordSuccess = 'Credencial atualizada com sucesso.';
        this.passwordForm.reset();
      },
      error: (err: HttpErrorResponse) => {
        this.savingPassword = false;
        this.setPasswordFormDisabled(false);
        this.passwordError = this.extractErrorMessage(err, 'Não foi possível atualizar a credencial.');
      },
    });
  }

  hasProfileFieldError(field: string, error?: string): boolean {
    const control = this.profileForm.get(field);
    if (!control) return false;
    if (error) return !!(control.touched && control.hasError(error));
    return !!(control.touched && control.invalid);
  }

  hasPasswordFieldError(field: string, error?: string): boolean {
    const control = this.passwordForm.get(field);
    if (!control) return false;
    if (error) return !!(control.touched && control.hasError(error));
    return !!(control.touched && control.invalid);
  }

  get passwordMismatch(): boolean {
    const confirmTouched = this.passwordForm.get('confirmarNovaCredencial')?.touched;
    return !!(confirmTouched && this.passwordForm.errors?.['passwordMismatch']);
  }

  private loadProfile(): void {
    this.loadingProfile = true;
    this.profileSuccess = '';
    this.profileError = '';
    this.setProfileFormDisabled(true);

    this.profileService.getMe().subscribe({
      next: (me) => {
        this.loadingProfile = false;
        this.profileForm.patchValue({
          nome: me.nome ?? '',
          email: me.email ?? '',
        });
        this.setProfileFormDisabled(false);
      },
      error: (err: HttpErrorResponse) => {
        this.loadingProfile = false;
        this.setProfileFormDisabled(false);
        if (err.status === 404) {
          const authProfile = this.authService.currentUserProfile;
          if (authProfile) {
            this.profileForm.patchValue({
              nome: authProfile.nome ?? '',
              email: authProfile.email ?? '',
            });
          }
        }
        this.profileError = this.extractErrorMessage(err, 'Não foi possível carregar os dados do perfil.');
      },
    });
  }

  private setProfileFormDisabled(disabled: boolean): void {
    if (disabled) {
      this.profileForm.disable({ emitEvent: false });
      return;
    }
    this.profileForm.enable({ emitEvent: false });
  }

  private setPasswordFormDisabled(disabled: boolean): void {
    if (disabled) {
      this.passwordForm.disable({ emitEvent: false });
      return;
    }
    this.passwordForm.enable({ emitEvent: false });
  }

  private extractErrorMessage(err: HttpErrorResponse, fallback: string): string {
    if (err.status === 404) {
      return 'API de perfil não encontrada (404). Reinicie/atualize o back-end com os novos endpoints de perfil.';
    }

    const apiError = err?.error;

    if (Array.isArray(apiError?.errors) && apiError.errors.length) {
      const msg = apiError.errors[0]?.message;
      if (msg) return String(msg);
    }

    if (typeof apiError?.message === 'string' && apiError.message.trim()) {
      return apiError.message.trim();
    }

    if (typeof apiError === 'string' && apiError.trim()) {
      return apiError.trim();
    }

    return fallback;
  }

  private passwordsMatchValidator(group: AbstractControl): ValidationErrors | null {
    const nova = group.get('novaCredencial')?.value;
    const confirmar = group.get('confirmarNovaCredencial')?.value;
    if (!nova || !confirmar) return null;
    return nova === confirmar ? null : { passwordMismatch: true };
  }
}
