
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 { lucideLogIn } 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-login',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    NgIcon
  ],
  viewProviders: [provideIcons({ lucideLogIn })],
  templateUrl: './login.component.html'
})
/**
 * Login form allowing existing users to authenticate against a selected server.
 */
export class LoginComponent {
  serversSvc = inject(ServerDirectoryFacade);

  servers = this.serversSvc.servers;
  username = '';
  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 login form, then navigate to search on success. */
  submit() {
    this.error.set(null);
    const sid = this.serverId || this.serversSvc.activeServer()?.id;

    this.auth.login({ username: this.username.trim(),
      password: this.password,
      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 || 'Login failed');
      }
    });
  }

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

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