
import { useEffect, useState } from 'react';

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_is_active: boolean;
    promotion_case: PromotionCase[];
}

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

interface ActivePromotionBannerProps {
    discounts: Discount[];
    setDiscounts: React.Dispatch<React.SetStateAction<Discount[]>>;
}

const ActivePromotionBanner: React.FC<ActivePromotionBannerProps> = ({ discounts, setDiscounts }) => {
    const [promotions, setPromotions] = useState<Promotion[]>([]);
    const [isLoading, setIsLoading] = 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(data);
                }
            } catch (error) {
                console.error('Failed to fetch running promotions:', error);
            }
            setIsLoading(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 isAlreadyAdded = (promoName: string) => {
        return discounts.some((d) => d.coupon_name === promoName.toUpperCase());
    };

    const addPromotionAsDiscount = (promotion: Promotion, promotionCase: PromotionCase) => {
        const maxId = discounts?.length ? discounts.reduce((max: number, d: Discount) => (d.id > max ? d.id : max), discounts[0]?.id || 0) : 0;

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

        setDiscounts([
            ...discounts,
            {
                id: maxId + 1,
                coupon_name: promotion.promotion_name.toUpperCase(),
                amount: isNaN(promoValue) ? 0 : promoValue,
                free_item: '',
            },
        ]);
    };

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

    return (
        <div className="mx-2 mt-4 rounded-md border border-dashed border-primary bg-primary-light p-4 dark:bg-primary/10">
            <div className="mb-3 flex 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="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>
            </div>

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

                    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>
                                {added && <span className="rounded bg-success/20 px-2 py-0.5 text-xs font-medium text-success">Sudah ditambahkan</span>}
                            </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) => (
                                                <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 !== 'free_item' && (
                                                            <button
                                                                type="button"
                                                                disabled={added}
                                                                className="btn btn-outline-primary btn-sm px-2 py-0.5 text-xs disabled:cursor-not-allowed disabled:opacity-50"
                                                                onClick={() => addPromotionAsDiscount(promo, pc)}
                                                            >
                                                                + Add
                                                            </button>
                                                        )}
                                                    </td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                            )}
                        </div>
                    );
                })}
            </div>
        </div>
    );
};

export default ActivePromotionBanner;
