import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatDialog } from '@angular/material/dialog';
import { AddUserModalComponent } from './add-user-modal/add-user-modal.component';
import { DeleteModalComponent } from '../../../../shared/delete_modal/delete-modal/delete-modal.component';
import { HttpClient } from '@angular/common/http';
import { ToastrService } from 'ngx-toastr';
import { ConfigService } from '@services/config.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
  baseUrl: string;
  private apiUrl: string;
  dataSource = new MatTableDataSource<any>();
  filters: { [key: string]: string } = {};
  loading: boolean = false;
  length: number = 0;
  itemsPerPage: number = 10;
  page: number = 0;
  pageSizeOptions: number[] = [5, 10, 20, 40, 100];
  columns = [
    {
      columnDef: 'id',
      header: 'ID',
      cell: (user: any) => `${user.id}`
    },
    {
      columnDef: 'username',
      header: 'Nombre de Usuario',
      cell: (user: any) => `${user.username}`
    },
    {
      columnDef: 'groupsView',
      header: 'Vista de Grupos',
      cell: (user: any) => `${user.groupsView}`
    },
    {
      columnDef: 'allowedOrganizationalUnits',
      header: 'Unidades Organizacionales Permitidas',
      cell: (user: any) => `${user.allowedOrganizationalUnits.map((unit: { name: any; }) => unit.name).join(', ')}`
    },
    {
      columnDef: 'roles',
      header: 'Roles',
      cell: (user: any) => `${user.roles.join(', ')}`
    }
  ];
  displayedColumns = [...this.columns.map(column => column.columnDef), 'actions'];

  constructor(
    public dialog: MatDialog,
    private configService: ConfigService,
    private http: HttpClient,
    private toastService: ToastrService
  ) {
    this.baseUrl = this.configService.apiUrl;
    this.apiUrl = `${this.baseUrl}/users`;
  }

  ngOnInit() {
    this.search();
  }

  search() {
    this.loading = true;
    this.http.get<any>(`${this.apiUrl}?&page=${this.page + 1}&itemsPerPage=${this.itemsPerPage}`, { params: this.filters }).subscribe(
      (data) => {
        this.dataSource.data = data['hydra:member'];
        this.length = data['hydra:totalItems'];
        this.loading = false;
      },
      (error) => {
        console.error('Error fetching users', error);
        this.loading = false;
      }
    );
  }

  addUser() {
    const dialogRef = this.dialog.open(AddUserModalComponent, { width: '500px' });

    dialogRef.componentInstance.userAdded.subscribe(() => {
      this.search();
    });
  }

  editUser(user: any): void {
    const dialogRef = this.dialog.open(AddUserModalComponent, {
      width: '600px',
      data: user['@id']
    });

    dialogRef.componentInstance.userEdited.subscribe(() => {
      this.search();
    });

    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        this.search();
      }
    });
  }

  deleteUser(user: any): void {
    const dialogRef = this.dialog.open(DeleteModalComponent, {
      width: '500px',
      data: { name: user.username }
    });

    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        const apiUrl = `${this.baseUrl}/users/${user.uuid}`;

        this.http.delete(apiUrl).subscribe({
          next: () => {
            console.log('User deleted successfully');
            this.toastService.success('User deleted successfully');
            this.search();
          },
          error: (error) => {
            console.error('Error deleting user:', error);
          }
        });
      }
    });
  }

  onPageChange(event: any): void {
    this.page = event.pageIndex;
    this.itemsPerPage = event.pageSize;
    this.length = event.length;
    this.search();
  }
}