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

interface Promotion {
    promotion_type: string;
    promotion_name: string;
    promotion_start: Date;
    promotion_end: Date;
    promotion_is_active: boolean;
    promotion_case: [];
    promotion_category: string;
    promotion_include_categories: [];
    promotion_exclude_categories: [];
    promotion_included_products: [];
    promotion_excluded_products: [];
    promotion_unique_users: [];
    promotion_merge_free_items: boolean;
    promotion_member_only?: boolean;
}

interface FreeItemValue {
    productId: string;
    active: boolean;
}

interface Case {
    id: number;
    value: number;
    case_type: string;
    promo_value: string | string[] | FreeItemValue[];
    max_discount?: number | string;
}

export const SavePromotion = (promotionForm: Promotion) => {
    const validationError = validateInput(promotionForm);

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

    const data = {
        promotion_type: promotionForm.promotion_type,
        promotion_name: promotionForm.promotion_name,
        promotion_start: promotionForm.promotion_start,
        promotion_end: promotionForm.promotion_end,
        promotion_is_active: promotionForm.promotion_is_active,
        promotion_case: formattedCase(promotionForm.promotion_case),
        promotion_category: promotionForm.promotion_category,
        promotion_include_categories: promotionForm.promotion_include_categories,
        promotion_exclude_categories: promotionForm.promotion_exclude_categories,
        promotion_included_products: promotionForm.promotion_included_products || [],
        promotion_excluded_products: promotionForm.promotion_excluded_products || [],
        promotion_merge_free_items: promotionForm.promotion_merge_free_items,
        promotion_member_only: Boolean(promotionForm.promotion_member_only),
    };

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

const validateInput = (promotionForm: Promotion): string | null => {
    if (!promotionForm.promotion_name) {
        return 'Promotion name is required.';
    }
    if (!promotionForm.promotion_type) {
        return 'Promotion type is required.';
    }

    // Check if there is at least one common element in categories
    const hasCommonCategory = promotionForm.promotion_include_categories.some((category) => promotionForm.promotion_exclude_categories.includes(category));
    if (hasCommonCategory) {
        return 'Product categories are included and excluded simultaneously.';
    }

    // Check if there is at least one common element in products
    const hasCommonProduct = promotionForm.promotion_included_products?.some((product) => promotionForm.promotion_excluded_products?.includes(product));
    if (hasCommonProduct) {
        return 'Products are included and excluded simultaneously.';
    }

    const startDate = new Date(promotionForm.promotion_start);
    const endDate = new Date(promotionForm.promotion_end);

    if (promotionForm.promotion_start && promotionForm.promotion_end) {
        if (startDate > endDate) {
            return 'Start date is later than end date';
        }
    }

    const promotion_case = formattedCase(promotionForm.promotion_case);
    if (promotion_case.length <= 0) {
        return 'Please add at least 1 case to proceed';
    }

    return null;
};
const formattedCase = (items: Case[]): Case[] => {
    return items
        .map((item: Case) => {
            if (item.case_type === 'free_item' && Array.isArray(item.promo_value)) {
                if (item.promo_value.length > 0 && typeof item.promo_value[0] === 'string') {
                    const freeItemValues: FreeItemValue[] = (item.promo_value as string[]).map((productId) => ({
                        productId,
                        active: true,
                    }));
                    return {
                        ...item,
                        promo_value: freeItemValues,
                    };
                }
                return item;
            }

            if (item.case_type === 'percentage_discount') {
                const maxDiscount = Number(item.max_discount) || 0;
                return {
                    ...item,
                    max_discount: maxDiscount > 0 ? maxDiscount : 0,
                };
            }

            const { max_discount: _unusedMax, ...rest } = item as Case & {
                max_discount?: number | string;
            };
            return rest;
        })
        .filter((item: Case) => {
            if (item.case_type === 'free_item') {
                return item.value > 0 && Array.isArray(item.promo_value) && item.promo_value.length > 0 && typeof item.promo_value[0] === 'object' && 'productId' in item.promo_value[0];
            }
            return item.value > 0 && item.case_type !== '' && item.promo_value !== '';
        })
        .sort((a: Case, b: Case) => a.value - b.value);
};
