import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { NgbModal } from "@ng-bootstrap/ng-bootstrap";
import { HelpersService } from "src/app/cores/services/helpers.service";
import { LoadingService } from "src/app/cores/services/loading.service";
import { AuthService } from "src/app/cores/services/auth.service";
import { LaporanService } from "src/app/cores/api-services/laporan/laporan.service";
import { SubmitComponent } from "../../laporan/modal/submit/submit.component";
import { DetailPerbaikanService } from "src/app/cores/api-services/perbaikan/detail-perbaikan.service";
import { ImageShowModalComponent } from "../../../components/image-show-modal/image-show-modal.component";
import { MaintenanceService } from "src/app/cores/api-services/perbaikan/maintenance.service";
import { forkJoin, map } from "rxjs";

@Component({
  selector: "app-detail",
  templateUrl: "./detail.component.html",
  styleUrls: ["./detail.component.scss"],
})
export class DetailComponent implements OnInit {
  detailSchedule: any | null = null;
  detailSegmenPerbaikan: any | null = null;
  closeResult = "";

  updateStatus(statusId: string) {
    const modalRef = this.modal.open(SubmitComponent);
    modalRef.result.then(
      (result) => {
        if (result) {
          this.laporan
            .update(this.detailSchedule.report_id, { status_id: statusId })
            .subscribe({
              next: () => {
                this.helpers.toast("success", "Data berhasil Diperbarui");
                this.getAll();
              },
              error: () => {
                this.helpers.toast("error", "Data gagal ditambahkan");
              },
            });
        }
      },
      () => {}
    );
  }

  onUpdatePerbaikan() {
    this.updateStatus("RPR");
  }

  onUpdateDonePerbaikan() {
    this.updateStatus("FIXED");
  }

  reportCompleted() {
    this.updateStatus("DONE");
  }

  id = this.activatedRoute.snapshot.params["id"];
  segmenId: string | null = null;
  photo: any;
  isButtonDisabled = false;

  getAll() {
    this.api
      .getById(this.id)
      .pipe()
      .subscribe({
        next: ({ data }) => {
          this.detailSchedule = data;

          const segmens = this.detailSchedule.report.segmens;
          const segmentIds = segmens.map((segment: any) => segment.segmen.id);
          const observables = segmentIds.map((segmenId: any) =>
            this.maintenance.getAll({
              filter: {
                report_schedule_id: { eq: `${this.id}` },
                segmen_id: { eq: `${segmenId}` },
              },
            })
          );

          forkJoin(observables).subscribe({
            next: (results) => {
              this.photo = results;

              const hasEmptyData = this.photo.some(
                (dataItem: any) => dataItem.data.length === 0
              );
              this.isButtonDisabled = hasEmptyData;
            },
            error: () => {
              this.helpers.toast("error", "Gagal mengambil data");
            },
          });
        },
      });
  }

  constructor(
    private auth: AuthService,
    private laporan: LaporanService,
    private activatedRoute: ActivatedRoute,
    private router: Router,
    public api: DetailPerbaikanService,
    public maintenance: MaintenanceService,
    public modal: NgbModal,
    public helpers: HelpersService,
    public loading: LoadingService
  ) {
    this.getAll();
  }

  ngOnInit(): void {}

  onBack(): void {
    this.router.navigate(["../../"], { relativeTo: this.activatedRoute });
  }

  onAction(data: any): void {
    const modalRef = this.modal.open(ImageShowModalComponent);
    modalRef.componentInstance.data = data;
  }

  isPNGL(): boolean {
    const decodedToken = this.auth.getLoggedUser();
    if (decodedToken) {
      const userRole = decodedToken.role.code;
      return userRole === "SADM";
    } else {
      return false;
    }
  }
}
