import { coloredToast } from '@/lib/toast';
import { useState } from 'react';

interface Bundling {
    promotion_name: string;
    promotion_start: Date;
    promotion_end: Date;
    promotion_is_active: boolean;
    promotion_case: Case[];
}

interface Case {
    id: number;
    master: [];
    product_item: [];
    bundling_type: string;
}

const validateInput = (bundlingForm: Bundling) => {
    if (!bundlingForm.promotion_name) {
        return 'Promotion name is required.';
    }

    if (!bundlingForm.promotion_start || !bundlingForm.promotion_end) {
        return 'Promotion start and end date is required.';
    } else {
        const startDate = new Date(bundlingForm.promotion_start);
        const endDate = new Date(bundlingForm.promotion_end);

        if (startDate > endDate) {
            return 'Start date is later than end date';
        }
    }
    if (!bundlingForm.promotion_case || bundlingForm.promotion_case.length <= 0) {
        return 'Please add at least 1 case to proceed';
    }

    return null;
};

export const SaveBundling = (bundlingForm: Bundling) => {
    const validationError = validateInput(bundlingForm);

    if (validationError) {
        coloredToast('warning', validationError);
        return { status: false };
    }

    const master = bundlingForm.promotion_case.flatMap((item) => item.master);
    const product_item = bundlingForm.promotion_case.flatMap((item) => item.product_item);
    const master_value = master.map((item: any) => item.value);
    const product_item_value = product_item.map((item: any) => item);

    const bundlingData = [
        {
            ...bundlingForm.promotion_case[0],
            master: master_value,
            product_item: product_item_value,
            bundling_type: 'label',
        },
    ];

    const data = {
        promotion_name: bundlingForm.promotion_name,
        promotion_start: bundlingForm.promotion_start,
        promotion_end: bundlingForm.promotion_end,
        promotion_is_active: bundlingForm.promotion_is_active,
        promotion_case: bundlingData,
    };

    return {
        status: true,
        data,
    };
};

// const formattedCase = (items: Case[]): Case[] => {
//     return items.filter((item: Case) => item.value > 0 && item.case_type !== '' && item.promo_value !== '').sort((a: Case, b: Case) => a.value - b.value);
// };
