import apis from '@/utils/apis';

export const handlePrintReceipt = async (order: any, restaurantInfo: any, currencySymbol: string = '$', configData?: any) => {
    const resName = restaurantInfo?.restaurant_name || 'Vendor';
    const address = restaurantInfo?.address;
    const resAddress = typeof address === 'object'
        ? [address?.building_no, address?.tower, address?.area, address?.city].filter(Boolean).join(', ')
        : (address || '');
    const resPhone = (restaurantInfo?.country_code || '') + (restaurantInfo?.restaurant_phone || '');

    const orderItems = [...(order.cart_items || []), ...(order.grocery_cart_items || []), ...(order.other_cart_items || [])];

    let config = configData;
    if (!config) {
        try {
            const res = await apis.Configuration.getConfiguration();
            config = res?.data?.[0];
        } catch (error) {
            console.error('Error fetching configuration for receipt:', error);
        }
    }

    const formatAddonQty = (addon: any) => {
        const qty = addon?.selected_quantity ?? (typeof addon?.quantity === 'number' || typeof addon?.quantity === 'string' ? addon.quantity : null) ?? (typeof addon?.no_of_quantity === 'number' || typeof addon?.no_of_quantity === 'string' ? addon.no_of_quantity : null);
        return qty ? ` (x${qty})` : '';
    };

    const itemsHtml = orderItems.map((item: any) => {
        const qtyStr = typeof item.quantity === 'object' ? (item.quantity?.name || item.quantity?.title || '') : (item.quantity || '');
        const unitStr = item.unit || '';
        let displayUnit = '';
        if (unitStr) {
            if (qtyStr && String(unitStr).toLowerCase().includes(String(qtyStr).toLowerCase())) {
                displayUnit = unitStr;
            } else {
                displayUnit = `${qtyStr} ${unitStr}`.trim();
            }
        } else {
            displayUnit = String(qtyStr || '');
        }

        return `
        <tr>
            <td style="padding: 4px 0; vertical-align: top;">${item.no_of_quantity || item.noOfQuantity || 1} x ${item.name}</td>
            <td style="text-align: right; padding: 4px 0; vertical-align: top;">${currencySymbol}${(item.total_price !== undefined && item.total_price !== null ? Number(item.total_price) : ((item.price || 0) * (item.no_of_quantity || item.noOfQuantity || 1))).toFixed(2)}</td>
        </tr>
        ${item.size ? `<tr><td colspan="2" style="font-size: 10px; color: #444; padding-left: 10px;">- Size: ${typeof item.size === 'object' ? (item.size.name || item.size.title) : item.size}</td></tr>` : ''}
        ${displayUnit ? `<tr><td colspan="2" style="font-size: 10px; color: #444; padding-left: 10px;">- Qty: ${displayUnit}</td></tr>` : ''}
        ${item.pieces ? `<tr><td colspan="2" style="font-size: 10px; color: #444; padding-left: 10px;">- Pieces: ${typeof item.pieces === 'object' ? (item.pieces.name || item.pieces.title) : item.pieces}</td></tr>` : ''}
        ${item.add_ons?.length ? `<tr><td colspan="2" style="font-size: 10px; color: #444; padding-left: 10px;">- Add-ons: ${item.add_ons.map((a: any) => `${a.name || a.title}${formatAddonQty(a)}`).join(', ')}</td></tr>` : ''}
        ${item.toppings?.length ? `<tr><td colspan="2" style="font-size: 10px; color: #444; padding-left: 10px;">- Toppings: ${item.toppings.map((t: any) => `${t.name || t.title}${formatAddonQty(t)}`).join(', ')}</td></tr>` : ''}
        ${item.other_add_ons?.length ? `<tr><td colspan="2" style="font-size: 10px; color: #444; padding-left: 10px;">- Other Add-ons: ${item.other_add_ons.map((o: any) => `${o.name || o.title}${formatAddonQty(o)}`).join(', ')}</td></tr>` : ''}
    `}).join('');

    const surchargesList = order.surcharges?.filter(
        (item: any) => item.charge_type === 'surcharge' || item.surcharge_type === 'surcharge' || (!item.charge_type && !item.surcharge_type)
    ) || [];
    const extraChargesList = order.surcharges?.filter(
        (item: any) => item.charge_type === 'extra_charge' || item.surcharge_type === 'extra_charge'
    ) || [];

    const surchargesTotal = surchargesList.reduce((sum: number, item: any) => sum + (item.amount || 0), 0);
    const extraChargesTotal = extraChargesList.reduce((sum: number, item: any) => sum + (item.amount || 0), 0);

    const subtotalVal = Number(order.cart_amount || 0);
    const discountVal = Number(order.coupon_amount || 0);
    const platformFeeVal = Number(order.platform_fee || 0);
    const deliveryFeeVal = Number(order.delivery_fee || 0);
    const taxVal = Number(order.tax_amount || 0);
    const tipVal = Number(order.tip_amount || 0);
    const calculatedTotal = order.total_amount !== undefined && order.total_amount !== null && Number(order.total_amount) > 0
        ? Number(order.total_amount)
        : Math.max(0, subtotalVal - discountVal + platformFeeVal + deliveryFeeVal + taxVal + tipVal + surchargesTotal + extraChargesTotal);

    const html = `
        <html>
            <head>
                <title>Bill</title>
                <style>
                    @page { 
                        size: 80mm auto; 
                        margin: 0; 
                    }
                    body { 
                        font-family: Arial, sans-serif;
                        font-size: 16px; 
                        width: 80mm; 
                        margin: 0;
                        padding: 0;
                        color: #000 !important;
                        background-color: #fff !important;
                    }
                    .receipt-box {
                        width: 80mm;
                        padding: 5mm;
                        box-sizing: border-box;
                    }
                    .header { text-align: center; margin-bottom: 5px; }
                    .restaurant-name { font-size: 20px; font-weight: bold; margin-bottom: 3px; text-transform: uppercase; }
                    .info { font-size: 14px; margin-bottom: 2px; }
                    hr { border: 0; border-top: 2px dashed #000; margin: 10px 0; }
                    table { width: 100%; border-collapse: collapse; }
                    .total-section { margin-top: 10px; }
                    .total-row { font-weight: bold; font-size: 18px; border-top: 1px solid #000; }
                    .footer { text-align: center; margin-top: 20px; font-size: 13px; line-height: 1.5; }
                    .order-id { font-weight: bold; display: block; margin: 5px 0; }
                </style>
            </head>
            <body>
                <div class="receipt-box">
                    <div class="header">
                        <div class="restaurant-name">${resName}</div>
                        <div class="info">${resAddress}</div>
                        <div class="info"><b>Tel: ${resPhone}</b></div>
                        ${config?.product_name ? `
                        <div style="font-size: 13px; color: #555; margin-top: 4px; font-weight: normal;">
                            Powered by <span style="font-weight: bold;">${config.product_name}</span>
                            ${config.support?.call ? ` | Support: ${config.support.call}` : ''}
                        </div>
                        ` : ''}
                    </div>
                    <hr />
                    <div class="info"><b>Order ID: ${order.order_id || 'N/A'}</b></div>
                    <div class="info">Date: ${new Date().toLocaleString()}</div>
                    <div class="info">Customer: ${order.add_receiver_detail?.name || order.customer_id?.name || 'Walk-in Customer'}</div>
                    ${(() => {
            const receiver = order.add_receiver_detail || {};
            const customerObj = order.customer_id || order.user_id || {};
            const customerId = receiver.customer_id
                || (typeof customerObj === 'object' ? (customerObj.custom_id || customerObj.customer_id || customerObj.user_id) : null)
                || (receiver._id && receiver._id !== 'Walk-in Customer' ? receiver._id : null);
            return customerId ? `<div class="info">Customer ID: ${customerId}</div>` : '';
        })()}
                    <hr />
                    <table>
                        ${itemsHtml}
                    </table>
                    <hr />
                    <div class="total-section">
                        <table>
                            <tr>
                                <td style="padding: 2px 0;">Subtotal:</td>
                                <td style="text-align: right;">${currencySymbol}${subtotalVal.toFixed(2)}</td>
                            </tr>
                            ${discountVal > 0 ? `
                            <tr>
                                <td style="padding: 2px 0;">Discount:</td>
                                <td style="text-align: right;">-${currencySymbol}${discountVal.toFixed(2)}</td>
                            </tr>` : ''}
                            ${platformFeeVal > 0 ? `
                            <tr>
                                <td style="padding: 2px 0;">Platform Fee:</td>
                                <td style="text-align: right;">${currencySymbol}${platformFeeVal.toFixed(2)}</td>
                            </tr>` : ''}
                            ${deliveryFeeVal > 0 ? `
                            <tr>
                                <td style="padding: 2px 0;">Delivery Fee:</td>
                                <td style="text-align: right;">${currencySymbol}${deliveryFeeVal.toFixed(2)}</td>
                            </tr>` : ''}
                            ${surchargesTotal > 0 ? `
                            <tr>
                                <td style="padding: 2px 0;">Surcharges:</td>
                                <td style="text-align: right;">${currencySymbol}${surchargesTotal.toFixed(2)}</td>
                            </tr>` : ''}
                            ${extraChargesTotal > 0 ? `
                            <tr>
                                <td style="padding: 2px 0;">Extra Charges:</td>
                                <td style="text-align: right;">${currencySymbol}${extraChargesTotal.toFixed(2)}</td>
                            </tr>` : ''}
                            ${taxVal > 0 ? `
                            <tr>
                                <td style="padding: 2px 0;">${config?.tax?.tax_keyword || order?.tax_keyword || 'Tax'}:</td>
                                <td style="text-align: right;">${currencySymbol}${taxVal.toFixed(2)}</td>
                            </tr>` : ''}
                            ${tipVal > 0 ? `
                            <tr>
                                <td style="padding: 2px 0;">Driver Tip:</td>
                                <td style="text-align: right;">${currencySymbol}${tipVal.toFixed(2)}</td>
                            </tr>` : ''}
                            ${/* order.sales_commission > 0 ? `
                            <tr>
                                <td style="padding: 2px 0;">Sales Commission:</td>
                                <td style="text-align: right;">${currencySymbol}${Number(order.sales_commission).toFixed(2)}</td>
                            </tr>` : '' */ ''}
                            <tr class="total-row">
                                <td style="padding: 8px 0;">TOTAL:</td>
                                <td style="text-align: right; padding: 8px 0;">${currencySymbol}${calculatedTotal.toFixed(2)}</td>
                            </tr>
                        </table>
                    </div>
                    <hr />
                    <div class="info" style="text-align: center;">
                        <b>MODE: ${String(order.payment_type || 'Cash').toUpperCase()}</b>
                    </div>
                    <div class="footer">
                        <b>Thank you! Visit Again.</b>
                    </div>
                </div>
            </body>
        </html>
    `;

    // Create hidden iframe if it doesn't exist
    let iframe = document.getElementById('receipt-print-iframe') as HTMLIFrameElement;
    if (!iframe) {
        iframe = document.createElement('iframe');
        iframe.id = 'receipt-print-iframe';
        iframe.style.position = 'fixed';
        iframe.style.right = '0';
        iframe.style.bottom = '0';
        iframe.style.width = '0';
        iframe.style.height = '0';
        iframe.style.border = '0';
        document.body.appendChild(iframe);
    }

    const iframeDoc = iframe.contentWindow?.document || iframe.contentDocument;
    if (iframeDoc) {
        iframeDoc.open();
        iframeDoc.write(html);
        iframeDoc.close();

        // Wait for resources to load then print
        setTimeout(() => {
            iframe.contentWindow?.focus();
            iframe.contentWindow?.print();
        }, 500);
    }
};
