import { CommonModule } from "@angular/common";
import { Component } from "@angular/core";
import { ReactiveFormsModule } from "@angular/forms";
import { Router } from "@angular/router";
import {
  NgbDropdownModule,
  NgbModal,
  NgbPaginationModule,
} from "@ng-bootstrap/ng-bootstrap";
import {
  Laporan,
  LaporanService,
} from "src/app/cores/api-services/laporan/laporan.service";
import { BaseCrudComponent } from "src/app/cores/class-templates/base-crud.component";
import { AuthService } from "src/app/cores/services/auth.service";
import { HelpersService } from "src/app/cores/services/helpers.service";
import { LoadingService } from "src/app/cores/services/loading.service";

@Component({
  selector: "app-laporan",
  standalone: true,
  imports: [
    NgbPaginationModule,
    NgbDropdownModule,
    CommonModule,
    ReactiveFormsModule,
  ],
  templateUrl: "./laporan.component.html",
  styleUrls: ["./laporan.component.scss"],
})
export class LaporanComponent extends BaseCrudComponent<Laporan> {
  constructor(
    private router: Router,
    private auth: AuthService,
    public override modal: NgbModal,
    public override helpers: HelpersService,
    public override api: LaporanService,
    public override loading: LoadingService
  ) {
    super(helpers, loading, api, modal);
    this.queryLimit = 5;
    this.queries = {
      page: 1,
      sort: "-created_at",
      limit: 5,
      embed: "status_report,user,segmens,segmens.segmen,segmens.photos",
    };
    if (this.auth.getLoggedUser().role.code == "PNGL") {
      this.api.endpoint = `report-list/pengelola`;
    }
  }

  statusId: string = "";

  field = {
    eq: this.statusId,
  };

  applyFilter(statusId: string) {
    this.statusId = statusId;
    if (this.statusId !== "") {
      this.queries.filter = { status_id: { eq: this.statusId } };
    } else {
      if (this.auth.getLoggedUser().role.code == "SADM") {
        delete this.queries.filter.status_id;
      } else {
        this.queries.filter = { status_id: { ne: `PROG,RJT` } };
      }
    }
    this.getAll();
    return true;
  }

  goToDetail(id: string) {
    if (this.auth.getLoggedUser().role.code == "PNGL") {
      this.router.navigate(["dashboard", "data-laporan", id]);
    } else {
      this.router.navigate(["dashboard", "data-laporan", id]);
    }
  }

  isPNGL(): boolean {
    const decodedToken = this.auth.getLoggedUser();
    if (decodedToken) {
      const userRole = decodedToken.role.code;

      return userRole === "SADM";
    } else {
      return false;
    }
  }

  parsing(text: string) {
    return JSON.parse(text);
  }
}
