import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { GridModule, PageChangeEvent } from '@progress/kendo-angular-grid';
import { InputsModule } from '@progress/kendo-angular-inputs';
import { ButtonsModule } from '@progress/kendo-angular-buttons';
import { IndicatorsModule } from '@progress/kendo-angular-indicators';
import { HttpClient } from '@angular/common/http';
import { UserApiService } from '../../services/user-api.service';
import { EditUserDialogComponent } from '../../components/edit-user-dialog/edit-user-dialog.component';
import { CreateUserDialogComponent } from '../../components/create-user-dialog/create-user-dialog.component';
import {
  UserListItemDto, UserDto, CreateUserRequest, UpdateUserRequest, PagedResult
} from '../../models/user.model';
import { ApiConfigService } from '../../../../core/services/api-config.service';
import { PageHeaderActionsDirective } from '../../../../shared/directives/page-header-actions.directive';

@Component({
  selector: 'app-users-page',
  standalone: true,
  imports: [
    CommonModule, FormsModule, GridModule, InputsModule,
    ButtonsModule, IndicatorsModule, EditUserDialogComponent, CreateUserDialogComponent,
    PageHeaderActionsDirective,
  ],
  templateUrl: './users-page.component.html',
  styleUrls: ['./users-page.component.scss'],
})
export class UsersPageComponent implements OnInit {
  data: UserListItemDto[] = [];
  totalCount = 0;
  page = 1;
  pageSize = 20;
  isLoading = false;
  searchText = '';

  // Create dialog
  showCreateDialog = false;

  // Edit dialog
  showEditDialog = false;
  editingUser: UserDto | null = null;

  // Reset password result
  resetPasswordResult: { userId: string; tempPassword: string } | null = null;

  // Auth test result (dev only)
  authTestResult: string | null = null;

  constructor(
    private userApi: UserApiService,
    private http: HttpClient,
    private apiConfig: ApiConfigService,
  ) {}

  ngOnInit(): void { this.loadData(); }

  loadData(): void {
    this.isLoading = true;
    this.userApi.getPaged({ page: this.page, pageSize: this.pageSize, search: this.searchText || undefined })
      .subscribe({
        next: (result: PagedResult<UserListItemDto>) => {
          this.data       = result.items;
          this.totalCount = result.totalCount;
          this.isLoading  = false;
        },
        error: () => { this.isLoading = false; }
      });
  }

  onPageChange(event: PageChangeEvent): void {
    this.page     = event.skip / this.pageSize + 1;
    this.pageSize = event.take;
    this.loadData();
  }

  onSearch(): void { this.page = 1; this.loadData(); }

  /** Dev-only: hits /api/auth/me and shows the parsed claims so we can see what the JWT contains. */
  testAuth(): void {
    this.http.get(`${this.apiConfig.authUrl}/me`).subscribe({
      next: (result) => { this.authTestResult = JSON.stringify(result, null, 2); },
      error: (err)   => { this.authTestResult = `ERROR ${err.status}: ${JSON.stringify(err.error)}`; },
    });
  }

  openCreateDialog(): void { this.showCreateDialog = true; }
  closeCreateDialog(): void { this.showCreateDialog = false; }

  onUserCreated(request: CreateUserRequest): void {
    this.userApi.createUser(request).subscribe(result => {
      this.closeCreateDialog();
      this.resetPasswordResult = { userId: result.userId, tempPassword: result.tempPassword };
      this.loadData();
    });
  }

  openEditDialog(user: UserListItemDto): void {
    this.userApi.getById(user.id).subscribe(dto => {
      this.editingUser    = dto;
      this.showEditDialog = true;
    });
  }

  closeEditDialog(): void {
    this.showEditDialog = false;
    this.editingUser    = null;
  }

  onUserSaved(request: UpdateUserRequest): void {
    if (!this.editingUser) return;
    this.userApi.update(this.editingUser.id, request).subscribe(() => {
      this.closeEditDialog();
      this.loadData();
    });
  }

  deactivateUser(user: UserListItemDto): void {
    if (!confirm(`Deactivate ${user.email}? They will lose access immediately.`)) return;
    this.userApi.deactivate(user.id).subscribe(() => this.loadData());
  }

  resetPassword(user: UserListItemDto): void {
    if (!confirm(`Reset password for ${user.email}? A new temporary password will be generated.`)) return;
    this.userApi.resetPassword(user.id).subscribe(result => {
      this.resetPasswordResult = { userId: user.id, tempPassword: result.tempPassword };
    });
  }

  copyResetPassword(): void {
    if (this.resetPasswordResult) {
      navigator.clipboard.writeText(this.resetPasswordResult.tempPassword);
    }
  }

  dismissResetResult(): void { this.resetPasswordResult = null; }
}
