import { Component, OnInit } from "@angular/core";
import { BaseCrudComponent } from "src/app/cores/class-templates/base-crud.component";
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 { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { WhiteSpaceValidator } from "src/app/cores/form-validators/whitespace";
import { ValidationError } from "ngx-awesome-uploader";
import { AdaperSurveyor } from "./adapter";
import { HttpClient } from "@angular/common/http";
import { PostSurveyService } from "src/app/cores/api-services/surveyor/postsurvey.service";
import { Survey } from "src/app/cores/interfaces/master";

@Component({
  selector: "app-detail",
  templateUrl: "./detail.component.html",
  styleUrls: ["./detail.component.scss"],
})
export class DetailComponent
  extends BaseCrudComponent<Survey>
  implements OnInit
{
  public adapter = new AdaperSurveyor(this.http);

  public uploadSuccess(event: any): void {}

  public onValidationError(error: ValidationError): void {
    alert(`Validation Error ${error.error} in ${error.file?.name}`);
  }

  id: string = "";
  isButtonDisabled = false;

  form: FormGroup = {} as FormGroup;

  constructor(
    private http: HttpClient,
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private formBuilder: FormBuilder,
    public override api: PostSurveyService,
    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",
    };
  }

  override ngOnInit(): void {
    this.id = this.activatedRoute.snapshot.params["id"];
    this.initForm();
  }

  initForm(): void {
    this.form = this.formBuilder.group({
      report_id: this.id,
      tingkat_kerusakan: ["baik", [Validators.required]],
      tipe_kerusakan: ["berlubang", [Validators.required]],
      kedalaman_lubang: ["tidak_ada", [Validators.required]],
      length: [
        null,
        [Validators.required, Validators.pattern(/^[0-9]+(\.[0-9]{1,2})?$/)],
      ],
      width: [
        null,
        [Validators.required, Validators.pattern(/^[0-9]+(\.[0-9]{1,2})?$/)],
      ],
      jenis_material: ["ACBC", [Validators.required]],
      masukan_material: [null, [WhiteSpaceValidator.noWhiteSpace]],
      note: [null, [WhiteSpaceValidator.noWhiteSpace]],
    });
  }

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

  onSubmit(): void {
    if (this.form.valid) {
      const photoSurveyor = {
        photos: {
          abs_path: this.adapter.imageFiles.abs_path,
        },
      };

      console.log(photoSurveyor);

      console.log(this.adapter.imageFiles);

      this.api.insert(this.form.value).subscribe({
        next: ({ data }) => {
          console.log("hasil post ke endpoint surveyor", data);
          console.log("foto yang akan dikirim", photoSurveyor);

          this.api.update(data.id, photoSurveyor).subscribe({
            next: ({ data }) => {
              console.log(data);
            },
          });
          this.helpers.toast(
            "success",
            "Data Hasil Survey berhasil ditambahkan"
          );
          // this.router.navigate(["/dashboard/surveyor"]);
        },
        error: (e) => {
          this.helpers.toast("error", "Data gagal ditambahkan");
        },
      });
    }
  }
}
