import { CommonModule } from "@angular/common";
import { Component, Input, OnInit } from "@angular/core";
import {
  FormBuilder,
  Validators,
  FormGroup,
  ReactiveFormsModule,
  FormsModule,
} from "@angular/forms";
import {
  NgbActiveModal,
  NgbCalendar,
  NgbDate,
  NgbDatepicker,
} from "@ng-bootstrap/ng-bootstrap";
import { UserService } from "src/app/cores/api-services/manage/user.service";
import { HelpersService } from "src/app/cores/services/helpers.service";

@Component({
  selector: "app-modal-assign-surveyor",
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule, NgbDatepicker, FormsModule],
  templateUrl: "./modal-assign-surveyor.component.html",
  styleUrls: ["./modal-assign-surveyor.component.scss"],
})
export class ModalAssignSurveyorComponent implements OnInit {
  @Input() action = "create";
  @Input() data: any = {};

  form: FormGroup = {} as FormGroup;

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

  surveyorSelected: any;
  dataSurveyor: any;

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

  constructor(
    calendar: NgbCalendar,
    private surveyor: UserService,
    public activeModal: NgbActiveModal,
    public helpers: HelpersService,
    private formBuilder: FormBuilder
  ) {
    const today = new Date();
    this.todayDate = {
      year: today.getFullYear(),
      month: today.getMonth() + 1,
      day: today.getDate(),
    };
    this.surveyor
      .getAll({
        filter: { urole_id: { eq: "1b4701ab-da41-405b-9fe3-039a4daf0094" } },
        limit: 10,
        sort: "-created_at",
      })
      .subscribe({
        next: ({ data }) => {
          this.dataSurveyor = data;
        },
      });

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

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

  initForm(): void {
    this.form = this.formBuilder.group({
      survey_start_date: [this.fromDate, Validators.required],
      survey_end_date: [this.fromDate],
      assign_survey_to: [null, [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({
      survey_start_date: formattedStartDate,
      survey_end_date: formattedEndDate,
    });
  }

  onSubmit(): void {
    this.formatAndPatchValues();
    if (this.form.valid) {
      this.activeModal.close(this.form.value);
    }
  }

  onSurveyorByChange(event: any): void {
    const assignSurveyorControl = this.form.get("assign_surveyor");
    if (assignSurveyorControl) {
      assignSurveyorControl.setValue(event.target.value);
    }
  }

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

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

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