import { Component, inject, signal } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzMessageService } from 'ng-zorro-antd/message';
import { AuthService } from '../../services/auth.service';
import { getErrorMessage } from '../../utils/error.utils';

@Component({
  selector: 'app-auth',
  imports: [ReactiveFormsModule, NzIconModule],
  providers: [NzMessageService],
  templateUrl: './auth.html',
  styleUrl: './auth.css'
})
export class AuthPage {
  private readonly fb = inject(FormBuilder);
  private readonly router = inject(Router);
  private readonly authService = inject(AuthService);
  private readonly message = inject(NzMessageService);

  mode = signal<'login' | 'register'>('login');
  loading = signal(false);
  isDark = signal(true);

  loginForm = this.fb.group({
    email: ['', [Validators.required, Validators.email]],
    password: ['', [Validators.required, Validators.minLength(6)]]
  });

  registerForm = this.fb.group({
    name: ['', [Validators.required, Validators.minLength(2)]],
    email: ['', [Validators.required, Validators.email]],
    password: ['', [Validators.required, Validators.minLength(6)]]
  });

  toggleMode(): void {
    this.mode.set(this.mode() === 'login' ? 'register' : 'login');
  }

  toggleTheme(): void {
    const html = document.documentElement;
    if (html.classList.contains('dark')) {
      html.classList.remove('dark');
      this.isDark.set(false);
    } else {
      html.classList.add('dark');
      this.isDark.set(true);
    }
  }

  login(): void {
    if (this.loginForm.invalid) {
      Object.values(this.loginForm.controls).forEach(c => c.markAsTouched());
      return;
    }
    const { email, password } = this.loginForm.value;
    this.loading.set(true);
    this.authService.login(email!, password!).subscribe({
      next: () => {
        this.loading.set(false);
        this.router.navigate(['/catalog']);
      },
      error: (err) => {
        this.loading.set(false);
        this.message.error(getErrorMessage(err, 'Email ou mot de passe incorrect'));
      }
    });
  }

  register(): void {
    if (this.registerForm.invalid) {
      Object.values(this.registerForm.controls).forEach(c => c.markAsTouched());
      return;
    }
    const { name, email, password } = this.registerForm.value;
    this.loading.set(true);
    this.authService.register(name!, email!, password!).subscribe({
      next: () => {
        this.loading.set(false);
        this.message.success('Compte créé avec succès !');
        this.mode.set('login');
        this.loginForm.patchValue({ email: email!, password: '' });
      },
      error: (err) => {
        this.loading.set(false);
        this.message.error(getErrorMessage(err, 'Erreur lors de la création du compte'));
      }
    });
  }
}
