export type CouponPreviewState = 'eligible' | 'min_purchase' | 'not_eligible';

interface CouponFormPreviewInput {
    coupon_name: string;
    coupon_type: string;
    coupon_amount: number;
    coupon_min_purchase: number;
    coupon_is_highlight: boolean;
    coupon_start_date?: Date | string | null;
    coupon_end_date?: Date | string | null;
}

export interface VoucherPreviewData {
    code: string;
    type: string;
    amount_label: string;
    estimated_discount: number;
    eligible: boolean;
    disabled_reason: string;
    is_highlight: boolean;
    has_matching_products: boolean;
    min_purchase: number;
    valid_from: string | null;
    valid_until: string | null;
}

export function formatCouponAmountLabel(coupon: Pick<CouponFormPreviewInput, 'coupon_type' | 'coupon_amount'>) {
    if (coupon.coupon_type === 'percentage') {
        return `${Number(coupon.coupon_amount || 0)}%`;
    }
    if (coupon.coupon_type === 'free_item') {
        return 'Free item';
    }
    return `IDR ${Number(coupon.coupon_amount || 0).toLocaleString('id-ID')}`;
}

function formatShortAmount(amount: number) {
    if (Number.isNaN(amount)) return String(amount);

    if (amount >= 1_000_000) {
        const jt = amount / 1_000_000;
        return (jt % 1 === 0 ? jt : jt.toFixed(1)) + 'Jt';
    }
    if (amount >= 1_000) {
        const k = amount / 1_000;
        return (k % 1 === 0 ? k : k.toFixed(1)) + 'K';
    }
    return amount.toString();
}

export function formatMinPurchaseLabel(minPurchase: number) {
    if (minPurchase > 0) {
        return `*min purch  ${formatShortAmount(minPurchase)}`;
    }
    return '';
}

export function formatValidRange(validFrom?: string | Date | null, validUntil?: string | Date | null) {
    const parse = (value?: string | Date | null) => {
        if (value == null || value === '') return null;
        const date = value instanceof Date ? value : new Date(value);
        return Number.isNaN(date.getTime()) ? null : date;
    };

    const from = parse(validFrom);
    const to = parse(validUntil);

    const dateOpts: Intl.DateTimeFormatOptions = {
        day: 'numeric',
        month: 'short',
        timeZone: 'Asia/Jakarta',
    };

    if (from && to) {
        const fromLabel = from.toLocaleDateString('en-GB', dateOpts).trim();
        const toLabel = to.toLocaleDateString('en-GB', dateOpts).trim();
        return `*valid ${fromLabel} - ${toLabel}`;
    }

    // if (from) {
    //     const fromLabel = from.toLocaleDateString('en-GB', dateOpts).trim();
    //     return `*valid from ${fromLabel}`;
    // }

    if (to) {
        const toLabel = to.toLocaleDateString('en-GB', dateOpts).trim();
        return `*valid until ${toLabel}`;
    }

    return null;
}

function toIsoDate(value?: Date | string | Date[] | null) {
    if (value == null || value === '') return null;
    const raw = Array.isArray(value) ? value[0] : value;
    if (!raw) return null;
    const date = raw instanceof Date ? raw : new Date(raw);
    if (Number.isNaN(date.getTime())) return null;
    return date.toISOString();
}

function calculateEstimatedDiscount(coupon: CouponFormPreviewInput) {
    const amount = Number(coupon.coupon_amount || 0);
    if (coupon.coupon_type === 'percentage') {
        const base = Number(coupon.coupon_min_purchase || 0) || 1_000_000;
        return Math.round(base * (amount / 100));
    }
    if (coupon.coupon_type === 'free_item') {
        return 0;
    }
    return amount;
}

export function buildVoucherPreviewData(
    coupon: CouponFormPreviewInput,
    previewState: CouponPreviewState = 'eligible'
): VoucherPreviewData | null {
    if (coupon.coupon_type === 'free_item') {
        return null;
    }

    const code = String(coupon.coupon_name || 'VOUCHER').toUpperCase() || 'VOUCHER';
    const amountLabel = formatCouponAmountLabel(coupon);
    const estimatedDiscount = calculateEstimatedDiscount(coupon);
    const minPurchase = Number(coupon.coupon_min_purchase || 0);
    const isHighlight = Boolean(coupon.coupon_is_highlight);
    const validFrom = toIsoDate(coupon.coupon_start_date);
    const validUntil = toIsoDate(coupon.coupon_end_date);

    const base = {
        code,
        type: coupon.coupon_type,
        amount_label: amountLabel,
        estimated_discount: estimatedDiscount,
        is_highlight: isHighlight,
        min_purchase: minPurchase,
        valid_from: validFrom,
        valid_until: validUntil,
    };

    if (previewState === 'eligible') {
        return {
            ...base,
            eligible: true,
            disabled_reason: '',
            has_matching_products: true,
        };
    }

    if (previewState === 'min_purchase') {
        const exampleSubtotal = minPurchase > 0 ? Math.max(minPurchase - 433_000, 0) : 1_467_000;
        const shortfall = Math.max(minPurchase - exampleSubtotal, 433_000);

        return {
            ...base,
            eligible: false,
            disabled_reason:
                minPurchase > 0
                    ? `Min. belanja Rp ${minPurchase.toLocaleString('id-ID')} (kurang Rp ${shortfall.toLocaleString('id-ID')})`
                    : 'Min. belanja belum terpenuhi',
            has_matching_products: true,
        };
    }

    return {
        ...base,
        eligible: false,
        disabled_reason: 'Tidak ada item di keranjang yang memenuhi syarat',
        has_matching_products: false,
    };
}
