import { useEffect, useMemo, useState } from 'react';
import {
    AdjustmentSourceType,
    emptyAdjustment,
    formatSystemMetaDisplayValue,
    SYSTEM_META_LABELS,
    UnifiedAdjustment,
} from '@/utils/orderAdjustmentAdapter';
import { coloredToast } from '@/lib/toast';
import {
    evaluatePromotionCases,
    promotionHasEligibleCase,
    type CaseEligibility,
} from '@/utils/promotionEligibility';
import {
    findUpgradeableManualFreeItem,
    isPromotionFreeItemCaseUsed,
    isSamePromotion,
    parsePromoValueProductIds,
    type FreeItemValue,
    type PromotionCaseForLink,
    type PromotionForLink,
} from '@/utils/orderPromotionLink';
import NumberFormatter from '@/lib/ribuan';

interface FreeItemOption {
    _id: string;
    productId: string;
    product_item_idx: number | null;
    product_title: string;
    product_qty?: number;
    attribute_selected?: Record<string, string>;
}

interface PromotionCase extends PromotionCaseForLink { }

interface Coupon {
    id?: string;
    _id?: string;
    coupon_name: string;
    coupon_amount: number;
    coupon_min_purchase: number;
    coupon_is_individual: boolean;
    coupon_is_unique_user?: boolean;
    coupon_unique_user?: string[];
}

export interface OrderItemRow {
    id: number;
    item_id: string;
    product_image: string;
    product_title: string;
    product_sku: string;
    product_url: string;
    quantity: number;
    amount: number;
    price?: number;
    attributes: any[];
    custom_text?: any;
    variation: null | any;
    is_gift_card?: boolean;
    is_free_item?: boolean;
    gift_card_data?: any;
    product?: string;
    product_categories?: string[];
    promotion_id?: string;
    promotion_name?: string;
    promotion_case_id?: number;
}

interface AdjustmentFormProps {
    adjustments: UnifiedAdjustment[];
    setAdjustments: React.Dispatch<React.SetStateAction<UnifiedAdjustment[]>>;
    items?: OrderItemRow[];
    setItems?: React.Dispatch<React.SetStateAction<OrderItemRow[]>>;
    order_status?: string;
    lockPointAdjustment?: boolean;
    userId?: string;
    promotions?: PromotionForLink[];
    isLoadingPromotions?: boolean;
}

const EligibilityCheckIcon = () => (
    <svg
        xmlns="http://www.w3.org/2000/svg"
        fill="none"
        viewBox="0 0 24 24"
        strokeWidth={1.5}
        stroke="currentColor"
        className="h-5 w-5 shrink-0"
        aria-hidden
    >
        <path strokeLinecap="round" strokeLinejoin="round" d="M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
    </svg>
);

const sourceTypeOptions: { value: AdjustmentSourceType; label: string }[] = [
    { value: 'voucher', label: 'Voucher' },
    { value: 'point', label: 'Point' },
    { value: 'extra_discount', label: 'Extra Discount' },
    { value: 'fee', label: 'Fee' },
    { value: 'tax', label: 'Tax' },
    { value: 'unique_code', label: 'Unique Code' },
    { value: 'custom_meta', label: 'Custom Meta' },
    { value: 'promotion', label: 'Promotion' },
];

const manualMetaSourceTypes: AdjustmentSourceType[] = ['point', 'extra_discount', 'fee', 'tax', 'unique_code'];

const isManualMetaSource = (sourceType: AdjustmentSourceType) => {
    return manualMetaSourceTypes.includes(sourceType);
};

