
import { useEffect, useState } from 'react';
import { UnifiedAdjustment } from '@/utils/orderAdjustmentAdapter';

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

interface PromotionCase {
    id: number;
    value: number;
    case_type: string;
    promo_value: string | string[] | FreeItemValue[];
}

interface Promotion {
    id: string;
    _id: string;
    promotion_type: string;
    promotion_name: string;
    promotion_start: string;
    promotion_end: string;
    promotion_case: PromotionCase[];
}

interface ActivePromotionCardProps {
    adjustments: UnifiedAdjustment[];
    setAdjustments: React.Dispatch<React.SetStateAction<UnifiedAdjustment[]>>;
    order_status?: string;
}

const ActivePromotionCard: React.FC<ActivePromotionCardProps> = ({ adjustments, setAdjustments, order_status = 'Processing' }) => {
    const [promotions, setPromotions] = useState<Promotion[]>([]);
    const [isLoadingPromotion, setIsLoadingPromotion] = useState(true);

    useEffect(() => {
        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();
                    setPromotions(Array.isArray(data) ? data : []);
                } else {
                    setPromotions([]);
                }
            } catch (error) {
                console.error('Failed to fetch running promotions:', error);
                setPromotions([]);
            }

            setIsLoadingPromotion(false);
        };

        fetchRunningPromotions();
    }, []);

    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: PromotionCase) => {
        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 isPromotionCaseAdded = (promotionName: string, caseType: string, amount: number) => {
        return adjustments.some((row) => row.source_type === 'promotion' && row.promotion_name === promotionName && row.promotion_case_type === caseType && row.amount === amount);
    };

    const addPromotionCase = (promotion: Promotion, promotionCase: PromotionCase) => {
        if (promotionCase.case_type !== 'extra_discount' && promotionCase.case_type !== 'birthday_extra') {
            return;
        }

        const parsedAmount = typeof promotionCase.promo_value === 'string' ? Number(promotionCase.promo_value) : 0;

        setAdjustments((prev) => [
            ...prev,
            {
                id: prev.length ? prev.reduce((max, row) => (row.id > max ? row.id : max), 0) + 1 : 1,
                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: promotion.id || promotion._id || '',
                promotion_case_id: promotionCase.id,
                promotion_case_value: Number(promotionCase.value) || 0,
            },
        ]);
    };

    if (isLoadingPromotion || promotions.length === 0) return null;

    return (
        <div className="panel mb-5 ">
            <div className="mb-3 font-semibold">Promosi Aktif</div>

            <div className="flex flex-col gap-3">
                {promotions.map((promo) => {
                    const promoId = promo.id || promo._id;

                    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 items-center justify-between">
                                <div className="flex 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>
                                </div>
                            </div>

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

                            {promo.promotion_case.length > 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 text-right"></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {promo.promotion_case.map((pc) => {
                                                const parsedAmount = typeof pc.promo_value === 'string' ? Number(pc.promo_value) : 0;
                                                const added = isPromotionCaseAdded(promo.promotion_name, pc.case_type, isNaN(parsedAmount) ? 0 : parsedAmount);

                                                return (
                                                    <tr key={pc.id} className="border-b border-white-light last:border-0 dark:border-[#1b2e4b]">
                                                        <td className="py-1.5">{promo.promotion_type === 'subtotal_of_cart' ? `Rp ${Number(pc.value).toLocaleString('id-ID')}` : pc.value}</td>
                                                        <td className="py-1.5">{getCaseTypeLabel(pc.case_type)}</td>
                                                        <td className="py-1.5">{getPromoValueDisplay(pc)}</td>
                                                        <td className="py-1.5 text-right">
                                                            {(pc.case_type === 'extra_discount' || pc.case_type === 'birthday_extra') && (
                                                                <button
                                                                    type="button"
                                                                    disabled={added || order_status !== 'Processing'}
                                                                    className="btn btn-outline-primary btn-sm px-2 py-0.5 text-xs disabled:cursor-not-allowed disabled:opacity-50"
                                                                    onClick={() => addPromotionCase(promo, pc)}
                                                                >
                                                                    {added ? 'Added' : '+ Add'}
                                                                </button>
                                                            )}
                                                        </td>
                                                    </tr>
                                                );
                                            })}
                                        </tbody>
                                    </table>
                                </div>
                            )}
                        </div>
                    );
                })}
            </div>
        </div>
    );
};

export default ActivePromotionCard;
