import dayjs from "dayjs";
// Only import plugins that are actually used
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
import duration from "dayjs/plugin/duration";
import isBetween from "dayjs/plugin/isBetween";
import "dayjs/locale/th"; // Used dynamically via setDayjsLocale
// Extend dayjs with required plugins only
dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.extend(duration);
dayjs.extend(isBetween);
export const DATE_TIME_FORMAT_CALENDAR = {
    year: 'BBBB',
    monthAndYear: 'MMMM BBBB',
    keyboardDate: 'DD/MM/BBBB',
};
// dayjs.extend(buddhistEra)
export const convertMinuteToArrayNumber = (minutes) => {
    const days = Math.floor(minutes / 1440); // 1440 minutes in a day (24 hours)
    const hours = Math.floor((minutes % 1440) / 60);
    const remainingMinutes = minutes % 60;
    return [days, hours, remainingMinutes];
};
export const convertArrayNumberToMinute = (arr) => {
    //[day, hour, minute]
    const minutes = (arr[0] ? arr[0] * (60 * 24) : 0) + (arr[1] ? arr[1] * 60 : 0) + (arr[2] ? arr[2] : 0);
    return minutes;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const convertMinuteToDuration = (value, type) => {
    const tempValue = dayjs.duration(value, 'minutes');
    let transformValue = tempValue.minutes();
    switch (type.value) {
        case 'minutes':
            transformValue = tempValue.minutes();
            break;
        case 'hours':
            transformValue = tempValue.hours();
            break;
        case 'days':
            transformValue = tempValue.days() + dayjs.duration({ months: tempValue.months() }).asDays() + dayjs.duration({ years: tempValue.years() }).asDays();
            break;
        case 'months':
            transformValue = tempValue.months();
            break;
        case 'years':
            transformValue = tempValue.years();
            break;
    }
    return transformValue;
};
export const convertDurationToMinute = (value, type) => {
    const tempValue = dayjs.duration({ [type]: value });
    return tempValue.asMinutes();
};
export const isExpired = (date) => {
    try {
        return dayjs().isAfter(dayjs(date));
    }
    catch (e) {
        return true;
    }
};
export const isCardExpired = (expiration) => {
    const [month, year] = expiration.split('/').map(Number);
    if (!month || !year)
        return true;
    const expDate = dayjs(`${2000 + year}-${month}-01`).endOf('month');
    return dayjs().isAfter(expDate, 'day');
};
export const convertTimeToMinutes = (timeString) => {
    // Parse the time string using Day.js
    const parsedTime = dayjs(`2000-01-01 ${timeString}`);
    // Check if the parsing was successful
    if (!parsedTime.isValid()) {
        console.error('Invalid time format');
        return 0;
    }
    // Calculate the total minutes
    const totalMinutes = parsedTime.hour() * 60 + parsedTime.minute();
    return totalMinutes;
};
export const convertMinutesToTime = (totalMinutes) => {
    // Calculate hours and minutes
    const hours = Math.floor(totalMinutes / 60);
    const minutes = totalMinutes % 60;
    // Format the result as "HH:mm"
    const formattedTime = dayjs().set('hour', hours).set('minute', minutes).format('HH:mm');
    return formattedTime;
};
export const convertMinutesToDayjs = (totalMinutes) => {
    // Calculate hours and minutes
    const hours = Math.floor(totalMinutes / 60);
    const minutes = totalMinutes % 60;
    // Format the result as "HH:mm"
    const formattedTime = dayjs().set('hour', hours).set('minute', minutes).set('ms', 0).set('s', 0).local();
    return formattedTime;
};
export const isTimeBefore = (time1, time2) => {
    //String Format HH:mm:ss
    const parseTime = (time) => {
        const [hours, minutes, seconds] = time.split(':').map(Number);
        const date = new Date();
        date.setHours(hours, minutes, seconds || 0, 0);
        return date;
    };
    const date1 = parseTime(time1);
    const date2 = parseTime(time2);
    return date1.getTime() < date2.getTime();
};
export const isTimeAfter = (time1, time2) => {
    const parseTime = (time) => {
        const [hours, minutes, seconds] = time.split(':').map(Number);
        const date = new Date();
        date.setHours(hours, minutes, seconds || 0, 0);
        return date;
    };
    const date1 = parseTime(time1);
    const date2 = parseTime(time2);
    return date1.getTime() > date2.getTime();
};
export const isTimeInRange = (start_time, end_time, current_time) => {
    const format = 'HH:mm:ss';
    const startTime = dayjs(start_time, format);
    const endTime = dayjs(end_time, format);
    const currentTime = dayjs(current_time, format);
    return currentTime.isBetween(startTime, endTime, null, '[]'); // '[]' includes both start and end times
};
export const isTimeRangeOverlapping = (range1, range2) => {
    const startTime1 = dayjs(range1.start_time, 'HH:mm:ss');
    const endTime1 = dayjs(range1.end_time, 'HH:mm:ss').subtract(1, 'minutes');
    const startTime2 = dayjs(range2.start_time, 'HH:mm:ss');
    const endTime2 = dayjs(range2.end_time, 'HH:mm:ss').subtract(1, 'minutes');
    // Check if range1 starts before or at the same time as range2 ends
    // and range1 ends after or at the same time as range2 starts
    return (startTime1.isBefore(endTime2) || startTime1.isSame(endTime2)) && (endTime1.isAfter(startTime2) || endTime1.isSame(startTime2));
};
export const getDates = (startDate, endDate, format) => {
    const dates = [];
    let currentDate = dayjs(startDate);
    const endDateObj = dayjs(endDate);
    while (currentDate.isBefore(endDateObj) || currentDate.isSame(endDateObj, 'day')) {
        dates.push(currentDate.format(format));
        currentDate = currentDate.add(1, 'day');
    }
    return dates;
};
export const checkOverlappingDayjs = (timeRanges) => {
    for (let i = 0; i < timeRanges.length; i++) {
        const { startTime: startTime1, endTime: endTime1 } = timeRanges[i];
        if (!startTime1 || !endTime1)
            continue; // Skip if either is null
        for (let j = i + 1; j < timeRanges.length; j++) {
            const { startTime: startTime2, endTime: endTime2 } = timeRanges[j];
            if (!startTime2 || !endTime2)
                continue; // Skip if either is null
            if (startTime1.isBefore(endTime2) && startTime2.isBefore(endTime1)) {
                return true; // Overlap found
            }
        }
    }
    return false; // No overlap
};
export const displayTime = (date) => {
    return dayjs(date).isValid() ? dayjs(date).tz().format('HH:mm') : '';
};
export const displayDate = (date) => {
    return dayjs(date).isValid() ? dayjs(date).tz().format('DD/MM/YYYY') : '';
};
export const isToday = (date) => {
    return dayjs().tz().format('DD MMM YYYY') === dayjs(date).tz().format('DD MMM YYYY');
};
export const displayLongDate = (date) => {
    return dayjs(date).isValid() ? dayjs(date).tz().format('DD MMM YYYY') : '';
};
export const displayDateTime = (date) => {
    return dayjs(date).isValid() ? dayjs(date).tz().format('DD MMM YYYY HH:mm') : '';
};
export const setDayjsLocale = (locale) => {
    dayjs.locale(locale);
};
export const setDayjsTimeZone = (timezone) => {
    dayjs.tz.setDefault(timezone);
};
export const getRemainingDays = (date) => {
    const remainingDays = dayjs(date).diff(dayjs(), 'day');
    return remainingDays;
};
export const formatDate = (date) => {
    return dayjs(date).isValid() ? dayjs(date).tz().format('YYYY-MM-DD') : '';
};
