import dayjs, { Dayjs } from 'dayjs';
import { FillTarget } from 'chart.js';
import { hexToRgba } from '@utils/functions';
import { ILicenseData, ILicenseReport } from '@red/domain';
import { ComplexFillTarget } from 'chart.js/dist/types';

const monthNames = dayjs.monthsShort();
const currentMonth = dayjs(Date.now()).month();

export const verboseDate = (date: Dayjs) => `${monthNames[date.month()]} ${date.year()}`;

export const getLineConfig: (
    color: string,
    displayLine: boolean,
    target: FillTarget,
) => {
    type: 'line';
    borderColor: string;
    backgroundColor: string;
    pointBackgroundColor: string;
    fill: ComplexFillTarget;
} = (color, displayLine, target) => ({
    type: 'line',
    borderColor: hexToRgba(color, displayLine ? 1 : 0),
    backgroundColor: hexToRgba(color, 1),
    pointBackgroundColor: hexToRgba(color, 1),
    fill: {
        target: target ?? '-1',
        above: hexToRgba(color, 0.3),
        below: hexToRgba(color, 0.3),
    },
    pointStyle: false,
});

export const getLabelsFromLicense = (license: ILicenseReport) => {
    const startMonth = dayjs(license.startDate).startOf('month');
    const endMonth = dayjs(license.endDate).endOf('month');
    let monthIterator = startMonth;

    const result = [];

    while (monthIterator.isBefore(endMonth)) {
        result.push(verboseDate(monthIterator));
        monthIterator = monthIterator.add(1, 'month');
    }

    if (startMonth.isSame(endMonth, 'month') || isCurrentMonth(startMonth.toDate())) {
        result.splice(0, 0, '');
    }

    return result;
};

export const getDataUntilCurrentMonth = (monthlyData: ILicenseData[]) => {
    return monthlyData.filter(data => dayjs(data.startDate).isSameOrBefore(dayjs(Date.now()), 'month'));
};

export const isCurrentMonth = (date: Date | string) => {
    return dayjs(date).isSame(dayjs(Date.now()), 'month');
};
