import { CommonModule } from "@angular/common";
import { Component, OnInit, Input } from "@angular/core";
import { FilePreviewModel, ValidationError } from "ngx-awesome-uploader";
import { FilePickerModule } from "ngx-awesome-uploader";
import { HttpClient } from "@angular/common/http";
import { Adapter } from "./adapter";
import { Observable, of } from "rxjs";
import { delay } from "rxjs/operators";
import { AuthService } from "src/app/cores/services/auth.service";
import {
  ModalDismissReasons,
  NgbAccordionModule,
  NgbModal,
} from "@ng-bootstrap/ng-bootstrap";
import { BaseCrudComponent } from "src/app/cores/class-templates/base-crud.component";
import {
  Maintenance,
  MaintenanceService,
} from "src/app/cores/api-services/perbaikan/maintenance.service";
import { HelpersService } from "src/app/cores/services/helpers.service";
import { LoadingService } from "src/app/cores/services/loading.service";
import { LightboxComponent } from "../lightbox/lightbox.component";
import { ActivatedRoute } from "@angular/router";
import { AlertComponent } from "../alert/alert.component";
import { FormsModule } from "@angular/forms";
import { LaporanService } from "src/app/cores/api-services/laporan/laporan.service";

export interface PhotoAfter {
  filename: string;
  abs_path: string;
  file_dump_id: string;
}

@Component({
  selector: "app-upload-image",
  standalone: true,
  imports: [
    CommonModule,
    NgbAccordionModule,
    FilePickerModule,
    LightboxComponent,
    FormsModule,
  ],
  templateUrl: "./upload-image.component.html",
  styleUrls: ["./upload-image.component.scss"],
})
export class UploadImageComponent
  extends BaseCrudComponent<Maintenance>
  implements OnInit
{
  @Input() detailedSegment: any;
  @Input() index: any;
  @Input() status_report: any;

  adapter = new Adapter(this.http);
  imageFiles: PhotoAfter[] = [];

  note: any;
  id: string = "";
  form: any = {};

  constructor(
    private auth: AuthService,
    private laporan: LaporanService,
    private http: HttpClient,
    private activatedRoute: ActivatedRoute,
    public override helpers: HelpersService,
    public override loading: LoadingService,
    public override api: MaintenanceService,
    public override modal: NgbModal
  ) {
    super(helpers, loading, api, modal);
    this.id = this.activatedRoute.snapshot.params["id"];
  }

  override ngOnInit(): void {
    this.queries = {
      filter: {
        report_schedule_id: { eq: `${this.id}` },
        segmen_id: { eq: `${this.detailedSegment?.segmen?.id}` },
      },
      limit: 10,
    };

    this.form.report_schedule_id = this.id;
    this.form.segmen_id = this.detailedSegment.segmen.id;
    this.form.date = new Date();
    this.form.note = "";
    this.getAll();
    this.checkFoto();
  }

  override getAll(): void {
    this.loading.show();
    this.api.getAll(this.queries).subscribe({
      next: ({ data }) => {
        this.loading.hide();
        this.note = data;
        if (data?.[0]?.photo_after) {
          this.imageFiles = data[0].photo_after;
        } else {
        }
      },
      error: () => {
        this.loading.hide();
        this.helpers.toast("error", `Gagal mengambil data`);
      },
    });
  }

  checkFoto(): boolean {
    for (const item of this.imageFiles) {
      if (item.abs_path) {
        return true;
      }
    }
    return false;
  }

  public onFileAdded(file: FilePreviewModel) {}

  public onValidationError(error: ValidationError): void {
    if (error.error === "FILE_MAX_SIZE") {
      this.helpers.toast(
        `warning`,
        "File terlalu besar maksimal yang diizinkan adalah 5mb"
      );
    }
  }

  onFileInputChange(event: any) {}

  isUploadSuccessful: boolean = false;
  public uploadSuccess(event: any): void {
    this.modal.dismissAll;
    this.loading.isLoading();
    this.imageFiles.push({
      filename: event.uploadResponse.data.filename,
      abs_path: event.uploadResponse.data.abs_path,
      file_dump_id: event.uploadResponse.data.id,
    });
    this.isUploadSuccessful = true;
  }

  public onSubmit() {
    this.form.photo_after = this.imageFiles;

    this.api
      .insert(this.form)
      .pipe()
      .subscribe({
        next: () => {
          this.helpers.toast("success", "Foto berhasil ditambahkan");
          this.getAll();
          this.laporan.getAll();
        },
      });

    setTimeout(() => {
      window.location.reload();
    }, 1500);
  }

  public removeFile(index: number): void {
    this.imageFiles.splice(index, 1);
  }

  public onRemoveSuccess(e: FilePreviewModel) {
    alert("Data berhasil dihapus");
  }

  public myCustomValidator(file: File): Observable<boolean> {
    if (!file.name.includes("uploader")) {
      return of(true).pipe(delay(2000));
    }
    return of(false).pipe(delay(2000));
  }

  closeResult = "";
  open(content: any) {
    if (this.status_report.id == "FOLUP") {
      const modalRef = this.modal.open(AlertComponent, {
        backdropClass: "bg-info",
        size: "sm",
      });
      modalRef.componentInstance.bgColor = "#4b527e";
      modalRef.componentInstance.textColor = "#000000";
      modalRef.componentInstance.message = "Ubah status menjadi";
      modalRef.componentInstance.statusMessage = "Perbaikan";
    } else {
      this.modal
        .open(content, {
          ariaLabelledBy: "modal-basic-title",
          centered: true,
        })
        .result.then(
          (result) => {
            this.closeResult = `Closed with: ${result}`;
          },
          (reason) => {
            this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
          }
        );
    }
  }

  closeModal() {
    this.modal.dismissAll();
  }

  private getDismissReason(reason: any): string {
    if (reason === ModalDismissReasons.ESC) {
      return "by pressing ESC";
    } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
      return "by clicking on a backdrop";
    } else {
      return `with: ${reason}`;
    }
  }

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