import { Component, ElementRef, ViewChild, Inject, PLATFORM_ID } from '@angular/core';
import { CommonModule, isPlatformBrowser } from '@angular/common';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import { AuthService } from '../../services/auth.service';

@Component({
  selector: 'app-register',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule, RouterLink],
  templateUrl: './register.html',
  styleUrls: ['./register.scss']
})
export class Register {
  registerForm: FormGroup;
  isSubmitting = false;
  apiError = '';

  toastMessage = '';
  @ViewChild('successToast') successToast!: ElementRef;

  constructor(
    private fb: FormBuilder,
    private authService: AuthService,
    private router: Router,
    @Inject(PLATFORM_ID) private platformId: object
  ) {
    this.registerForm = this.fb.group({
      fullName: ['', [Validators.required, Validators.minLength(3)]],
      email: ['', [Validators.required, Validators.email]],
      phone: ['', [Validators.required]],
      password: ['', [Validators.required, Validators.minLength(6)]],
      confirmPassword: ['', [Validators.required]]
    }, {
      validators: [this.passwordsMatchValidator]
    });
  }

  private passwordsMatchValidator(group: FormGroup) {
    const pass = group.get('password')?.value;
    const confirm = group.get('confirmPassword')?.value;
    return pass === confirm ? null : { passwordsMismatch: true };
  }

  private async showToast(message: string) {
    this.toastMessage = message;

    // ✅ SSR-safe: só roda no browser
    if (!isPlatformBrowser(this.platformId)) return;

    const bs = await import('bootstrap');
    const toast = new bs.Toast(this.successToast.nativeElement, { autohide: true, delay: 1800 });
    toast.show();
  }

  onSubmit(): void {
    this.apiError = '';

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

    this.isSubmitting = true;

    const v = this.registerForm.value;

    const payload = {
      name: v.fullName,
      email: v.email,
      phone: v.phone,
      password: v.password,
      confirmPassword: v.confirmPassword
    };

    this.authService.register(payload).subscribe({
      next: async () => {
        this.isSubmitting = false;

        // Se você não quer manter "logado" após cadastrar:
        this.authService.logout();

        await this.showToast('Cadastro realizado com sucesso! Agora faça login para continuar.');

        setTimeout(() => {
          this.router.navigate(['/login']);
        }, 1000);
      },
      error: (err) => {
        this.isSubmitting = false;
        this.apiError = err?.error ?? 'Erro ao cadastrar.';
      }
    });
  }

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