import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { NgbModal } 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";
import { SubmitComponent } from "../modal/submit/submit.component";
import { Segmens } from "src/app/cores/interfaces/master";
import { ModalAssignSurveyorComponent } from "../../../components/modal-assign-surveyor/modal-assign-surveyor.component";
import { Subject, takeUntil } from "rxjs";
import { ExportLaporanByIdService } from "src/app/cores/api-services/export/export-laporanByid.service";
import { RejectedLaporanService } from "src/app/cores/api-services/laporan/rejected-laporan.service";
import { AlertComponent } from "../modal/alert/alert.component";
import { HttpClient } from "@angular/common/http";
import * as saveAs from "file-saver";

@Component({
  selector: "app-detail",
  templateUrl: "./detail.component.html",
  styleUrls: ["./detail.component.scss"],
})
export class DetailComponent
  extends BaseCrudComponent<Laporan>
  implements OnInit
{
  reportDetails: Laporan | undefined;
  segmens: Segmens[] | undefined;
  dataInsertSubs$ = new Subject<void>();

  id: string = "";
  showButtonCompleted: boolean = true;
  public isCollapsed = true;

  rate: any;

  constructor(
    private http: HttpClient,
    private auth: AuthService,
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private download: ExportLaporanByIdService,
    private rejected: RejectedLaporanService,
    public override api: LaporanService,
    public override modal: NgbModal,
    public override helpers: HelpersService,
    public override loading: LoadingService
  ) {
    super(helpers, loading, api, modal);
    this.queries = {
      sort: "-updated_at",
      page: 1,
      limit: 10,
      embed:
        "status_report,user,segmens,segmens.segmen,segmens.photos,schedule,survey,survey.photos,rating",
    };
    this.api.endpoint = "report-list";
  }

  override ngOnInit(): void {
    this.id = this.activatedRoute.snapshot.params["id"];
    this.loading.isLoading();
    this.api
      .getById(this.id, this.queries)
      .pipe()
      .subscribe({
        next: ({ data }) => {
          this.reportDetails = data;
          this.segmens = data.segmens;
        },
        error: () => {
          this.helpers.toast("error", "Data tidak ditemukan");
        },
      });
  }

  reportCompleted() {
    this.api.update(this.id, { status_id: "DONE" }).subscribe({
      next: () => {
        this.helpers.toast("success", "Data berhasil Diperbarui");
      },
      error: () => {
        this.helpers.toast("error", "Data gagal ditambahkan");
      },
    });
  }

  getData() {
    this.api
      .getById(this.id, this.queries)
      .pipe()
      .subscribe({
        next: ({ data }) => {
          this.reportDetails = data;
        },
        error: () => {
          this.helpers.toast("error", "Data Gagal Diperbarui");
        },
      });
  }

  reportReject() {
    const modalRef = this.modal.open(SubmitComponent);
    modalRef.componentInstance.modalType = 1;
    modalRef.componentInstance.message = "Ditolak";
    modalRef.result.then(
      (result) => {
        if (result) {
          this.api.update(this.id, { status_id: "RJT" }).subscribe({
            next: () => {
              this.getData();
              this.helpers.toast("danger", "Data berhasil Ditolak");
            },
            error: () => {
              this.helpers.toast("error", "Data gagal ditambahkan");
            },
          });
          this.rejected
            .insert({ report_id: this.id, note: result.note })
            .subscribe({});
          this.showButtonCompleted = false;
        }
      },
      () => {}
    );
  }

  onCreateSurveyor() {
    const modalRef = this.modal.open(ModalAssignSurveyorComponent);
    modalRef.componentInstance.action = "update";
    modalRef.result.then((result) => {
      if (result) {
        this.api
          .update(this.id, result)
          .pipe(takeUntil(this.dataInsertSubs$))
          .subscribe({
            next: () => {
              this.getData();
              this.helpers.toast("success", "Surveyor berhasil ditambahkan");
            },
            error: (e) => {
              this.helpers.toast(
                "error",
                `Surveyor gagal ditambahkan ${e.error.message}`
              );
            },
          });
      }
    });
  }

  downloadFile(data: any) {
    const blob = new Blob([data], { type: "application/pdf" });

    const url = window.URL.createObjectURL(blob);

    const link = document.createElement("a");
    link.href = url;
    link.download = `laporan${this.id}.pdf`;
    document.body.appendChild(link);

    link.click();
    document.body.removeChild(link);
  }

  onDownload() {
    this.loading.show();
    this.download
      .getById(this.id)
      .pipe()
      .subscribe({
        next: ({ data }) => {
          this.loading.hide();
          const rel_path = data.rel_path;
          window.open(rel_path, "_blank");
        },
        error: (error) => {},
      });
  }

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

  goToFollowUp() {
    this.api.getData(this.id, this.queries).subscribe({
      next: ({ data }) => {
        let showAlert = false;
        data.segmens.forEach((segment) => {
          if (
            segment.user_level.trim() === "-" ||
            segment.user_type.trim() === "-"
          ) {
            showAlert = true;
          }
        });
        if (showAlert) {
          this.modal.open(AlertComponent);
        } else {
          this.router.navigate(["tindak-lanjut"], {
            relativeTo: this.activatedRoute,
          });
        }
      },
    });
  }

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