import { coloredToast } from '@/lib/toast';
import { isSystemMetaKey, mapAdjustmentsToLegacy, UnifiedAdjustment } from './orderAdjustmentAdapter';

interface Billing {
    billing_name: string;
    billing_email: string;
    billing_phone: string;
}

interface Shipping {
    shipping_name: string;
    shipping_phone: string;
    shipping_address: string;
    shipping_province: string;
    shipping_city: string;
    shipping_kecamatan: string;
    shipping_kelurahan: string;
    shipping_postcode: string;
}

interface Item {
    id: number;
    item_id: string;
    product_image: string;
    product_title: string;
    product_url: string;
    product_sku: string;
    quantity: number;
    amount: number;
    attributes: string[];
    variation: Record<string, any> | null;
}

interface ShippingMethod {
    provider: string;
    service: string;
    price: number;
    tracking_code: string;
}

interface Discount {
    id: number;
    coupon_name: string;
    amount: number;
    free_item: string;
}

interface Meta {
    id: number;
    key: string;
    amount?: number;
    value?: string | boolean;
    name?: string;
    type?: string;
}

interface CustomMeta {
    id: number;
    key: string;
    value: string;
}

interface Payment {
    payment_code: string;
    name: string;
    acquire: string;
    payment_type: string;
}

interface OrderData {
    order_items: any[];
    order_voucher: any[];
    order_payment: any;
    order_shipment: any;
    sub_total: number;
    customer: {
        billing: {
            name: string;
            email: string;
            phone: string;
        };
        shipping: {
            name: string;
            phone: string;
            address: string;
            kelurahan: string;
            kecamatan: string;
            kota: string;
            provinsi: string;
            kodepos: string;
            negara: string;
        };
    };
    user_id: string;
    order_date: Date;
    order_status: string;
    meta_items: any[];
    custom_meta_items: any[];
    notes: string;
    admin_notes: string;
}

