import {Component, OnInit, OnDestroy} from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators,
  AbstractControl,
  ValidationErrors,
  ReactiveFormsModule
} from '@angular/forms';
import {Router, ActivatedRoute} from '@angular/router';
import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {ApiResponse, ApiService, AuthResponse, RegisterData} from '../../services/api';
import {NgClass} from '@angular/common';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  imports: [
    ReactiveFormsModule,
    NgClass
  ],
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit, OnDestroy {
  registerForm: FormGroup;
  loading = false;
  error = '';
  success = '';
  private destroy$ = new Subject<void>();
  returnUrl = '';

  constructor(
    private fb: FormBuilder,
    private apiService: ApiService,
    private router: Router,
    private route: ActivatedRoute
  ) {
    this.registerForm = this.fb.group({
      name: ['', [Validators.required, Validators.minLength(3)]],
      email: ['', [Validators.required, Validators.email]],
      password: ['', [Validators.required, Validators.minLength(6)]],
      password_confirmation: ['', [Validators.required]]
    }, {validators: this.passwordsMatchValidator});
  }

  ngOnInit(): void {
    this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/dashboard';
    this.clearMessages();
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }

  // Custom validator to check password and confirmation match
  passwordsMatchValidator(group: AbstractControl): ValidationErrors | null {
    const password = group.get('password')?.value;
    const confirm = group.get('password_confirmation')?.value;
    return password === confirm ? null : {passwordsMismatch: true};
  }

  get f() {
    return this.registerForm.controls;
  }

  getFieldError(fieldName: string): string {
    const field = this.registerForm.get(fieldName);
    if (!field) return '';

    if (field.errors && (field.touched || field.dirty)) {
      if (field.errors['required']) {
        return `${this.capitalizeFirst(fieldName.replace('_', ' '))} is required`;
      }
      if (field.errors['email']) {
        return 'Please enter a valid email address';
      }
      if (field.errors['minlength']) {
        return `${this.capitalizeFirst(fieldName.replace('_', ' '))} must be at least ${field.errors['minlength'].requiredLength} characters`;
      }
    }

    if (fieldName === 'password_confirmation' && this.registerForm.errors?.["passwordsMismatch"] && (field.touched || field.dirty)) {
      return 'Passwords do not match';
    }

    return '';
  }

  hasFieldError(fieldName: string): boolean {
    const field = this.registerForm.get(fieldName);
    if (!field) return false;

    if (fieldName === 'password_confirmation') {
      return field.touched && this.registerForm.errors?.["passwordsMismatch"] === true;
    }

    return !!(field.errors && (field.touched || field.dirty));
  }

  private capitalizeFirst(str: string): string {
    return str.charAt(0).toUpperCase() + str.slice(1);
  }

  clearMessages(): void {
    this.error = '';
    this.success = '';
  }

  onSubmit(): void {
    this.clearMessages();
    this.registerForm.markAllAsTouched();

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

    this.loading = true;

    const userData: RegisterData = {
      name: this.f['name'].value,
      email: this.f['email'].value,
      password: this.f['password'].value,
      password_confirmation: this.f['password_confirmation'].value
    };


    this.apiService.register(userData)
      .pipe(takeUntil(this.destroy$))
      .subscribe({
        next: (response: ApiResponse<AuthResponse>) => {
          this.loading = false;
          if (response.success) {
            this.success = 'Registration successful! Redirecting...';
            setTimeout(() => {
              this.router.navigate([this.returnUrl]);
            }, 1000);
          } else {
            console.log(response);
            this.error = response.message || 'Registration failed. Please try again.';
          }
        },
        error: (error: { status: number; error: { errors: any; }; userMessage: string; }) => {
          this.loading = false;
          if (error.status === 422 && error.error?.errors) {
            const serverErrors = error.error.errors;
            let errorMessages: string[] = [];

            Object.keys(serverErrors).forEach(key => {
              if (Array.isArray(serverErrors[key])) {
                errorMessages = errorMessages.concat(serverErrors[key]);
              }
            });

            this.error = errorMessages.join(', ');
          } else {
            this.error = error.userMessage || 'An error occurred. Please try again.';
          }
          console.error('Registration error:', error);
        }
      });
  }

  goToLogin(): void {
    this.router.navigate(['/login'], {queryParams: {returnUrl: this.returnUrl}});
  }
}
