import { useCallback } from "react";
import {
  formatDate,
  isHoliday,
  isNonWorkingDay,
} from "@/lib/utils/product-utils";
import { DeliveryTimeModel, HolidayModel } from "../types/models";

export const useEstimatedDate = (
  deliveryTimeList: DeliveryTimeModel[] = [],
  holidaysList: HolidayModel[] = []
) => {
  const getEstimatedDate = useCallback(
    (turnaroundTime?: { estimatedDateNumber?: number; cutOffTime?: string }) => {
      let turnaroundTimeCount = Math.max(0, Number(turnaroundTime?.estimatedDateNumber || 0));
      const now = new Date();
      const currentDate = new Date(now);

      let maxFirstLoop = 30;
      while (maxFirstLoop-- > 0) {
        if (
          isHoliday(currentDate, holidaysList || []) ||
          isNonWorkingDay(currentDate, deliveryTimeList || [])
        ) {
          currentDate.setDate(currentDate.getDate() + 1);
          continue;
        }

        const timeStr = turnaroundTime?.cutOffTime || "18:00";
        const [endHour = 18, endMinute = 0] = timeStr.split(":").map(Number);
        const cutOffTime = new Date(currentDate);
        cutOffTime.setHours(endHour, endMinute, 0, 0);

        if (
          now.getHours() > cutOffTime.getHours() ||
          (now.getHours() === cutOffTime.getHours() && now.getMinutes() >= cutOffTime.getMinutes())
        ) {
          currentDate.setDate(currentDate.getDate() + 1);
        }
        break;
      }

      let maxSecondLoop = 60;
      while (turnaroundTimeCount > 0 && maxSecondLoop-- > 0) {
        currentDate.setDate(currentDate.getDate() + 1);
        if (
          !isHoliday(currentDate, holidaysList || []) &&
          !isNonWorkingDay(currentDate, deliveryTimeList || [])
        ) {
          turnaroundTimeCount--;
        }
      }
      return formatDate(currentDate);
    },
    [deliveryTimeList, holidaysList]
  );

  return { getEstimatedDate };
};
