import { AfterViewInit, Component, ViewChild, inject } from '@angular/core';
import { GuiCellEdit, GuiSelectedRow } from '@generic-ui/ngx-grid';
import { UserTableComponent } from '../../components/tables/user-table/user-table.component';
import { MatTabsModule } from '@angular/material/tabs';
import { GroupTableComponent } from '../../components/tables/group-table/group-table.component';
import { ModuleTableComponent } from '../../components/tables/module-table/module-table.component';
import { UserCreateFormComponent } from '../../components/forms/user-create-form/user-create-form.component';
import { BasePageComponent } from '../base-page/base-page.component';
import { User } from '../../models/user-management.api.models';
import { firstValueFrom, forkJoin } from 'rxjs';
import Swal from 'sweetalert2';
import { env } from '../../../environments/environment'

import { UserSummaryComponent } from '../../components/summaries/user-summary/user-summary.component'
import { MatBottomSheet, MatBottomSheetModule } from '@angular/material/bottom-sheet';
import { MatButtonModule } from '@angular/material/button';

@Component({
  standalone: true,
  imports: [UserTableComponent, MatTabsModule, GroupTableComponent, ModuleTableComponent, MatButtonModule, MatBottomSheetModule],
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrl: './user.component.css'
})
export class UserComponent extends BasePageComponent implements AfterViewInit {
  initWithoutData = () => { }

  cellEditing: GuiCellEdit = {
    enabled: true,
    cellEdit: (value: any, item: User, index: number) => {
      if (!this.updateService.isEditable)
        return false;

      this.updateService.setAsync("user_" + item.id!.toString(), async () => {
        await firstValueFrom(this.userTable.service.update(item))
      })
      return true;
    }
  }

  private sUsername = null;

  private _bottomSheet = inject(MatBottomSheet);

  ngAfterViewInit(): void {
    this.buttonVisibilityService.setVisibleOnly(this.refreshService, this.creationService, this.updateService)
    this.refreshService.removeAll()
    this.refreshService.add(() => {
      this.userTable.fetchData();
      if (this.sUsername != null) {
        this.groupTable.fetchDataByUsername(this.sUsername);
        this.moduleTable.fetchDataByUsername(this.sUsername)
      }
    });

    this.creationService.component = UserCreateFormComponent;

    this.deletionService.add(() => this.handleDeleteRequest());
  }

  @ViewChild("userTable") userTable!: UserTableComponent
  @ViewChild("groupTable") groupTable!: GroupTableComponent;
  @ViewChild("moduleTable") moduleTable!: ModuleTableComponent;

  usersOnSelectedRows = (rows: GuiSelectedRow[]) => {
    if (rows.length > 0) {
      this.sUsername = rows[0].source.username;

      if (this.sUsername != null) {
        this.groupTable.fetchDataByUsername(this.sUsername);
        this.moduleTable.fetchDataByUsername(this.sUsername)
        this.openBottomSheet(rows[0].source);
      }
    }
  }

  handleDeleteRequest() {
    const sRows = this.userTable.selectedRows;
    if (sRows.length > 0)
      Swal.fire({
        title: "Löschen bestätigen",
        html: `<p class="text-start">Dieser Vorgang ist unwiderruflich. Möchten Sie fortfahren?<br><br>Anzahl der zu löschenden Einträge: ${sRows.length}</p>`,
        showDenyButton: true,
        confirmButtonText: "Ja",
        denyButtonText: `Nein`
      }).then((result) => {
        if (result.isConfirmed) {
          const deleteRequests = sRows.map(sRow => this.userTable.service.delete(sRow.source.id!));
          forkJoin(deleteRequests).subscribe({
            next: () => {
              this.updateService.executeAllAsync().then(() => {
                this.refreshService.executeAll();
              })
              Swal.fire({
                text: `${sRows.length} Einträge wurden erfolgreich gelöscht.`,
                icon: "success"
              })
            },
            error: err => Swal.fire({
              title: "Fehler",
              text: `Dieser Vorgang ist nicht möglich.`,
              icon: "error"
            })
          });
        }
      });
  }

  public get detailed_user_columns() {
    return env.columnNames.user.detailed
  }

  openBottomSheet(user: User): void {
    this._bottomSheet.open(UserSummaryComponent, {
      data: user
    });
  }
}