const BillPreview = (props) => {

    const { saleNumber, setSaleNumber} = props
    const [loading, setLoading] = useState(false)
    const [total, setTotal] = useState({})
    const [data, setData] = useState()
    const user_lang = commonFunc.getCookies('user_lang') || 'vi';
    const config = { token: _token_encode, lang: user_lang };  
    const containerRef = useRef(null);
    const qrRef = useRef();
    const [tenderCash, setTenderCash]=useState()
    ////

    const handleGetDataToPrint = async () => {
        
        try {  
            
            setLoading(true)   
            const url =`/api/POS/print-bill/${saleNumber}`
            const resultObj = await commonApi.APIGETByURL(url, config)           
            if (resultObj.status == 200){    
                            
                let dataTmp = resultObj?.data  
                   
                //dataTmp['carts'] = JSON.parse(dataTmp['carts'])
                setData(dataTmp)
                calculateSums (dataTmp?.carts)
                
                setTenderCash( dataTmp?.transaction_tenders?.find(tender => tender.tender_code === 'C'))
                if (window.QRCode) {
                    // Tạo mã QR
                    
                    const qrCode = new window.QRCode(qrRef.current, {
                        text: dataTmp?.id.toString()+'-'+dataTmp?.branch_no,
                        width: 50,
                        height: 50,
                    });

                    return () => {
                        qrCode.clear(); // Dọn dẹp mã QR khi component unmount
                    };
                } else {
                    console.error("QRCode library is not loaded.");
                }
            }    
        //console.log(dataInit )
        } catch (e) {            
            
            console.log("ERROR get-POS/print-bill" )
        }finally{
            setLoading(false)
        }
    };

    useEffect(()=>{
         handleGetDataToPrint()
         document.getElementById('master_footer').style.display = 'none';
         if (containerRef.current) {
            containerRef.current.focus();
        }
    },[])
 
    const handleClose=()=>{
        document.getElementById('master_footer').style.display = '';
        setSaleNumber(null)
    }

    function calculateSums(arr) {
        let totalAmount = 0;
        let totalExtension = 0;
        let totalQty =0;
        arr.forEach(promotion => {
            promotion?.items_apply.forEach(item => {
                totalAmount += item.qty * item.price;                
                totalExtension += item.extension;
                totalQty+=item.qty
            });
        });

        const total = {
            totalAmount: totalAmount,
            totalExtension,
            totalQty:totalQty
        };
        setTotal(total)
        
    }    

    const titles = {
        vi: {
            shop: "CỬA HÀNG",
            receipt: "PHIẾU THANH TOÁN",
            customer: "Khách hàng:",
            productList: "Danh sách sản phẩm:",
            quantity: "SL",
            price: "Giá bán (Đã VAT)",
            totalAmount: "Thành tiền",
            paymentMethod: "Phương thức thanh toán:",
            total: "Tổng tiền:",
            remain:"Cần thanh toán",
            discount:"Đã giảm",
            cashGiven: "Khách đưa:",
            change: "Tiền thừa:",
            vatNote: "Lưu ý: HĐ VAT chỉ xuất trong ngày !",
            qrNote: `Để tra cứu hóa đơn, xin vui lòng truy cập vào ${data?.page} hoặc scan QR Code trên bill`,
            thankYou: "Cảm ơn quý khách! Hẹn gặp lại"
        },
        en: {
            shop: "SHOP",
            receipt: "RECEIPT",
            customer: "Customer:",
            productList: "Product List:",
            quantity: "Qty",
            price: "Selling Price (Incl. VAT)",
            totalAmount: "Total Amount",
            paymentMethod: "Payment Method:",
            total: "Total:",
            remain:"Total after discount",
            discount:"Discount",
            cashGiven: "Cash Given:",
            change: "Change:",
            vatNote: "Note: VAT invoices can only be issued on the same day!",
            qrNote: `To look up invoices, please visit ${data?.page} or scan the QR Code on the bill`,
            thankYou: "Thank you! See you again"
        }
    };
    const currentTitles = titles[user_lang];
    const handleKeyDown = (event) => {
        
        if (event.key === 'Enter' || event.key === 'Escape') {
            handleClose();
        }
    }
    
    return (
        <div ref={containerRef} tabindex={"-1"} onKeyDown={(e)=>handleKeyDown(e)} style={{ width: '100%', maxWidth: '100mm', height: '100%', fontFamily: 'Arial', padding: '5px', margin: '0 auto' }}>
            <div style={{ display: 'inline-flex', width: '100%' }}>
                <div style={{ width: '80%' }}>
                    <div style={{ textAlign: 'left', fontSize: '14px', fontWeight: 'bold' }}>
                        {data?.branch_info?.branch_code} - {data?.branch_info?.store_name_e}
                    </div>
                    <div style={{ textAlign: 'left', fontSize: '12px' }}>
                        {currentTitles.receipt} {data?.id}: {commonFunc.formatDate(new Date(data?.sale_date), 'DD/MM/YYYY HH:mm')}
                    </div>
                </div>
                <div style={{ width: '20%' }}>
                    <div ref={qrRef} style={{ margin: 'auto', float: 'right' }}></div>
                </div>
            </div>
            <div style={{ borderTop: '1px solid #000', margin: '5px 0' }}></div>
            {data?.customer &&
                <div style={{ margin: '5px 0', fontSize: '12px' }}>
                    <div>
                        <strong>{currentTitles.customer}</strong> {data?.customer?.given_name} {data?.customer?.family_name}
                    </div>
                    <div>
                        <span style={{ float: 'left' }}>{data?.customer?.mobile}</span>
                        {data?.customer?.email &&
                            <span style={{ float: 'right' }}>{data.customer.email}</span>
                        }
                    </div>
                </div>
            }

            <div style={{ margin: '5px 0', fontSize: '12px' }}>
                <div style={{ clear: 'both' }}><strong>{currentTitles.productList}</strong></div>
                <div style={{ fontWeight: 'bold', display: 'flex', justifyContent: 'space-between', borderBottom: '1px solid #000', paddingBottom: '5px' }}>
                    <span style={{ textAlign: 'left', width: '10%' }}>{currentTitles.quantity}</span>
                    <span style={{ textAlign: 'right', width: '60%' }}>{currentTitles.price}</span>
                    <span style={{ textAlign: 'right', width: '30%' }}>{currentTitles.totalAmount}</span>
                </div>

                {data?.carts?.map((cart, index) => (
                    <div key={index} style={{ marginBottom: '10px' }}>
                        <div style={{ fontWeight: 'bold', fontSize: '12px' }}>{cart?.name_en}</div>
                        {cart.items_apply.map((item, idx) => (
                            <div key={idx} style={{ marginBottom: '5px' }}>
                                <div style={{ fontSize: '12px' }}>{item.item_code}: {item?.description_en[0]}</div>
                                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '5px', fontSize: '12px' }}>
                                    <span style={{ width: '10%' }}>{commonFunc.formatNumber(item.qty)}</span>
                                    <span style={{ textAlign: 'right', width: '60%' }}>
                                        <span style={{ fontStyle: 'italic', fontSize: 10 }}>(VAT {parseInt(item?.product_info?.product?.Rate)} %)</span>
                                        <span style={{ display: (item?.price !== (item?.promotion_price - item?.discount_value)) ? '' : 'none', textDecoration: 'line-through' }}>{commonFunc.formatNumber(item?.price)}</span>
                                        {commonFunc.formatNumber(item?.promotion_price - item?.discount_value)}
                                    </span>
                                    <span style={{ textAlign: 'right', width: '30%' }}>{commonFunc.formatNumber(item?.extension )}</span>
                                </div>
                            </div>
                        ))}
                    </div>
                ))}
            </div>

            <div style={{ borderTop: '1px solid #000', margin: '10px 0' }}></div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 'bold', fontSize: '12px' }}>
                <span>{currentTitles.total}</span>
                <span>{commonFunc.formatNumber(total?.totalAmount)}</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 'bold', fontSize: '12px' }}>
                <span>{currentTitles.discount}</span>
                <span>{commonFunc.formatNumber(total?.totalAmount-total?.totalExtension)}</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 'bold', fontSize: '12px' }}>
                <span>{currentTitles.remain}</span>
                <span>{commonFunc.formatNumber(total?.totalExtension)}</span>
            </div>

            <div style={{ margin: '5px 0', fontSize: '12px' }}>
                <strong>{currentTitles.paymentMethod}</strong>
                {data?.transaction_tenders?.map((tender, index) => (
                    <div key={index} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '5px' }}>
                        <span style={{ flex: 1 }}>{tender?.tender_desc}</span>
                        <span style={{ flex: 1, textAlign: 'right' }}>{commonFunc.formatNumber(tender?.contribution)}</span>
                    </div>
                ))}
            </div>
            {tenderCash && tenderCash?.collected > tenderCash?.contribution &&
                <>
                    <div style={{ borderTop: '1px solid #000', margin: '10px 0' }}></div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 'bold', fontSize: '12px' }}>
                        <span>{currentTitles.cashGiven}:</span>
                        <span>{commonFunc.formatNumber(tenderCash?.collected)}</span>
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 'bold', fontSize: '12px' }}>
                        <span>{currentTitles.change}:</span>
                        <span>{commonFunc.formatNumber(tenderCash?.collected - tenderCash?.contribution)}</span>
                    </div>
                </>
            }

            <div style={{ borderTop: '1px solid #000', margin: '10px 0' }}></div>
            <div style={{ textAlign: 'center', fontSize: '12px' }}>{currentTitles.vatNote}</div>
            <div style={{ textAlign: 'center', fontSize: '12px' }}>{currentTitles.qrNote}</div>
            <div autoFocus={true} tabIndex={0} onClick={handleClose} style={{ textAlign: 'center', fontSize: '12px', background: 'white', borderRadius: 4, padding: 2, border: '1px solid gray' }}>
                {currentTitles.thankYou}
            </div>
        </div>
    );
};
