import { Component, OnInit } from "@angular/core";
import { CommonModule } from "@angular/common";
import {
  NgbActiveModal,
  NgbAlertModule,
  NgbCalendar,
  NgbModal,
} from "@ng-bootstrap/ng-bootstrap";
import {
  FormBuilder,
  FormGroup,
  ReactiveFormsModule,
  Validators,
} from "@angular/forms";
import { NgbDate, NgbDatepickerModule } from "@ng-bootstrap/ng-bootstrap";
import { FormsModule } from "@angular/forms";
import { HelpersService } from "src/app/cores/services/helpers.service";
import { BaseCrudComponent } from "src/app/cores/class-templates/base-crud.component";
import {
  Perbaikan,
  PerbaikanService,
} from "src/app/cores/api-services/perbaikan/perbaikan.service";
import { LoadingService } from "src/app/cores/services/loading.service";

@Component({
  selector: "app-jadwal",
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    NgbDatepickerModule,
    FormsModule,
    NgbAlertModule,
  ],
  templateUrl: "./jadwal.component.html",
  styleUrls: ["./jadwal.component.scss"],
})
export class JadwalComponent
  extends BaseCrudComponent<Perbaikan>
  implements OnInit
{
  form: FormGroup = {} as FormGroup;

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

  showDatePicker = false;

  id: string = "";
  data: any;

  todayDate: {
    year: number;
    month: number;
    day: number;
  };

  constructor(
    calendar: NgbCalendar,
    public activeModal: NgbActiveModal,
    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.fromDate = calendar.getToday();
    this.toDate = calendar.getNext(calendar.getToday());
  }

  getFormattedDateRange(): any {
    const startDate = new Date(this.data.date_start);
    const endDate = this.data.date_end ? new Date(this.data.date_end) : null;

    const formattedStartDate = `${startDate.getDate()}/${
      startDate.getMonth() + 1
    }/${startDate.getFullYear()}`;

    if (endDate) {
      const formattedEndDate = `${endDate.getDate()}/${
        endDate.getMonth() + 1
      }/${endDate.getFullYear()}`;
      return `${formattedStartDate} - ${formattedEndDate}`;
    } else {
      return formattedStartDate;
    }
  }

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

  override ngOnInit(): void {
    this.initForm();
  }

  initForm(): void {
    this.form = this.formBuilder.group({
      report_id: [this.id],
      date_start: [this.fromDate, Validators.required],
      date_end: [this.toDate],
    });
    if (this.data) {
      this.form.patchValue(this.data);
    }
  }

  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)
    );
  }

  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 {
    this.formatAndPatchValues();
    if (this.form.valid) {
      this.api.update(this.data.id, this.form.value).subscribe({
        next: () => {
          this.helpers.toast("success", "Data berhasil ditambahkan");
          setTimeout(() => {
            window.location.reload();
          }, 1000);
          this.activeModal.close(this.form.value);
        },
        error: () => {
          this.helpers.toast("error", "Data gagal ditambahkan");
        },
      });
    }
  }
}
