import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { NgbModal } from "@ng-bootstrap/ng-bootstrap";
import { SubmitComponent } from "../modal/submit/submit.component";
import { BaseCrudComponent } from "src/app/cores/class-templates/base-crud.component";
import {
  Perbaikan,
  PerbaikanService,
} from "src/app/cores/api-services/perbaikan/perbaikan.service";
import { HelpersService } from "src/app/cores/services/helpers.service";
import { LoadingService } from "src/app/cores/services/loading.service";
import { NgbDate, NgbCalendar } from "@ng-bootstrap/ng-bootstrap";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { WhiteSpaceValidator } from "src/app/cores/form-validators/whitespace";
import { UserService } from "src/app/cores/api-services/manage/user.service";

@Component({
  selector: "app-tindak-lanjut",
  templateUrl: "./tindak-lanjut.component.html",
  styleUrls: ["./tindak-lanjut.component.scss"],
})
export class TindakLanjutComponent
  extends BaseCrudComponent<Perbaikan>
  implements OnInit
{
  id: string = "";
  form: FormGroup = {} as FormGroup;

  fromDate: NgbDate;
  toDate: NgbDate | null = null;
  hoveredDate: NgbDate | null = null;

  dateRangeVisible: boolean = false;
  showDatePicker = false;

  status_id: string = "FOLUP";
  todayDate: {
    year: number;
    month: number;
    day: number;
  };

  dataPengelola: any = "";
  filterByPengelola = {
    filter: { urole_id: { eq: "1038dcc0-3bb0-4253-87fa-ef0e09a4429d" } },
    limit: 10,
    sort: "-created_at",
  };

  constructor(
    calendar: NgbCalendar,
    private pengelola: UserService,
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private formBuilder: FormBuilder,
    public override helpers: HelpersService,
    public override loading: LoadingService,
    public override api: PerbaikanService,
    public override modal: NgbModal
  ) {
    super(helpers, loading, api, modal);
    const today = new Date();
    this.todayDate = {
      year: today.getFullYear(),
      month: today.getMonth() + 1,
      day: today.getDate(),
    };

    this.pengelola.getAll(this.filterByPengelola).subscribe({
      next: ({ data }) => {
        this.dataPengelola = data;
      },
    });

    this.fromDate = calendar.getToday();
    this.toDate = calendar.getNext(calendar.getToday(), "d", 1);
  }

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

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

  selectedMaintenanceBy: any;

  onMaintenanceByChange(event: any): void {
    // (<FormGroup>this.form.controls["list"]).controls[
    //   "maintenance_by"
    // ].patchValue(event.target.value);
    if (event && event.target) {
      (<FormGroup>this.form.controls["list"]).controls[
        "maintenance_by"
      ].patchValue(event.target.value);
    }
  }

  initForm(): void {
    this.form = this.formBuilder.group({
      report_id: [this.id],
      date_start: [this.fromDate, Validators.required],
      date_end: [this.toDate],
      status: [null, WhiteSpaceValidator.noWhiteSpace],
      note: [null, WhiteSpaceValidator.noWhiteSpace],
      list: this.formBuilder.group({
        maintenance_by: [this.selectedMaintenanceBy, Validators.required],
      }),
    });
  }

  formatDate(date: any): string {
    const year = date.year;
    const month = date.month < 10 ? "0" + date.month : date.month;
    const day = date.day < 10 ? "0" + date.day : date.day;

    return `${year}-${month}-${day}`;
  }

  formatAndPatchValues(): void {
    const formattedStartDate = this.formatDate(this.fromDate);
    const formattedEndDate = this.toDate ? this.formatDate(this.toDate) : null;

    this.form.patchValue({
      date_start: formattedStartDate,
      date_end: formattedEndDate,
    });
  }

  onSubmit(): void {
    const modalRef = this.modal.open(SubmitComponent);
    modalRef.result.then(
      (result) => {
        if (result) {
          this.formatAndPatchValues();
          if (this.form.valid) {
            this.api.insert(this.form.value).subscribe({
              next: () => {
                this.helpers.toast("success", "Data berhasil ditambahkan");
              },
              error: (e) => {
                this.helpers.toast("error", "Data gagal ditambahkan");
              },
            });
            setTimeout(() => {
              this.router.navigate(["dashboard", "jadwal-perbaikan"]);
            }, 2000);
          }
        }
      },
      () => {}
    );
  }

  getFormattedDateRange(): any {
    if (this.fromDate) {
      const fromDateStr = `${this.fromDate.day}/${this.fromDate.month}/${this.fromDate.year}`;
      if (this.toDate) {
        const toDateStr = `${this.toDate.day}/${this.toDate.month}/${this.toDate.year}`;
        return `${fromDateStr} - ${toDateStr}`;
      } else {
        return fromDateStr;
      }
    } else {
      return "";
    }
  }

  toggleDatePicker() {
    this.showDatePicker = !this.showDatePicker;
  }

  onDateSelection(date: NgbDate) {
    if (!this.fromDate && !this.toDate) {
      this.fromDate = date;
    } else if (this.fromDate && !this.toDate && date.after(this.fromDate)) {
      this.toDate = date;
    } else {
      this.toDate = null;
      this.fromDate = date;
    }
  }

  isHovered(date: NgbDate) {
    return (
      this.fromDate &&
      !this.toDate &&
      this.hoveredDate &&
      date.after(this.fromDate) &&
      date.before(this.hoveredDate)
    );
  }

  isInside(date: NgbDate) {
    return this.toDate && date.after(this.fromDate) && date.before(this.toDate);
  }

  isRange(date: NgbDate) {
    return (
      date.equals(this.fromDate) ||
      (this.toDate && date.equals(this.toDate)) ||
      this.isInside(date) ||
      this.isHovered(date)
    );
  }
}