const AdjustmentForm: React.FC<AdjustmentFormProps> = ({
    adjustments,
    setAdjustments,
    items = [],
    setItems,
    order_status = 'Processing',
    lockPointAdjustment = false,
    userId,
    promotions: promotionsProp,
    isLoadingPromotions: isLoadingPromotionsProp,
}) => {
    const isPointRowLocked = (row: UnifiedAdjustment) => lockPointAdjustment && row.source_type === 'point';
    const isSystemMetaRow = (row: UnifiedAdjustment) => row.source_type === 'system_meta';
    const hasAppliedVoucher = adjustments.some(
        (item) => item.source_type === 'voucher' && String(item.coupon_name || '').trim() !== ''
    );
    const isHiddenSystemMetaRow = (row: UnifiedAdjustment) => {
        if (!isSystemMetaRow(row)) return false;
        const key = row.meta_key || row.custom_key;
        if (key === 'campaign_v_id') return true;
        if (key === 'voucher_usage_applied') return !hasAppliedVoucher;
        return false;
    };
    const hasVisibleAdjustment = adjustments.some((row) => !isHiddenSystemMetaRow(row));
    const [selectedFreeItemProducts, setSelectedFreeItemProducts] = useState<Record<number, string>>({});
    const [freeItemOptionsByCase, setFreeItemOptionsByCase] = useState<Record<number, FreeItemOption[]>>({});

    const availableSourceTypeOptions = useMemo(() => {
        if (!lockPointAdjustment) return sourceTypeOptions;
        return sourceTypeOptions.filter((option) => option.value !== 'point');
    }, [lockPointAdjustment]);
    const [internalPromotions, setInternalPromotions] = useState<PromotionForLink[]>([]);
    const [internalLoadingPromotion, setInternalLoadingPromotion] = useState(true);
    const promotions = promotionsProp ?? internalPromotions;
    const isLoadingPromotion =
        isLoadingPromotionsProp !== undefined ? isLoadingPromotionsProp : internalLoadingPromotion;
    const [promotionsOpen, setPromotionsOpen] = useState(false);
    const [activeCoupons, setActiveCoupons] = useState<Coupon[]>([]);
    const [isLoadingCoupon, setIsLoadingCoupon] = useState(true);
    const [vouchersOpen, setVouchersOpen] = useState(false);

    const availableCoupons = useMemo(() => {
        return activeCoupons.filter((c) => {
            if (c.coupon_is_unique_user) {
                if (!userId) return false;
                if (Array.isArray(c.coupon_unique_user) && c.coupon_unique_user.includes(userId)) return false;
            }
            return true;
        });
    }, [activeCoupons, userId]);

    const cartSubTotal = useMemo(() => {
        return items.reduce((total, item) => {
            if (item.is_free_item) return total;
            return total + item.quantity * item.amount;
        }, 0);
    }, [items]);

    const couponMinPurchaseStatus = useMemo(() => {
        const map: Record<string, boolean> = {};
        availableCoupons.forEach(c => {
            const minPurchase = Number(c.coupon_min_purchase) || 0;
            map[c.coupon_name] = minPurchase <= 0 || cartSubTotal >= minPurchase;
        });
        return map;
    }, [availableCoupons, cartSubTotal]);

    const isCouponMinPurchaseMet = (couponName: string) => couponMinPurchaseStatus[couponName] ?? true;

    useEffect(() => {
        const fetchRunningCoupons = async () => {
            try {
                const api_url = process.env.API_URL;
                const response = await fetch(`${api_url}api/coupons/running`, {
                    method: 'GET',
                    headers: { 'Content-Type': 'application/json' },
                    credentials: 'include',
                });

                if (response.ok) {
                    const data = await response.json();
                    setActiveCoupons(Array.isArray(data) ? data : []);
                } else {
                    setActiveCoupons([]);
                }
            } catch (error) {
                console.error('Failed to fetch running coupons:', error);
                setActiveCoupons([]);
            }
            setIsLoadingCoupon(false);
        };

        fetchRunningCoupons();
    }, []);

    useEffect(() => {
        if (promotionsProp) {
            return;
        }

        const fetchRunningPromotions = async () => {
            try {
                const api_url = process.env.API_URL;
                const response = await fetch(`${api_url}api/promotions/running`, {
                    method: 'GET',
                    headers: { 'Content-Type': 'application/json' },
                    credentials: 'include',
                });

                if (response.ok) {
                    const data = await response.json();
                    setInternalPromotions(Array.isArray(data) ? data : []);
                } else {
                    setInternalPromotions([]);
                }
            } catch (error) {
                console.error('Failed to fetch running promotions:', error);
                setInternalPromotions([]);
            }

            setInternalLoadingPromotion(false);
        };

        fetchRunningPromotions();
    }, [promotionsProp]);

    useEffect(() => {
        if (!promotions.length) {
            setFreeItemOptionsByCase({});
            return;
        }

        const fetchFreeItemOptions = async () => {
            const api_url = process.env.API_URL;
            const nextOptions: Record<number, FreeItemOption[]> = {};

            for (const promo of promotions) {
                for (const pc of promo.promotion_case || []) {
                    if (pc.case_type !== 'free_item') continue;

                    const productIds = parsePromoValueProductIds(pc.promo_value);
                    if (!productIds.length) continue;

                    try {
                        const response = await fetch(`${api_url}api/products/free-item`, {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            credentials: 'include',
                            body: JSON.stringify({ productIds }),
                        });

                        if (response.ok) {
                            const data = await response.json();
                            nextOptions[pc.id] = Array.isArray(data) ? data : [];
                        }
                    } catch (error) {
                        console.error('Failed to fetch free item options:', error);
                    }
                }
            }

            setFreeItemOptionsByCase(nextOptions);

            setSelectedFreeItemProducts((prev) => {
                const updated = { ...prev };
                Object.entries(nextOptions).forEach(([caseId, options]) => {
                    const id = Number(caseId);
                    if (updated[id]) return;

                    const inStock = options.find((opt) => (opt.product_qty ?? 0) > 0);
                    if (options.length === 1 && inStock) {
                        updated[id] = inStock._id;
                    } else if (options.length > 1 && inStock) {
                        updated[id] = inStock._id;
                    }
                });
                return updated;
            });
        };

        void fetchFreeItemOptions();
    }, [promotions]);

    const nextId = useMemo(() => {
        if (!adjustments.length) return 1;
        return adjustments.reduce((max, row) => (row.id > max ? row.id : max), 0) + 1;
    }, [adjustments]);

    const eligibilityByPromoId = useMemo(() => {
        const map: Record<string, CaseEligibility[]> = {};
        promotions.forEach((promo) => {
            const id = String(promo.id || promo._id);
            map[id] = evaluatePromotionCases(promo, items);
        });
        return map;
    }, [promotions, items]);

    const promoCardHasActiveHighlight = (promoId: string, promo: PromotionForLink) => {
        const rows = eligibilityByPromoId[promoId] || [];
        if (!promotionHasEligibleCase(rows)) return false;

        return promo.promotion_case?.some((pc) => {
            const row = rows.find((e) => e.caseId === pc.id);
            return row?.eligible && !isPromotionCaseUsed(promoId, promo.promotion_name, pc);
        });
    };

    const addRow = () => {
        setAdjustments((prev) => [...prev, emptyAdjustment(nextId)]);
    };

    const removeRow = (id: number) => {
        setAdjustments((prev) => prev.filter((row) => row.id !== id));
    };

    const updateRow = (id: number, patch: Partial<UnifiedAdjustment>) => {
        setAdjustments((prev) =>
            prev.map((row) => {
                if (row.id !== id) return row;
                return { ...row, ...patch };
            })
        );
    };

    const handleSourceTypeChange = (id: number, sourceType: AdjustmentSourceType) => {
        setAdjustments((prev) =>
            prev.map((row) => {
                if (row.id !== id) return row;
                const metaKeyValue = isManualMetaSource(sourceType) ? sourceType : '';
                return {
                    ...emptyAdjustment(row.id),
                    source_type: sourceType,
                    meta_key: metaKeyValue,
                };
            })
        );
    };

    const getRowDuplicateKey = (row: UnifiedAdjustment) => {
        if (row.source_type === 'promotion') {
            const caseType = row.meta_key || row.promotion_case_type;
            if (!caseType) return '';
            return `promotion:${caseType}:${row.promotion_name || ''}`;
        }

        if (isManualMetaSource(row.source_type)) {
            return `manual:${row.source_type}`;
        }

        return '';
    };

    const getTypeLabel = (type?: string) => {
        switch (type) {
            case 'birthday':
                return 'Birthday';
            case 'qty_of_cart':
                return 'Qty of Cart';
            case 'subtotal_of_cart':
                return 'Subtotal of Cart';
            default:
                return type;
        }
    };

    const getCaseTypeLabel = (caseType: string) => {
        switch (caseType) {
            case 'extra_discount':
                return 'Extra Discount';
            case 'birthday_extra':
                return 'Birthday Discount';
            case 'free_item':
                return 'Free Item';
            default:
                return caseType;
        }
    };

    const getPromoValueDisplay = (pc: PromotionCaseForLink) => {
        if (pc.case_type === 'free_item') return 'Free Item';

        if (typeof pc.promo_value === 'string') {
            const num = Number(pc.promo_value);
            if (!isNaN(num)) return `Rp ${num.toLocaleString('id-ID')}`;
            return pc.promo_value;
        }

        return '-';
    };

    const getThresholdLabel = (type?: string) => {
        switch (type) {
            case 'qty_of_cart':
                return 'Min Qty';
            case 'subtotal_of_cart':
                return 'Min Subtotal';
            case 'birthday':
                return 'Value';
            default:
                return 'Min';
        }
    };

    const getNextAdjustmentId = (rows: UnifiedAdjustment[]) => {
        return rows.length ? rows.reduce((max, row) => (row.id > max ? row.id : max), 0) + 1 : 1;
    };

    const usedVoucherNames = useMemo(() => {
        return new Set(
            adjustments
                .filter((row) => row.source_type === 'voucher' && row.coupon_name !== '')
                .map((row) => row.coupon_name)
        );
    }, [adjustments]);

    const appliedIndividualCouponName = useMemo(() => {
        const matchedRow = adjustments.find((row) => {
            if (row.source_type !== 'voucher' || row.coupon_name === '') return false;
            return availableCoupons.some((coupon) => coupon.coupon_name === row.coupon_name && coupon.coupon_is_individual);
        });

        return matchedRow?.coupon_name || '';
    }, [adjustments, availableCoupons]);

    const visibleCoupons = useMemo(() => {
        return availableCoupons.filter((coupon) => !usedVoucherNames.has(coupon.coupon_name));
    }, [availableCoupons, usedVoucherNames]);

    const isCouponAlreadyUsed = (couponName: string) => usedVoucherNames.has(couponName);

    const isCouponAlreadyUsedByOtherRow = (couponName: string, rowId: number) => {
        return adjustments.some(
            (row) => row.id !== rowId && row.source_type === 'voucher' && row.coupon_name === couponName
        );
    };

    const getAppliedIndividualCouponNameByOtherRow = (rowId: number) => {
        const matchedRow = adjustments.find((row) => {
            if (row.id === rowId || row.source_type !== 'voucher' || row.coupon_name === '') return false;
            return availableCoupons.some((coupon) => coupon.coupon_name === row.coupon_name && coupon.coupon_is_individual);
        });

        return matchedRow?.coupon_name || '';
    };

    const isCouponBlockedByStacking = (coupon: Coupon) => {
        const hasOtherVoucher = adjustments.some(
            (row) => row.source_type === 'voucher' && row.coupon_name !== '' && row.coupon_name !== coupon.coupon_name
        );

        if (coupon.coupon_is_individual && hasOtherVoucher) return true;
        if (appliedIndividualCouponName && appliedIndividualCouponName !== coupon.coupon_name) return true;

        return false;
    };

    const getVoucherStackingMessage = (coupon: Coupon) => {
        if (coupon.coupon_is_individual) return 'Voucher ini tidak bisa digabung dengan voucher lain';
        if (appliedIndividualCouponName) return `Tidak bisa dipakai karena voucher ${appliedIndividualCouponName} bersifat individual`;
        return 'Voucher ini bisa digabung dengan voucher lain';
    };

    const handleVoucherNameInputChange = (row: UnifiedAdjustment, value: string) => {
        const couponName = value.toUpperCase();

        if (couponName === '') {
            updateRow(row.id, { coupon_name: '', amount: 0 });
            return;
        }

        const matchedCoupon = availableCoupons.find((coupon) => coupon.coupon_name === couponName);

        if (!matchedCoupon) {
            updateRow(row.id, { coupon_name: couponName });
            return;
        }

        if (isCouponAlreadyUsedByOtherRow(couponName, row.id)) {
            coloredToast('warning', `Voucher ${couponName} sudah dipakai`);
            return;
        }

        const appliedIndividualByOtherRow = getAppliedIndividualCouponNameByOtherRow(row.id);
        const hasOtherVoucher = adjustments.some(
            (otherRow) => otherRow.id !== row.id && otherRow.source_type === 'voucher' && otherRow.coupon_name !== ''
        );

        if (matchedCoupon.coupon_is_individual && hasOtherVoucher) {
            coloredToast('warning', 'Voucher ini tidak bisa digabung dengan voucher lain');
            return;
        }

        if (appliedIndividualByOtherRow && appliedIndividualByOtherRow !== couponName) {
            coloredToast('warning', `Tidak bisa dipakai karena voucher ${appliedIndividualByOtherRow} bersifat individual`);
            return;
        }

        updateRow(row.id, {
            coupon_name: couponName,
            amount: Number(matchedCoupon.coupon_amount) || 0,
        });
    };

    const hasAnyVoucherHighlight = useMemo(() => {
        return visibleCoupons.some((coupon) => isCouponMinPurchaseMet(coupon.coupon_name) && !isCouponBlockedByStacking(coupon));
    }, [visibleCoupons, couponMinPurchaseStatus, adjustments, appliedIndividualCouponName]);

    const isPromotionAlreadyUsed = (promotionId: string, promotionName: string) => {
        const usedInAdjustments = adjustments.some(
            (row) => row.source_type === 'promotion' && isSamePromotion(row.promotion_id, row.promotion_name, promotionId, promotionName)
        );

        const usedInItems = items.some(
            (item) => item.is_free_item && isSamePromotion(item.promotion_id, item.promotion_name, promotionId, promotionName)
        );

        return usedInAdjustments || usedInItems;
    };

    const isPromotionCaseUsed = (promotionId: string, promotionName: string, promotionCase: PromotionCaseForLink) => {
        const caseType = promotionCase.case_type;
        const parsedAmount = typeof promotionCase.promo_value === 'string' ? Number(promotionCase.promo_value) : 0;
        const caseAmount = caseType === 'free_item' ? 0 : isNaN(parsedAmount) ? 0 : parsedAmount;

        if (caseType === 'free_item') {
            return isPromotionFreeItemCaseUsed(items, promotionId, promotionName, promotionCase);
        }

        return adjustments.some((row) => {
            if (row.source_type !== 'promotion') return false;
            if (!isSamePromotion(row.promotion_id, row.promotion_name, promotionId, promotionName)) return false;

            const rowCaseType = row.promotion_case_type || row.meta_key;
            if (rowCaseType !== caseType) return false;

            if (row.promotion_case_id && promotionCase.id) {
                return row.promotion_case_id === promotionCase.id;
            }

            if (caseType === 'birthday_extra') return true;

            return (Number(row.amount) || 0) === caseAmount;
        });
    };

    const hasAnyPromoHighlight = useMemo(() => {
        return promotions.some((promo) => {
            const promoId = promo.id || promo._id;
            const promoIdStr = String(promoId);
            const rows = eligibilityByPromoId[promoIdStr] || [];
            if (!promotionHasEligibleCase(rows)) return false;

            return promo.promotion_case?.some((pc) => {
                const row = rows.find((e) => e.caseId === pc.id);
                return row?.eligible && !isPromotionCaseUsed(promoIdStr, promo.promotion_name, pc);
            });
        });
    }, [promotions, eligibilityByPromoId, items, adjustments]);

    const buildOrderItemFromSelected = (
        data: any,
        productId: string,
        productItemIdx: number | string | null,
        promotion: PromotionForLink,
        promotionCase: PromotionCaseForLink
    ): OrderItemRow => {
        const variation = data.variation || null;
        let attributes: string[] = [];
        let image = data.product_images?.[0] || '';

        if (variation?.attributes) {
            attributes = variation.attributes.map((attr: any) => attr.name);
            image = variation.image || image;

            const attributeObject = variation.attributes.reduce((result: any, attribute: any) => {
                result[attribute.name] = attribute.value?.label || attribute.value;
                return result;
            }, {});

            Object.assign(variation, attributeObject);
        }

        const hasItemIdx = productItemIdx !== null && productItemIdx !== '' && productItemIdx !== undefined;
        const itemId = hasItemIdx ? `${productId} | ${productItemIdx}` : productId;

        return {
            id: 0,
            item_id: itemId,
            product: productId,
            product_categories: data.product_categories || [],
            product_image: image,
            product_title: data.product_title || '',
            product_sku: data.product_sku || '',
            product_url: data.product_url || '',
            quantity: 1,
            amount: 0,
            price: data.product_price || 0,
            attributes,
            variation,
            custom_text: {},
            is_gift_card: false,
            is_free_item: true,
            gift_card_data: null,
            promotion_id: String(promotion.id || promotion._id || ''),
            promotion_name: promotion.promotion_name,
            promotion_case_id: promotionCase.id,
        };
    };

    const addPromotionFreeItem = async (promotion: PromotionForLink, promotionCase: PromotionCaseForLink) => {
        if (!setItems) {
            coloredToast('warning', 'Item form is not available');
            return;
        }

        const productIds = parsePromoValueProductIds(promotionCase.promo_value);
        if (!productIds.length) {
            coloredToast('warning', 'No free item products configured for this promotion');
            return;
        }

        const options = freeItemOptionsByCase[promotionCase.id] || [];
        const selectedOptionId =
            selectedFreeItemProducts[promotionCase.id] || (options.length === 1 ? options[0]?._id : productIds.length === 1 && !options.length ? productIds[0] : '');

        if (!selectedOptionId) {
            coloredToast('warning', 'Select a free item product first');
            return;
        }

        const selectedOpt = options.find((opt) => opt._id === selectedOptionId);
        if (selectedOpt && (selectedOpt.product_qty ?? 0) <= 0) {
            coloredToast('warning', 'Selected free item is out of stock');
            return;
        }

        const product_id = selectedOpt?.productId || selectedOptionId;
        const product_item_idx =
            selectedOpt?.product_item_idx != null ? String(selectedOpt.product_item_idx) : '';

        try {
            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/products/order-item-selected`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
                body: JSON.stringify({
                    product_id,
                    product_item_idx,
                }),
            });

            if (!response.ok) {
                coloredToast('warning', 'Failed to load free item product');
                return;
            }

            const data = await response.json();

            if (!data?.product_title) {
                coloredToast('warning', 'Free item product not found');
                return;
            }

            const newItem = buildOrderItemFromSelected(
                data,
                product_id,
                product_item_idx !== '' ? product_item_idx : null,
                promotion,
                promotionCase
            );

            setItems((prev) => {
                const existing = findUpgradeableManualFreeItem(
                    prev,
                    product_id,
                    product_item_idx !== '' ? product_item_idx : null
                );

                if (existing) {
                    return prev.map((row) =>
                        row.id === existing.id
                            ? {
                                ...row,
                                ...newItem,
                                id: existing.id,
                                quantity: row.quantity > 0 ? row.quantity : 1,
                            }
                            : row
                    );
                }

                const nextId = prev.length ? prev.reduce((max, row) => (row.id > max ? row.id : max), 0) + 1 : 1;
                return [...prev, { ...newItem, id: nextId }];
            });
        } catch (error) {
            console.error('Failed to add promotion free item:', error);
            coloredToast('danger', 'Failed to add free item');
        }
    };

    const addPromotionCase = (promotion: PromotionForLink, promotionCase: PromotionCaseForLink) => {
        if (promotionCase.case_type === 'free_item') {
            void addPromotionFreeItem(promotion, promotionCase);
            return;
        }

        if (promotionCase.case_type !== 'extra_discount' && promotionCase.case_type !== 'birthday_extra') {
            return;
        }

        const parsedAmount = typeof promotionCase.promo_value === 'string' ? Number(promotionCase.promo_value) : 0;
        const promotionId = String(promotion.id || promotion._id || '');

        setAdjustments((prev) => [
            ...prev,
            {
                id: getNextAdjustmentId(prev),
                source_type: 'promotion',
                coupon_name: '',
                amount: isNaN(parsedAmount) ? 0 : parsedAmount,
                free_item: '',
                meta_key: promotionCase.case_type,
                custom_key: '',
                custom_value: '',
                promotion_name: promotion.promotion_name,
                promotion_case_type: promotionCase.case_type,
                promotion_id: promotionId,
                promotion_case_id: promotionCase.id,
                promotion_case_value: Number(promotionCase.value) || 0,
            },
        ]);
    };

    const addVoucherCoupon = (coupon: Coupon) => {
        if (order_status !== 'Processing') return;

        if (isCouponAlreadyUsed(coupon.coupon_name)) {
            coloredToast('warning', `Voucher ${coupon.coupon_name} sudah dipakai`);
            return;
        }

        if (!isCouponMinPurchaseMet(coupon.coupon_name)) {
            coloredToast(
                'warning',
                `Voucher ${coupon.coupon_name} membutuhkan minimal pembelian Rp ${Number(coupon.coupon_min_purchase).toLocaleString('id-ID')}`
            );
            return;
        }

        if (isCouponBlockedByStacking(coupon)) {
            coloredToast('warning', getVoucherStackingMessage(coupon));
            return;
        }

        setAdjustments((prev) => [
            ...prev,
            {
                ...emptyAdjustment(getNextAdjustmentId(prev)),
                source_type: 'voucher',
                coupon_name: coupon.coupon_name,
                amount: Number(coupon.coupon_amount) || 0,
            },
        ]);
    };

    return (
        <>
            {(!isLoadingPromotion || !isLoadingCoupon) && (promotions.length > 0 || visibleCoupons.length > 0) && (
                <div className="mx-2 flex flex-col gap-2 lg:flex-row lg:items-start">
                    {promotions.length > 0 && (
                        <div className="mt-4 w-4/6 self-start rounded-lg border border-dashed border-primary bg-primary-light dark:bg-primary/10">
                            <button
                                type="button"
                                className="flex w-full items-center justify-between gap-3 p-4 text-left"
                                onClick={() => setPromotionsOpen((open) => !open)}
                                aria-expanded={promotionsOpen}
                            >
                                <div className="flex min-w-0 flex-1 items-center gap-2">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="shrink-0 text-primary">
                                        <path d="M20.59 13.41l-7.17 7.17a2 2 0 01-2.83 0L2 12V2h10l8.59 8.59a2 2 0 010 2.82z" />
                                        <line x1="7" y1="7" x2="7.01" y2="7" />
                                    </svg>
                                    <span className="font-semibold text-primary">Promosi Aktif</span>
                                    <span className="inline-flex items-center gap-1.5 rounded-full bg-primary/15 px-2 py-0.5 text-xs font-medium text-primary">
                                        {promotions.length}
                                        {hasAnyPromoHighlight && (
                                            <span className="relative flex h-2 w-2 shrink-0">
                                                <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-success opacity-75" />
                                                <span className="relative inline-flex h-2 w-2 rounded-full bg-success" />
                                            </span>
                                        )}
                                    </span>
                                </div>
                                <svg
                                    xmlns="http://www.w3.org/2000/svg"
                                    width="18"
                                    height="18"
                                    viewBox="0 0 24 24"
                                    fill="none"
                                    stroke="currentColor"
                                    strokeWidth="2"
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    className={`shrink-0 text-primary transition-transform duration-300 ease-out ${promotionsOpen ? 'rotate-180' : ''}`}
                                >
                                    <polyline points="6 9 12 15 18 9" />
                                </svg>
                            </button>

                            <div
                                className="grid transition-[grid-template-rows] duration-300 ease-out"
                                style={{ gridTemplateRows: promotionsOpen ? '1fr' : '0fr' }}
                                aria-hidden={!promotionsOpen}
                            >
                                <div className="min-h-0 overflow-hidden">
                                    <div
                                        className={`flex flex-col gap-3 border-t border-primary/20 px-4 pb-4 pt-3 transition-[opacity,transform] duration-300 ease-out ${promotionsOpen ? 'translate-y-0 opacity-100' : 'pointer-events-none -translate-y-1 opacity-0'
                                            }`}
                                    >
                                        {promotions.map((promo) => {
                                            const promoId = promo.id || promo._id;
                                            const promoIdStr = String(promoId);
                                            const cardHighlighted = promoCardHasActiveHighlight(promoIdStr, promo);

                                            return (
                                                <div
                                                    key={promoId}
                                                    className="rounded-md border border-white-light bg-white p-3 dark:border-[#1b2e4b] dark:bg-[#0e1726]"
                                                >
                                                    <div className="mb-2 flex flex-wrap items-center justify-between gap-2">
                                                        <div className="flex flex-wrap items-center gap-2">
                                                            <span className="font-semibold">{promo.promotion_name}</span>
                                                            <span className="rounded bg-primary/20 px-2 py-0.5 text-xs font-medium text-primary">{getTypeLabel(promo.promotion_type)}</span>
                                                            {cardHighlighted && (
                                                                <span className="rounded bg-success/15 px-2 py-0.5 text-xs font-medium text-success">Siap dipakai</span>
                                                            )}
                                                        </div>
                                                    </div>

                                                    <div className="text-xs text-gray-500 dark:text-gray-400">
                                                        {promo.promotion_start && promo.promotion_end
                                                            ? `${new Date(promo.promotion_start).toLocaleDateString('id-ID')} - ${new Date(promo.promotion_end).toLocaleDateString('id-ID')}`
                                                            : ''}
                                                    </div>

                                                    {(promo.promotion_case?.length ?? 0) > 0 && (
                                                        <div className="mt-2">
                                                            <table className="w-full text-sm">
                                                                <thead>
                                                                    <tr className="border-b border-white-light text-left text-xs text-gray-500 dark:border-[#1b2e4b] dark:text-gray-400">
                                                                        <th className="py-1">{getThresholdLabel(promo.promotion_type)}</th>
                                                                        <th className="py-1">Type</th>
                                                                        <th className="py-1">Value</th>
                                                                        <th className="py-1 w-[min(280px,38%)] text-right">Aksi</th>
                                                                    </tr>
                                                                </thead>
                                                                <tbody>
                                                                    {(promo.promotion_case || []).map((pc) => {
                                                                        const productIds =
                                                                            pc.case_type === 'free_item' ? parsePromoValueProductIds(pc.promo_value) : [];
                                                                        const freeItemOptions = pc.case_type === 'free_item' ? freeItemOptionsByCase[pc.id] || [] : [];
                                                                        const showFreeItemPicker =
                                                                            pc.case_type === 'free_item' &&
                                                                            (freeItemOptions.length > 1 ||
                                                                                (freeItemOptions.length === 1 && (freeItemOptions[0].product_qty ?? 0) <= 0) ||
                                                                                (freeItemOptions.length === 0 && productIds.length > 0));
                                                                        const isUsed = isPromotionCaseUsed(promoIdStr, promo.promotion_name, pc);
                                                                        const isBlocked = isPromotionAlreadyUsed(promoIdStr, promo.promotion_name) && !isUsed;
                                                                        const caseEligibility = (eligibilityByPromoId[promoIdStr] || []).find((e) => e.caseId === pc.id);
                                                                        const showCaseHighlight = caseEligibility?.eligible && !isUsed;
                                                                        const canAddCase =
                                                                            pc.case_type === 'extra_discount' ||
                                                                            pc.case_type === 'birthday_extra' ||
                                                                            pc.case_type === 'free_item';

                                                                        return (
                                                                            <tr
                                                                                key={pc.id}
                                                                                className={`border-b border-white-light last:border-0 dark:border-[#1b2e4b] ${showCaseHighlight
                                                                                    ? 'bg-success/10 dark:bg-success/15'
                                                                                    : 'bg-white dark:bg-[#0e1726]'
                                                                                    }`}
                                                                            >
                                                                                <td className="py-1.5 align-top">
                                                                                    <div className="flex flex-wrap items-center gap-1.5">
                                                                                        <span>
                                                                                            {promo.promotion_type === 'subtotal_of_cart'
                                                                                                ? `Rp ${Number(pc.value).toLocaleString('id-ID')}`
                                                                                                : pc.value}
                                                                                        </span>
                                                                                        {showCaseHighlight && (
                                                                                            <span className="inline-flex text-success" title="Memenuhi syarat">
                                                                                                <EligibilityCheckIcon />
                                                                                            </span>
                                                                                        )}
                                                                                    </div>
                                                                                </td>
                                                                                <td className="py-1.5 align-top">{getCaseTypeLabel(pc.case_type)}</td>
                                                                                <td className="py-1.5 align-top">{getPromoValueDisplay(pc)}</td>
                                                                                <td className="py-1.5 align-middle">
                                                                                    {canAddCase && (
                                                                                        <div className="flex flex-row flex-wrap items-center justify-end gap-2">
                                                                                            {showFreeItemPicker && (
                                                                                                <select
                                                                                                    className="form-select min-w-[12rem] max-w-full flex-1 py-1 text-xs sm:min-w-[14rem]"
                                                                                                    disabled={isUsed || isBlocked || order_status !== 'Processing'}
                                                                                                    value={selectedFreeItemProducts[pc.id] || ''}
                                                                                                    onChange={(e) =>
                                                                                                        setSelectedFreeItemProducts((prev) => ({
                                                                                                            ...prev,
                                                                                                            [pc.id]: e.target.value,
                                                                                                        }))
                                                                                                    }
                                                                                                >
                                                                                                    <option value="">Pilih free item</option>
                                                                                                    {(freeItemOptions.length > 0
                                                                                                        ? freeItemOptions
                                                                                                        : productIds.map((id) => ({ _id: id, product_title: id, product_qty: 0 }))
                                                                                                    ).map((opt) => (
                                                                                                        <option key={opt._id} value={opt._id} disabled={(opt.product_qty ?? 0) <= 0}>
                                                                                                            {opt.product_title}
                                                                                                            {(opt.product_qty ?? 0) <= 0 ? ' (Out of Stock)' : ''}
                                                                                                        </option>
                                                                                                    ))}
                                                                                                </select>
                                                                                            )}
                                                                                            <button
                                                                                                type="button"
                                                                                                disabled={isUsed || isBlocked || order_status !== 'Processing'}
                                                                                                className="btn btn-outline-primary btn-sm shrink-0 whitespace-nowrap px-3 py-1 text-xs disabled:cursor-not-allowed disabled:opacity-50"
                                                                                                onClick={() => addPromotionCase(promo, pc)}
                                                                                            >
                                                                                                {isUsed ? 'Used' : isBlocked ? 'Unavailable' : '+ Add'}
                                                                                            </button>
                                                                                        </div>
                                                                                    )}
                                                                                </td>
                                                                            </tr>
                                                                        );
                                                                    })}
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                    )}
                                                </div>
                                            );
                                        })}
                                    </div>
                                </div>
                            </div>
                        </div>
                    )}

                    <div className="mt-4 w-2/6 self-start rounded-lg border border-dashed border-primary bg-primary-light dark:bg-primary/10">
                        <button
                            type="button"
                            className="flex w-full items-center justify-between gap-3 p-4 text-left"
                            onClick={() => setVouchersOpen((open) => !open)}
                            aria-expanded={vouchersOpen}
                        >
                            <div className="flex min-w-0 flex-1 items-center gap-2">
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" height="20" width="20" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" className="w-6 text-primary">
                                    <path strokeLinecap="round" strokeLinejoin="round" d="M12 6v12m-3-2.818.879.659c1.171.879 3.07.879 4.242 0 1.172-.879 1.172-2.303 0-3.182C13.536 12.219 12.768 12 12 12c-.725 0-1.45-.22-2.003-.659-1.106-.879-1.106-2.303 0-3.182s2.9-.879 4.006 0l.415.33M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
                                </svg>

                                <span className="font-semibold text-primary">Voucher Aktif</span>
                                <span className="inline-flex items-center gap-1.5 rounded-full bg-primary/15 px-2 py-0.5 text-xs font-medium text-primary">
                                    {visibleCoupons.length}
                                    {hasAnyVoucherHighlight && (
                                        <span className="relative flex h-2 w-2 shrink-0">
                                            <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-success opacity-75" />
                                            <span className="relative inline-flex h-2 w-2 rounded-full bg-success" />
                                        </span>
                                    )}
                                </span>
                            </div>
                            <svg
                                xmlns="http://www.w3.org/2000/svg"
                                width="18"
                                height="18"
                                viewBox="0 0 24 24"
                                fill="none"
                                stroke="currentColor"
                                strokeWidth="2"
                                strokeLinecap="round"
                                strokeLinejoin="round"
                                className={`shrink-0 text-primary transition-transform duration-300 ease-out ${vouchersOpen ? 'rotate-180' : ''}`}
                            >
                                <polyline points="6 9 12 15 18 9" />
                            </svg>
                        </button>

                        <div
                            className="grid transition-[grid-template-rows] duration-300 ease-out"
                            style={{ gridTemplateRows: vouchersOpen ? '1fr' : '0fr' }}
                            aria-hidden={!vouchersOpen}
                        >
                            <div className="min-h-0 overflow-hidden">
                                <div
                                    className={`flex flex-col gap-3 border-t border-primary/20 px-4 pb-4 pt-3 transition-[opacity,transform] duration-300 ease-out ${vouchersOpen ? 'translate-y-0 opacity-100' : 'pointer-events-none -translate-y-1 opacity-0'
                                        }`}
                                >
                                    {visibleCoupons.length > 0 ? (
                                        visibleCoupons.map((coupon) => {
                                            const minPurchase = Number(coupon.coupon_min_purchase) || 0;
                                            const minMet = isCouponMinPurchaseMet(coupon.coupon_name);
                                            const blockedByStacking = isCouponBlockedByStacking(coupon);
                                            const canApply = order_status === 'Processing' && minMet && !blockedByStacking;

                                            return (
                                                <div
                                                    key={coupon._id || coupon.id || coupon.coupon_name}
                                                    className={`rounded-md border border-white-light bg-white p-3 dark:border-[#1b2e4b] dark:bg-[#0e1726] ${canApply ? 'ring-1 ring-success/30' : ''}`}
                                                >
                                                    <div className="mb-2 flex flex-wrap items-start justify-between gap-2">
                                                        <div className="min-w-0">
                                                            <div className="flex flex-wrap items-center gap-2">
                                                                <span className="font-semibold">{coupon.coupon_name}</span>
                                                                <span className="rounded bg-primary/20 px-2 py-0.5 text-xs font-medium text-primary">
                                                                    Rp {Number(coupon.coupon_amount || 0).toLocaleString('id-ID')}
                                                                </span>
                                                                <span
                                                                    className={`rounded px-2 py-0.5 text-xs font-medium ${coupon.coupon_is_individual
                                                                        ? 'bg-warning/15 text-warning'
                                                                        : 'bg-success/15 text-success'
                                                                        }`}
                                                                >
                                                                    {coupon.coupon_is_individual ? 'Non-stacking' : 'Stackable'}
                                                                </span>
                                                                {canApply && (
                                                                    <span className="inline-flex text-success" title="Siap dipakai">
                                                                        <EligibilityCheckIcon />
                                                                    </span>
                                                                )}
                                                            </div>
                                                            <div className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                                                {minPurchase > 0
                                                                    ? `Min. pembelian Rp ${minPurchase.toLocaleString('id-ID')}`
                                                                    : 'Tanpa minimum pembelian'}
                                                            </div>
                                                        </div>

                                                        <button
                                                            type="button"
                                                            className="btn btn-outline-primary btn-sm shrink-0 whitespace-nowrap px-3 py-1 text-xs disabled:cursor-not-allowed disabled:opacity-50"
                                                            disabled={!canApply}
                                                            onClick={() => addVoucherCoupon(coupon)}
                                                        >
                                                            + Add
                                                        </button>
                                                    </div>



                                                    {minMet && blockedByStacking && (
                                                        <p className="text-xs text-orange-500">{getVoucherStackingMessage(coupon)}</p>
                                                    )}
                                                </div>
                                            );
                                        })
                                    ) : (
                                        <p className="text-sm text-gray-500 dark:text-gray-400">Tidak ada voucher aktif yang bisa ditampilkan.</p>
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {hasVisibleAdjustment && (
                <div className="m-2 rounded-md border border-white-light py-4 dark:border-[#1b2e4b]">
                    <div className="ms-4">
                        <label htmlFor="unified_adjustment" className="mb-0 font-bold uppercase ltr:mr-2 rtl:ml-2">
                            Add Adjustment
                        </label>
                        {lockPointAdjustment && (
                            <p className="mt-1 text-xs italic text-gray-500 dark:text-gray-400">Point tidak bisa diubah setelah order dibuat.</p>
                        )}
                    </div>

                    {adjustments.map((row) => {
                        if (isHiddenSystemMetaRow(row)) return null;
                        return (
                        <div className="ms-4 mt-2" key={row.id}>
                            <div className="mt-4 flex flex-wrap items-end gap-4">
                                <div className="w-52">
                                    <label htmlFor={`source_type_${row.id}`}>source type</label>
                                    {isSystemMetaRow(row) ? (
                                        <input id={`source_type_${row.id}`} type="text" className="form-input" disabled value="System Meta" />
                                    ) : (
                                        <select
                                            id={`source_type_${row.id}`}
                                            className={`form-select ${getRowDuplicateKey(row) !== '' &&
                                                adjustments.some((d) => d.id !== row.id && getRowDuplicateKey(d) === getRowDuplicateKey(row))
                                                ? 'border-2 !border-rose-400'
                                                : ''
                                                }`}
                                            disabled={order_status !== 'Processing' || row.source_type === 'promotion' || isPointRowLocked(row)}
                                            value={row.source_type}
                                            onChange={(e) => handleSourceTypeChange(row.id, e.target.value as AdjustmentSourceType)}
                                        >
                                            {(isPointRowLocked(row) ? sourceTypeOptions : availableSourceTypeOptions).map((option) => (
                                                <option key={option.value} value={option.value}>
                                                    {option.label}
                                                </option>
                                            ))}
                                        </select>
                                    )}
                                </div>

                                {(row.source_type === 'voucher' || row.source_type === 'promotion') && (
                                    <>
                                        <div className="w-1/3">
                                            <label htmlFor={`voucher_name_${row.id}`} className="mb-1 block">
                                                {row.source_type === 'promotion' ? 'promotion name' : 'voucher name'}
                                            </label>
                                            <input
                                                id={`voucher_name_${row.id}`}
                                                type="text"
                                                className={`form-input uppercase ${row.source_type === 'voucher' && row.coupon_name && !isCouponMinPurchaseMet(row.coupon_name) ? '!border-orange-400' : ''}`}
                                                disabled={order_status !== 'Processing' || row.source_type === 'promotion'}
                                                placeholder={row.source_type === 'voucher' ? 'VOUCHER CUSTOM' : ''}
                                                value={
                                                    row.source_type === 'promotion'
                                                        ? row.promotion_name || getCaseTypeLabel(row.promotion_case_type || row.meta_key)
                                                        : row.coupon_name
                                                }
                                                onChange={(e) => {
                                                    handleVoucherNameInputChange(row, e.target.value);
                                                }}
                                            />
                                            {row.source_type === 'voucher' && row.coupon_name && !isCouponMinPurchaseMet(row.coupon_name) && (() => {
                                                const selectedCoupon = availableCoupons.find((c) => c.coupon_name === row.coupon_name);
                                                return selectedCoupon ? (
                                                    <p className="mt-1 text-xs text-orange-500">
                                                        Min. pembelian Rp {Number(selectedCoupon.coupon_min_purchase).toLocaleString('id-ID')} (subtotal: Rp {cartSubTotal.toLocaleString('id-ID')})
                                                    </p>
                                                ) : null;
                                            })()}
                                        </div>
                                        <div className="w-52">
                                            <label htmlFor={`voucher_amount_${row.id}`}>{row.source_type === 'promotion' ? 'promotion amount' : 'coupon amount'}</label>
                                            <NumberFormatter
                                                id={`voucher_amount_${row.id}`}
                                                className="form-input"
                                                disabled={order_status !== 'Processing' || row.source_type === 'promotion'}
                                                value={row.amount}
                                                onChange={(value: number) => updateRow(row.id, { amount: value })}
                                            />
                                        </div>
                                    </>
                                )}
                                {isManualMetaSource(row.source_type) && (
                                    <div className="w-52">
                                        <label htmlFor={`meta_amount_${row.id}`}>meta amount</label>
                                        <NumberFormatter
                                            id={`meta_amount_${row.id}`}
                                            className="form-input"
                                            disabled={order_status !== 'Processing' || isPointRowLocked(row)}
                                            value={row.amount}
                                            onChange={(value: number) => updateRow(row.id, { amount: value })}
                                        />
                                        {isPointRowLocked(row) && (
                                            <p className="mt-1 text-xs italic text-gray-500 dark:text-gray-400">Point terkunci (read-only).</p>
                                        )}
                                    </div>
                                )}


                                {isSystemMetaRow(row) && (
                                    <>
                                        <div className="w-72">
                                            <label htmlFor={`system_meta_label_${row.id}`}>meta name</label>
                                            <input
                                                id={`system_meta_label_${row.id}`}
                                                type="text"
                                                className="form-input"
                                                disabled
                                                value={SYSTEM_META_LABELS[row.meta_key] || row.meta_key}
                                            />
                                        </div>
                                        <div className="w-72">
                                            <label htmlFor={`system_meta_value_${row.id}`}>value</label>
                                            <input
                                                id={`system_meta_value_${row.id}`}
                                                type="text"
                                                className="form-input"
                                                disabled
                                                readOnly
                                                value={formatSystemMetaDisplayValue(row.meta_key, row.custom_value)}
                                            />
                                        </div>
                                    </>
                                )}

                                {row.source_type === 'custom_meta' && (
                                    <>
                                        <div className="w-52">
                                            <label htmlFor={`custom_meta_key_${row.id}`}>custom meta name</label>
                                            <input
                                                id={`custom_meta_key_${row.id}`}
                                                type="text"
                                                className={`form-input ${adjustments.some((d) => d.id !== row.id && d.source_type === 'custom_meta' && d.custom_key === row.custom_key && row.custom_key !== '')
                                                    ? 'border-2 !border-rose-400'
                                                    : ''
                                                    }`}
                                                disabled={order_status !== 'Processing'}
                                                value={row.custom_key}
                                                onChange={(e) => updateRow(row.id, { custom_key: e.target.value })}
                                            />
                                        </div>
                                        <div className="w-52">
                                            <label htmlFor={`custom_meta_value_${row.id}`}>custom meta value</label>
                                            <input
                                                id={`custom_meta_value_${row.id}`}
                                                type="text"
                                                className="form-input"
                                                disabled={order_status !== 'Processing' || !row.custom_key}
                                                value={row.custom_value}
                                                onChange={(e) => updateRow(row.id, { custom_value: e.target.value })}
                                            />
                                        </div>
                                    </>
                                )}

                                {order_status === 'Processing' && !isPointRowLocked(row) && !isSystemMetaRow(row) && (
                                    <button className="mb-0.5" type="button" onClick={() => removeRow(row.id)}>
                                        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                                            <line x1="18" y1="6" x2="6" y2="18"></line>
                                            <line x1="6" y1="6" x2="18" y2="18"></line>
                                        </svg>
                                    </button>
                                )}
                            </div>
                        </div>
                        );
                    })}
                </div>
            )}

            {order_status === 'Processing' && (
                <div className="m-4">
                    <button type="button" className="btn btn-outline-primary btn-sm mt-4" onClick={addRow}>
                        Add Adjustment
                    </button>
                </div>
            )}
        </>
    );
};

export default AdjustmentForm;