export const SaveOrder = (
    adminNotes: string,
    billing: Billing,
    orderDate: Date,
    paymentDate: any,
    shipping: Shipping,
    items: Item[],
    shippingMethod: ShippingMethod,
    discounts: Discount[],
    meta: Meta[],
    customMeta: CustomMeta[],
    orderStatus: string,
    paymentType: Payment,
    totalPrice: number,
    notes: string,
    userId: string,
    adjustments?: UnifiedAdjustment[]
) => {
    const normalizedData = adjustments && adjustments.length > 0 ? mapAdjustmentsToLegacy(adjustments) : { discounts, meta, customMeta };

    const validationError = validateInput(
        adminNotes,
        billing,
        orderDate,
        shipping,
        items,
        shippingMethod,
        normalizedData.discounts,
        normalizedData.meta,
        normalizedData.customMeta,
        orderStatus,
        paymentType,
        userId
    );

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

    const data: OrderData = {
        order_items: formattedItem(items),
        order_voucher: formattedDiscount(normalizedData.discounts),
        order_payment: { ...paymentType, payment_date: paymentDate },
        order_shipment: shippingMethod,
        sub_total: totalPrice,
        customer: {
            billing: {
                name: billing.billing_name,
                email: billing.billing_email,
                phone: billing.billing_phone,
            },
            shipping: {
                name: shipping.shipping_name,
                phone: shipping.shipping_phone,
                address: shipping.shipping_address,
                kelurahan: shipping.shipping_kelurahan,
                kecamatan: shipping.shipping_kecamatan,
                kota: shipping.shipping_city,
                provinsi: shipping.shipping_province,
                kodepos: shipping.shipping_postcode,
                negara: '',
            },
        },
        user_id: userId,
        order_date: orderDate,
        order_status: orderStatus,
        meta_items: formattedMetaItem(normalizedData.meta),
        custom_meta_items: formattedCustomMetaItem(normalizedData.customMeta),
        notes: notes,
        admin_notes: adminNotes,
    };

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

const validateInput = (
    adminNotes: string,
    billing: Billing,
    orderDate: Date,
    shipping: Shipping,
    items: Item[],
    shippingMethod: ShippingMethod,
    discounts: Discount[],
    meta: Meta[],
    customMeta: CustomMeta[],
    orderStatus: string,
    paymentType: Payment,
    userId: string
): string | null => {
   

    if (!billing.billing_name) {
        return 'Billing name is required.';
    }
    if (!billing.billing_email) {
        return 'Billing email is required.';
    }
    if (!billing.billing_email.includes('@')) {
        return 'Invalid billing email format.';
    }
    if (billing.billing_phone.length <= 7) {
        return 'Billing phone must have at least 8 characters.';
    }

    if (!orderDate) {
        return 'Order date must be selected.';
    }

    if (!shipping.shipping_name) {
        return 'Shipping name is required.';
    }

    if (shipping.shipping_phone.length <= 7) {
        return 'Shipping phone must have at least 8 characters.';
    }
    if (!shipping.shipping_address) {
        return 'Shipping address is required.';
    }
    if (!shipping.shipping_province) {
        return 'Shipping province is required.';
    }
    if (!shipping.shipping_city) {
        return 'Shipping city is required.';
    }
    if (!shipping.shipping_kecamatan) {
        return 'Shipping kecamatan is required.';
    }
    if (!shipping.shipping_kelurahan) {
        return 'Shipping kelurahan is required.';
    }
    if (!shipping.shipping_postcode) {
        return 'Shipping postcode is required.';
    }

    const qtyItem = items.reduce((total: number, item: Item) => total + item.quantity, 0);
    if (qtyItem <= 0 || !formattedItem(items).length) {
        return 'Please add at least 1 item to proceed';
    }

    if (!shippingMethod.provider) {
        return 'Shipping provider must be filled';
    }

    if (!checkDuplicateCouponName(formattedDiscount(discounts))) {
        return 'Cannot apply with same coupon name';
    }

    if (!checkDuplicateMetaKey(formattedMetaItem(meta))) {
        return 'Cannot add with same meta name';
    }

    if (!checkDuplicateCustomMetaKey(formattedCustomMetaItem(customMeta))) {
        return 'Cannot add with same custom meta name';
    }

    if (!orderStatus) {
        return 'Order status must be selected';
    }

    if (!paymentType.payment_code) {
        return 'Payment type must be selected';
    }

    // if add order = user id : '' and using point
    const point = countPoint(meta);

    if (!userId && point > 0) {
        return 'No user define, cannot using point';
    }

    return null;
};

const formattedItem = (items: any) => {
    return items
        .filter((item: any) => item.item_id !== '' && item.quantity > 0)
        .map((item: any) => {
            const product_id = item.item_id.split(' | ');
            let attribute_selected = generateAttributeValue(item);

            if (item.is_gift_card && item.variation && item.variation.Gift) {
                attribute_selected = { Gift: item.variation.Gift };
            }

            return {
                product_id: product_id[0],
                name: item.product_title,
                image: item.product_image,
                sku: item.product_sku,
                url: item.product_url,
                qty: item.quantity,
                price: item.amount,
                attribute_selected: attribute_selected,
                custom_text: item.custom_text,
                collect_in_store: item.click_n_collect?.store_name || '',
                pick_in_store_code: item.click_n_collect?.unique_code || '',
                is_gift_card: item.is_gift_card || false,
                is_free_item: item.is_free_item || false,
                gift_card_data: item.gift_card_data !== undefined ? item.gift_card_data : null,
                ...(item.promotion_id ? { promotion_id: item.promotion_id } : {}),
                ...(item.promotion_name ? { promotion_name: item.promotion_name } : {}),
                ...(item.promotion_case_id ? { promotion_case_id: item.promotion_case_id } : {}),
            };
        });
};
const generateAttributeValue = (item: any) => {
    if (item.attributes.length > 0) {
        const attributeValues: Record<string, any> = {};

        item.attributes.forEach((attr: string) => {
            let valueAttr = item.variation[attr];
            if (attr === 'color') {
                valueAttr = valueAttr.label || valueAttr; // Assign the label to valueAttr
            }

            attributeValues[attr] = valueAttr;
        });

        return attributeValues;
    }

    return {};
};

const formattedDiscount = (discounts: any) => {
    return discounts
        .filter((discount: any) => discount.coupon_name !== '')
        .map((discount: any) => {
            return {
                voucher: discount.coupon_name,
                amount: discount.amount,
                free_item: discount.free_item,
            };
        });
};
const formattedMetaItem = (meta: any) => {
    return meta
        .filter((item: any) => item.key !== '')
        .map((item: any) => {
            if (isSystemMetaKey(item.key)) {
                const rawValue = item.value;
                return {
                    key: item.key,
                    value: rawValue === true || rawValue === 'true' ? true : rawValue === false || rawValue === 'false' ? false : rawValue,
                };
            }

            const formatted: { key: string; amount: number; name?: string; type?: string } = {
                key: item.key,
                amount: item.amount || 0,
            };

            if (item.name) formatted.name = item.name;
            if (item.type) formatted.type = item.type;

            return formatted;
        });
};
const formattedCustomMetaItem = (customMeta: any) => {
    return customMeta
        .filter((meta: any) => meta.key !== '')
        .map((meta: any) => {
            return {
                key: meta.key,
                value: meta.value,
            };
        });
};
const checkDuplicateCouponName = (discounts: any[]): boolean => {
    const encounteredKeys = new Set();

    for (const discount of discounts) {
        if (encounteredKeys.has(discount.voucher)) {
            // Duplicate key found
            return false;
        }
        encounteredKeys.add(discount.voucher);
    }

    // No duplicate keys found
    return true;
};
const checkDuplicateMetaKey = (metas: any[]): boolean => {
    const encounteredKeys = new Set<string>();

    for (const meta of metas) {
        const metaType = String(meta.type || '').toLowerCase();
        const metaName = String(meta.name || '');
        const isPromotion = metaType === 'promotion' || metaName !== '';
        const duplicateKey = isPromotion ? `promotion:${meta.key}:${metaName}:${metaType || 'promotion'}` : `manual:${meta.key}`;

        if (encounteredKeys.has(duplicateKey)) {
            return false;
        }

        encounteredKeys.add(duplicateKey);
    }

    return true;
};
const checkDuplicateCustomMetaKey = (customMeta: any[]): boolean => {
    const encounteredKeys = new Set();

    for (const meta of customMeta) {
        if (encounteredKeys.has(meta.key)) {
            // Duplicate key found
            return false;
        }
        encounteredKeys.add(meta.key);
    }

    // No duplicate keys found
    return true;
};

const countPoint = (meta: any) => {
    return meta.reduce((total: number, item: any) => {
        if (item.key === 'point') {
            return total + item.amount;
        }
        return total;
    }, 0);
};
