import { AfterViewInit, Component, ViewChild, inject } from '@angular/core';
import { GuiColumn, GuiRowClass, GuiRowStyle, GuiSelectedRow } from '@generic-ui/ngx-grid/gui/grid/src/core/api/gui.grid.public-api';
import { UserTableComponent } from '../../components/tables/user-table/user-table.component';
import { UserRepTableComponent } from '../../components/tables/user-rep-table/user-rep-table.component';
import { GroupTableComponent } from '../../components/tables/group-table/group-table.component';
import { UserRepService } from '../../services/api/user-representation.service';
import Swal from 'sweetalert2';
import { MatTabsModule, MatTabGroup } from '@angular/material/tabs';
import { env } from '../../../environments/environment';
import { BasePageComponent } from '../base-page/base-page.component';
import { Group, User, UserRep } from '../../models/user-management.api.models';
import { RepCreateFormComponent } from '../../components/forms/rep-create-form/rep-create-form.component';
import { MatDialog } from '@angular/material/dialog';
import { BaseTableComponent } from '../../components/tables/base-table/base-table.component';
import { GroupService } from '../../services/api/group.service';
import { UserService } from '../../services/api/user.service';

@Component({
  standalone: true,
  imports: [MatTabsModule, MatTabGroup, UserTableComponent, GroupTableComponent, UserRepTableComponent],
  selector: 'app-user-representation',
  templateUrl: './user-representation.component.html',
  styleUrl: './user-representation.component.css'
})
export class UserRepresentationComponent extends BasePageComponent implements AfterViewInit {

  useRepLabel: string = "";
  groupColumns: Array<GuiColumn>;
  groupRepCols: Array<GuiColumn>;
  slUserId?: number;
  slGroupId?: number;
  slRepUserId?: number;
  slRepGroupId?: number;
  slRepId?: number;

  private readonly dialog: MatDialog = inject(MatDialog);

  rep_row_class: GuiRowClass = {
    classFunction(source, index) {
      const now = new Date()

      return (!source.validFrom && !source.validTo)
        ? "current-period-row"
        : (new Date(source.validFrom) > now)
          ? "future-period-row"
          : (new Date(source.validTo) < now)
            ? "past-period-row"
            : "current-period-row";
    }
  }

  initWithoutData = () => { }

  constructor(private userRepService: UserRepService) {
    super()
    this.groupRepCols = env.columnNames.group.representative;
    this.groupColumns = env.columnNames.group.right;
    this.userRepService = userRepService;
  }

  ngAfterViewInit(): void {
    this.buttonVisibilityService.setVisibleOnly(this.refreshService, this.transferService)
    this.refreshService.removeAll();
    this.refreshService.add(() => {
      this.users.fetchData();
      this.groups.fetchData();
      this.repUsers.fetchData();
      this.repGroups.fetchData();
      this.userReps.fetchData();
    })
    this.transferService.add(() => {
      this.repUsers.safelyUnselectAll();
      this.repGroups.safelyUnselectAll();
      this.userReps.safelyUnselectAll();
    })
  }

  @ViewChild("users") users!: UserTableComponent;
  @ViewChild("groups") groups!: GroupTableComponent;
  @ViewChild("repUsers") repUsers!: UserTableComponent;
  @ViewChild("repGroups") repGroups!: GroupTableComponent;
  @ViewChild("userReps") userReps!: UserRepTableComponent;

  // user
  userOnSelectedRows = (rows: GuiSelectedRow[]) => {
    if (rows.length > 0) {
      this.useRepLabel = `Vertretungen von ${rows[0].source?.username}`
      //this.users.safelyUnselectAll();
      this.userReps.fetchByUser(rows[0].source?.id);
      this.slGroupId = undefined;
      this.slUserId = rows[0].source?.id
    }
  }

  userOnClick = (table: BaseTableComponent<User, UserService>) => {
    this.userOnSelectedRows(table.selectedRows);
  }

  // group
  groupOnSelectedRows = (rows: GuiSelectedRow[]) => {
    if (rows.length > 0) {
      this.useRepLabel = `Vertretungen von ${rows[0].source?.name}`
      this.groups.safelyUnselectAll();
      this.userReps.fetchByGroup(rows[0].source?.id);
      this.slUserId = undefined;
      this.slGroupId = rows[0].source?.id
    }
  }

  groupOnClick = (table: BaseTableComponent<Group, GroupService>) => {
    this.groupOnSelectedRows(table.selectedRows);
  }

