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

@Component({
  selector: 'app-roles',
  templateUrl: './roles.component.html',
  styleUrls: ['./roles.component.css']
})
export class RolesComponent implements OnInit {
  baseUrl: string = this.configService.apiUrl;
  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: (role: any) => `${role.id}`
    },
    {
      columnDef: 'name',
      header: 'Nombre',
      cell: (role: any) => `${role.name}`
    },
    {
      columnDef: 'permissions',
      header: 'Permisos',
      cell: (role: any) => `${role.permissions.join(', ')}`
    }
  ];
  displayedColumns = [...this.columns.map(column => column.columnDef), 'actions'];

  private apiUrl = `${this.baseUrl}/user-groups`;

  constructor(
    public dialog: MatDialog,
    private http: HttpClient,
    private dataService: DataService,
    private toastService: ToastrService,
    private configService: ConfigService
  ) {}

  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 roles', error);
        this.loading = false;
      }
    );
  }

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

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

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

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

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

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

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

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