
import {
  Component,
  inject,
  signal
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideUserPlus } from '@ng-icons/lucide';

import { AuthenticationService } from '../../application/services/authentication.service';
import { ServerDirectoryFacade } from '../../../server-directory';
import { UsersActions } from '../../../../store/users/users.actions';
import { User } from '../../../../shared-kernel';

@Component({
  selector: 'app-register',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    NgIcon
  ],
  viewProviders: [provideIcons({ lucideUserPlus })],
  templateUrl: './register.component.html'
})
/**
 * Registration form allowing new users to create an account on a selected server.
 */
export class RegisterComponent {
  serversSvc = inject(ServerDirectoryFacade);

  servers = this.serversSvc.servers;
  username = '';
  displayName = '';
  password = '';
  serverId: string | undefined = this.serversSvc.activeServer()?.id;
  error = signal<string | null>(null);

  private auth = inject(AuthenticationService);
  private store = inject(Store);
  private route = inject(ActivatedRoute);
  private router = inject(Router);

  /** TrackBy function for server list rendering. */
  trackById(_index: number, item: { id: string }) { return item.id; }

  /** Validate and submit the registration form, then navigate to search on success. */
  submit() {
    this.error.set(null);
    const sid = this.serverId || this.serversSvc.activeServer()?.id;

    this.auth.register({ username: this.username.trim(),
      password: this.password,
      displayName: this.displayName.trim(),
      serverId: sid }).subscribe({
      next: (resp) => {
        if (sid)
          this.serversSvc.setActiveServer(sid);

        const user: User = {
          id: resp.id,
          oderId: resp.id,
          username: resp.username,
          displayName: resp.displayName,
          status: 'online',
          role: 'member',
          joinedAt: Date.now()
        };

        this.store.dispatch(UsersActions.authenticateUser({ user }));
        const returnUrl = this.route.snapshot.queryParamMap.get('returnUrl')?.trim();

        if (returnUrl?.startsWith('/')) {
          this.router.navigateByUrl(returnUrl);

          return;
        }

        this.router.navigate(['/search']);
      },
      error: (err) => {
        this.error.set(err?.error?.error || 'Registration failed');
      }
    });
  }

  /** Navigate to the login page. */
  goLogin() {
    const returnUrl = this.route.snapshot.queryParamMap.get('returnUrl')?.trim();

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