  //repUser
  repUserOnSelectedRows = (rows: GuiSelectedRow[]) => {
    if (rows.length == 0 && this.slRepUserId) {
      if (!this.slUserId && !this.slGroupId) {
        Swal.fire({
          icon: "error",
          title: "Oops...",
          text: "Bitte wählen Sie den Benutzer oder die Gruppe!",
        });
      }
      else if (!this.slRepUserId) {
        Swal.fire({
          icon: "error",
          title: "Oops...",
          text: "Bitte wählen Sie die Vertretungen Benutzer!",
        });
      }
      else {
        var newUserRep: UserRep = {
          userId: this.slUserId,
          groupId: this.slGroupId,
          repUserId: this.slRepUserId
        }

        this.openCreateSheet(newUserRep, res => {
          if (res.successful) {
            this.slRepUserId = undefined;

            this.repUsers.safelyUnselectAll()
            this.repGroups.safelyUnselectAll()
            if (this.slUserId)
              this.userReps.fetchByUser(this.slUserId)
            if (this.slGroupId)
              this.userReps.fetchByGroup(this.slGroupId)
          }
          else if (res.error) {
            Swal.fire({
              icon: "error",
              title: "Oops...",
              text: `Dieser Vorgang ist nicht möglich.`,
            });
          }
        });
      }

      this.slRepUserId = undefined;
    }
    else if (rows.length > 0) {
      this.slRepUserId = rows[0].source?.id;
    }
  }

  repUserOnClick = (table: BaseTableComponent<User, UserService>) => {
    this.repUserOnSelectedRows(table.selectedRows);
  }

  // repGroup
  repGroupOnSelectedRows = (rows: GuiSelectedRow[]) => {
    if (rows.length == 0 && this.slRepGroupId) {
      if (!this.slUserId && !this.slGroupId) {
        Swal.fire({
          icon: "error",
          title: "Oops...",
          text: "Bitte wählen Sie den Benutzer oder die Gruppe!",
        });
      }
      else if (!this.slRepGroupId) {
        Swal.fire({
          icon: "error",
          title: "Oops...",
          text: "Bitte wählen Sie die Vertretungen Gruppe!",
        });
      }
      else {
        var newUserRep = {
          userId: this.slUserId,
          groupId: this.slGroupId,
          repGroupId: this.slRepGroupId,
        }

        this.openCreateSheet(newUserRep, res => {
          if (res.successful) {
            this.slRepGroupId = undefined;
            this.repUsers.safelyUnselectAll()
            this.groups.safelyUnselectAll()
            if (this.slUserId)
              this.userReps.fetchByUser(this.slUserId)
            if (this.slGroupId)
              this.userReps.fetchByGroup(this.slGroupId)
          }
          else if (res.error) {
            Swal.fire({
              icon: "error",
              title: "Oops...",
              text: `Dieser Vorgang ist nicht möglich.`,
            });
          }
        });
      }

      this.slRepGroupId = undefined;
    }
    else if (rows.length > 0) {
      this.slRepGroupId = rows[0].source?.id;
    }
  }

  repGroupOnClick = (table: BaseTableComponent<Group, GroupService>) => {
    this.repGroupOnSelectedRows(table.selectedRows);
  }

  // rep events
  repOnSelectedRows = (rows: GuiSelectedRow[]) => {
    if (rows.length == 0 && this.slRepId) {
      this.userRepService.delete(this.slRepId).subscribe({
        next: (res) => {
          this.slRepId = undefined;
          this.userReps.safelyUnselectAll();
          if (this.slUserId != undefined)
            this.userReps.fetchData(this.slUserId)
          if (this.slGroupId != undefined)
            this.userReps.fetchData(undefined, this.slGroupId)
        },
        error: (err) => {
          this.slRepId = undefined;
          this.repUsers.safelyUnselectAll()
          Swal.fire({
            icon: "error",
            title: "Oops...",
            text: `Dieser Vorgang ist nicht möglich.`,
          });
        }
      })
    }
    else if (rows.length > 0) {
      this.slRepId = rows[0].source?.id;
    }
  }

  repOnClick = (table: BaseTableComponent<UserRep, UserRepService>) => {
    this.repOnSelectedRows(table.selectedRows);
  }

  openCreateSheet(userRep: UserRep, afterCreation: (any: any) => any): void {

    this.dialog.open(RepCreateFormComponent, {
      width: "50rem",
      data: { userRep: userRep, afterCreation: afterCreation }
    });
  }
}
