const POSTransaction=(props)=>{
    const { config, carts, baskets, setBaskets, handleClose, userInfo,shift_id, member, setMember, setSaleNumber} = props 
    const btnTenderRef = useRef(null)
    const btnPrintRef = useRef(null);
    const [showModalTender,setShowModalTender] = useState(false)
    const [showModalVAT,setShowModalVAT] = useState(false)

    const [loading, setLoading] = useState(false)
    const [paymentMethodList, setPaymentMethodList]=useState([])
    const [isFormLoaded, setIsFormLoaded] = useState(false);
    const {Row, Col} = ReactBootstrap
    const [totalAmount, setTotalAmount] = useState(0)
    const [totalAmountPaid, setTotalAmountPaid] = useState(0)
    const [totalAmountRemain, setTotalAmountRemain] = useState(0) 
   
    const [tendersApplied, setTendersApplied]=useState((baskets?.basket?.tenders || []))
  

    useEffect(() => {
        if(paymentMethodList.length==0){            
            fetchApplyTenders()
        }
    }, []); // Chạy chỉ một lần khi component mount

    // Focus vào nút "Hình thức thanh toán" (hoặc Hoàn tất) sau khi paymentMethodList đã được load
    useEffect(() => {
        if (paymentMethodList.length > 0) {
            const timer = setTimeout(() => {
                if (btnTenderRef.current) {
                    btnTenderRef.current.focus();
                } else if (btnPrintRef.current) {
                    btnPrintRef.current.focus();
                }
            }, 200);
            return () => clearTimeout(timer);
        }
    }, [paymentMethodList, baskets]);

    const fetchApplyTenders = async () => {

        setLoading(true);
        try {
            const url = '/api/get-apply-tenders';
           
            const resultObj = await commonApi.APIGETByURL(url, config);
            setLoading(false);            
            if (resultObj.status === 200) {
                
                setPaymentMethodList(resultObj.data);
            } else {
                
                console.log("Unexpected response quotation:", resultObj.status);
                location.href('/login?next=' + window.location.pathname + window.location.search);
            }
        } catch (e) {
            
            console.log(e.message)
            setLoading(false);
            console.log("ERROR get-quotation", e);
        }
    };    
    
    const handleShowTender=()=>{
        setShowModalTender(true)        
        btnTenderRef.current
    }

    const handleTransactionKeyDown = (event) => {
        // Chỉ xử lý phím mũi tên khi modal chọn hình thức thanh toán và modal VAT đóng
        if (showModalTender || showModalVAT) {
            return;
        }

        const arrowKeys = ['ArrowDown', 'ArrowRight', 'ArrowUp', 'ArrowLeft'];
        if (arrowKeys.includes(event.key)) {
            event.preventDefault();
            const buttons = document.querySelectorAll('.btn-transaction-action');
            // Lọc ra các nút đang hiển thị và không bị disable
            const enabledButtons = Array.from(buttons).filter(btn => {
                if (btn.disabled) return false;
                const style = window.getComputedStyle(btn);
                return style.display !== 'none' && style.visibility !== 'hidden';
            });

            if (enabledButtons.length === 0) return;

            const currentButtonIndex = enabledButtons.findIndex(btn => document.activeElement === btn);
            let nextIndex = 0;

            if (currentButtonIndex !== -1) {
                if (event.key === 'ArrowDown' || event.key === 'ArrowRight') {
                    nextIndex = (currentButtonIndex + 1) % enabledButtons.length;
                } else {
                    nextIndex = (currentButtonIndex - 1 + enabledButtons.length) % enabledButtons.length;
                }
            } else {
                nextIndex = 0; // Mặc định tập trung vào nút đầu tiên
            }

            enabledButtons[nextIndex].focus();
        }
    };

    useEffect(()=>{    
            
        if (baskets==null){ 
            return 
        }
        
        const ttAmount = calculateTotalAmount(carts)
        
        const tenders= (baskets?.basket?.tenders || [])
        
        const ttAmountPaid = calculateTotalTenderValue(tenders)
        setTotalAmount (ttAmount)
        setTotalAmountPaid( ttAmountPaid)
        setTotalAmountRemain(ttAmount-ttAmountPaid)
        setTendersApplied(tenders)
        
        if(btnTenderRef?.current){
            btnTenderRef.current.focus()
        }
        if (isFormLoaded==false){
            setIsFormLoaded(true);
        }        
        if(ttAmount-ttAmountPaid <=0 && ttAmount>0){
            setShowModalTender(false)            
            if (btnPrintRef.current) {                            
                //btnPrintRef.current.click(); // Gọi focus khi component được render
                handleCompleteTransaction()
            }
        }
        if (btnPrintRef.current) {
            
            btnPrintRef.current.focus(); // Gọi focus khi component được render
        }        
        
        if (baskets?.transaction_id != null){
            setMember(null);
            if (handleClose){
                handleClose()                
            }     
        }
    },[carts, baskets,isFormLoaded]) 

    const calculateTotalAmount = (carts) => {
        
        return carts?.reduce((total, cart) => {
            
            return total + cart.items_apply?.reduce((subTotal, item) => {                
                return subTotal + (item.extension );
                
            }, 0);
        }, 0);
    };
    const calculateTotalTenderValue = (tenders) => {
        return (tenders?.reduce((total, tender) => total + parseInt( tender.value), 0) | 0);
    };
    const handleDeleteTender=async(tender_code)=>{
        const sw = typeof Swal !== 'undefined' ? Swal : (window.Swal || null);
        let alertConfirm = false;
        if (sw) {
            const { isConfirmed } = await sw.fire({
                title: "Delete record?",
                text: "Do you want to delete this record?",
                icon: "question",
                showCancelButton: true,
                confirmButtonColor: "#7c3aed",
                cancelButtonColor: "#64748b",
                confirmButtonText: "Confirm",
                cancelButtonText: "Cancel"
            });
            alertConfirm = isConfirmed;
        } else {
            alertConfirm = confirm("Do you want delete record");
        }
        if (!alertConfirm){
            return;
        }
        
        setBaskets(prev => {
            // Khởi tạo nếu prev là null
            const basket = prev || { basket: { tenders: [] } };

            // Lọc ra các tender không phải là tender_code cần xóa
            const updatedTenders = basket.basket.tenders.filter(tender => tender.tender_code !== tender_code);

            return {
                ...basket,
                basket: {
                    ...basket.basket,
                    tenders: updatedTenders // Cập nhật danh sách tenders
                }
            };
        });
    }

    const handleCompleteTransaction= async()=>{

        try {
            
            setLoading(true);    
            if(shift_id==null){
                alert('Chưa được mở ca')
                return
            }      
            let tenders = baskets?.basket?.tenders
            let return_tx_no = baskets?.basket?.return_tx_no
            if (tenders==null){
                // tự tạo 1 tender C cash để cân đối bill trừ
                const collected = totalAmountRemain
                
                tenders = [
                    {sale_tx_no: null,  
                        tender_code: 'C', // Giả sử trả tiền mặt TODO
                        collected: collected,
                        contribution: collected,
                        tender_desc: paymentMethodList?.find(obj=> obj.value=='C')?.key || ''
                    }
                ]
                tenders = null
            }
            
            const transaction = {
                sales_tx_hdr: {
                    user_id: 1,  // Ví dụ ID người dùng, bạn có thể thay đổi theo yêu cầu
                    company_id: 1,  // Ví dụ ID công ty, bạn có thể thay đổi theo yêu cầu
                    branch_no: 1,  // Ví dụ số chi nhánh, điều chỉnh tùy theo nhu cầu
                    cust_code: baskets?.basket?.cust_code || null,  // Lấy mã khách hàng từ basket
                    sale_date: new Date().toISOString(),  // Ngày giao dịch hiện tại
                    po_number: baskets?.basket?.po_number || null,  // Thay đổi nếu có thông tin
                    shift_id:shift_id,
                    carts:carts,
                    transaction_code:baskets?.basket?.basket_id
                },
                sales_tx_lines: carts?.map(cart => 
                    cart.items_apply.map(item => ({
                        sale_tx_no: null,  // Sẽ được gán sau khi insert vào SalesTxHDR
                        item_code: item.item_code,
                        item_qty: item.qty,
                        price: item.price,
                        extension: item.extension,
                        discount_value: item.discount_value,
                        description:item?.product_info?.product?.description ||'',
                        description_vi: item.description_vi.join(', '),  // Kết hợp các mô tả tiếng Việt
                        description_en: item.description_en.join(', '),  // Kết hợp các mô tả tiếng Anh
                        tax_rate: parseInt( item?.product_info?.product?.Rate | 0),  // Ví dụ tỷ lệ thuế, điều chỉnh theo yêu cầu
                        uom_vi: item.product_info.product.uom_vi,
                        uom_en: item.product_info.product.uom_en,
                        supplier_cost: parseFloat(item.product_info.product.supplier_cost),
                        supplier_code: item.product_info.product.supplier_code,
                        promo_code: cart?.id,  // Thay đổi nếu có thông tin khuyến mãi
                        promo_name_vi: cart?.name_vi || "",
                        promo_name_en: cart?.name_en || "",
                        return_tx_no:return_tx_no
                    })).flat()
                ).flat(),
                sale_tenders: tenders? tenders.map(tender => ({
                    sale_tx_no: null,  // Sẽ được gán sau khi insert vào SalesTxHDR
                    tender_code: tender.tender_code,
                    collected: tender.value || 0,
                    contribution: tender.contribution || 0,
                    tender_desc: paymentMethodList?.find(obj=> obj.value==tender.tender_code)?.key || ''
                })):null,
                invoice_info: baskets?.basket?.invoice_info || null,
            };
            const data ={
                "data":transaction
            }
            
            const updateAPI = await commonApi.APIPOSTByURL('/api/create-mdc-transaction', data, config);
            const result =  updateAPI;
            
            if (result && result.status==201 && result?.data?.status=='success') {
                
                console.log('Updated successfully:', result.data);                
                commonFunc.setCookies('baskets', {}, -1);   
                
                setBaskets(prev =>({
                        ...prev,items:[], basket:{}
                    })
                )
                
               setSaleNumber(result?.data?.transaction_id || null)
               //setBaskets(null)
             
                //actionAlert('Updated successfully','success')
                         
            } else {
                console.error('Error updating:', result.message || 'Unknown error');              
                //actionAlert('Update customer not successfull','error')
            }
        } catch (e) {
            console.error("Error: " + e.message);
        } finally {
            setLoading(false);
        }
    }
    const titles = {
        vi: {
            tenders: "Hình thức thanh toán",
            totalAmount: "Tổng tiền:",
            amountPaid: "Đã trả:",
            amountRemaining: "Còn lại:",
            excessAmount: "Tiền thừa:",
            complete: "Hoàn tất",
            invoice: "Xuất hóa đơn",
            invoice_edit: "Sửa hóa đơn",
            tenderButton: "Hình thức thanh toán"
        },
        en: {
            tenders: "Payment Methods",
            totalAmount: "Total Amount:",
            amountPaid: "Amount Paid:",
            amountRemaining: "Remaining:",
            excessAmount: "Excess Amount:",
            complete: "Complete",
            invoice: "Invoice",
            invoice_edit: "Edit Invoice",
            tenderButton: "Payment Methods"
        }
    };
    const user_lang = config?.lang || 'vi';
    const currentTitles = titles[user_lang];
    
    if ((paymentMethodList?.length==0 || config.branch_no==0) && userInfo?.username!='0907012207'){  
        if (config?.branch_no==0)
            return (<h2 style={{color:'red'}}>Chương trình thử nghiệm !!</h2>)
        else
            return <></>
    }
    return (
        <div onKeyDown={handleTransactionKeyDown}>
            <style>{`
                .btn-transaction-action:focus {
                    outline: none !important;
                    border: 2px solid #000 !important;
                    box-shadow: 0 0 0 0.3rem rgba(255, 193, 7, 0.4) !important;
                    transform: scale(1.05);
                    transition: all 0.15s ease-in-out;
                }
                .btn-transaction-action.btn-success:focus {
                    box-shadow: 0 0 0 0.3rem rgba(40, 167, 69, 0.4) !important;
                }
                .btn-transaction-action.btn-info:focus {
                    box-shadow: 0 0 0 0.3rem rgba(23, 162, 184, 0.4) !important;
                }
            `}</style>
            <LoadingComponent loading={loading} message="Wait" />
            <Row>
                <Col xs={12} md={7} style={{ marginBottom: '15px' }}>
                    <h4 style={{ fontWeight: '600', color: '#212529', marginBottom: '15px' }}>{currentTitles.tenders}</h4>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                        {tendersApplied?.map((tender, index) => {
                            const paymentMethod = paymentMethodList?.find(method => method.value === tender.tender_code);
                            return paymentMethod ? (
                                <div key={tender.tender_code} style={{ 
                                    display: 'flex', 
                                    alignItems: 'center', 
                                    justifyContent: 'space-between',
                                    padding: '10px 14px', 
                                    backgroundColor: '#f8f9fa', 
                                    borderRadius: '6px',
                                    border: '1px solid #dee2e6' 
                                }}>
                                    <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                                        <span style={{ fontWeight: '600', color: '#6c757d' }}>{index + 1}.</span>
                                        {(!['payment', 'voucher'].includes(paymentMethodList?.find(obj => obj.value == tender.tender_code)?.type)) &&
                                            <IconActionCtl
                                                className="fa fa-trash-o"
                                                handleAction={() => handleDeleteTender(tender?.tender_code)}
                                                style={{ fontSize: 18, color: '#dc3545', cursor: 'pointer', transition: 'color 0.2s' }}
                                                tabIndex={0}
                                            />
                                        }
                                        <span style={{ fontWeight: '500', color: '#495057' }}>
                                            {paymentMethod.icon} {paymentMethod.key}
                                        </span>
                                    </div>
                                    <span style={{ fontWeight: 'bold', color: '#dc3545', fontSize: '1.05em' }}>
                                        {commonFunc.formatNumber(tender.value)}
                                    </span>
                                </div>
                            ) : null;
                        })}
                    </div>
                </Col>
                <Col xs={12} md={5} style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'flex-start', gap: '10px', flexWrap: 'wrap', marginBottom: '15px' }}>
                    <>
                        {
                            (totalAmountRemain > 0) ? (
                                <ButtonCtl
                                    label={<><i className="fa fa-money" style={{ marginRight: '6px' }} aria-hidden="true"></i> {currentTitles.tenderButton}</>}
                                    onClick={handleShowTender}
                                    variant='warning'
                                    type='button'
                                    className="btn-transaction-action"
                                    style={{ padding: '8px 16px', borderRadius: '6px', fontWeight: '600', boxShadow: '0 2px 4px rgba(255,193,7,0.2)' }}
                                    tabIndex="0"
                                    refCtl={btnTenderRef}
                                />                                    
                            ) : null
                        }
                        <ButtonCtl
                            label={<><i className="fa fa-print" style={{ marginRight: '6px' }} aria-hidden="true"></i> {currentTitles.complete}</>}
                            onClick={handleCompleteTransaction}
                            variant='success'
                            type='button'
                            className="btn-transaction-action"
                            style={{ padding: '8px 16px', borderRadius: '6px', fontWeight: '600', display: (totalAmountRemain > 0) ? 'none' : 'inline-block', boxShadow: '0 2px 4px rgba(40,167,69,0.2)' }}
                            tabIndex="0"
                            refCtl={btnPrintRef}
                        />                    
                        <ButtonCtl
                            label={<><i className="fa fa-file-text" style={{ marginRight: '6px' }} aria-hidden="true"></i> {baskets?.basket?.invoice_info == null ? currentTitles.invoice : currentTitles.invoice_edit}</>}
                            onClick={() => setShowModalVAT(true)}
                            variant='info'
                            type='button'
                            className="btn-transaction-action"
                            style={{ padding: '8px 16px', borderRadius: '6px', fontWeight: '600', color: '#fff', boxShadow: '0 2px 4px rgba(23,162,184,0.2)' }}
                            tabIndex="0"
                        />
                    </>
                </Col>
            </Row>
            <Row style={{ 
                border: '1px solid #dee2e6', 
                borderRadius: '8px', 
                padding: '16px', 
                marginTop: '15px', 
                marginBottom: '20px',
                backgroundColor: '#f8f9fa',
                boxShadow: 'inset 0 1px 3px rgba(0,0,0,0.05)',
                marginRight: '0px',
                marginLeft: '0px'
            }}>
                <Col xs={12} md={4} style={{ borderRight: '1px solid #dee2e6', padding: '10px 15px' }}>
                    <div style={{ display: 'flex', flexDirection: 'column' }}>
                        <span style={{ fontSize: '0.9em', color: '#6c757d', fontWeight: '500' }}>{currentTitles.totalAmount}</span>
                        <span style={{ fontSize: '1.4em', fontWeight: '700', color: '#198754', marginTop: '4px' }}>
                            {commonFunc.formatNumber(totalAmount)}
                        </span>
                    </div>
                </Col>
                <Col xs={12} md={4} style={{ borderRight: '1px solid #dee2e6', padding: '10px 15px' }}>
                    <div style={{ display: 'flex', flexDirection: 'column' }}>
                        <span style={{ fontSize: '0.9em', color: '#6c757d', fontWeight: '500' }}>{currentTitles.amountPaid}</span>
                        <span style={{ fontSize: '1.4em', fontWeight: '700', color: '#dc3545', marginTop: '4px' }}>
                            {commonFunc.formatNumber(totalAmountPaid)}
                        </span>
                    </div>
                </Col>
                <Col xs={12} md={4} style={{ padding: '10px 15px' }}>
                    <div style={{ display: 'flex', flexDirection: 'column' }}>
                        <span style={{ fontSize: '0.9em', color: '#6c757d', fontWeight: '500' }}>{currentTitles.amountRemaining}</span>
                        <span style={{ fontSize: '1.4em', fontWeight: '700', color: '#0d6efd', marginTop: '4px' }}>
                            {commonFunc.formatNumber(totalAmountRemain > 0 ? totalAmountRemain : 0)}
                        </span>
                        {totalAmountRemain < 0 &&
                            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '8px', paddingTop: '8px', borderTop: '1px dashed #dee2e6' }}>
                                <span style={{ fontSize: '0.9em', color: '#212529', fontWeight: '600' }}>{currentTitles.excessAmount}:</span>
                                <span style={{ fontSize: '1.1em', fontWeight: '700', color: '#212529' }}>
                                    {commonFunc.formatNumber(totalAmountRemain * -1)}
                                </span>
                            </div>
                        }
                    </div>
                </Col>
            </Row>
            <PopupForm 
                title={config?.lang=='vi'?"Hình thức thanh toán":"Payment Methods"}                
                childComponent={POSTender} show={showModalTender} 
                carts={carts} backdrop={"static"} fullscreen={true}
                setShowForm={setShowModalTender} setShow={setShowModalTender} handleCloseModalTender={() => setShowModalTender(false)}
                paymentMethodList={paymentMethodList} tendersApplied={tendersApplied} setTendersApplied={setTendersApplied} 
                totalAmountRemain={totalAmountRemain} setBaskets={setBaskets} classNameCustom="modal-custom-1" userInfo={userInfo}
                config={config} custCode={baskets?.basket?.cust_code} baskets={baskets}
            />
            {POSVAT &&
                <PopupForm 
                    title={config?.lang=='vi'?"Hóa đơn điện tử":"E-Invoice"}                    
                    childComponent={POSVAT} show={showModalVAT} 
                    backdrop={"static"} fullscreen={true} config={config}
                    setShowForm={setShowModalVAT} setShow={setShowModalVAT} handleClose={() => setShowModalVAT(false)}
                    setBaskets={setBaskets} baskets={baskets} style={{ zIndex: 1070 }} classNameCustom="modal-custom-1" member={member}
                />
            }
            
        </div>
    );
};

const POSTender=(props)=>{
    const {useMemo} =React
    let scriptUrls = [
    ];

    useEffect(() => {
        if(_extension=='js'){
            if(window?.TenderAdapter==null){
                scriptUrls.push('/static/e_comm/components/POS/product_cart/tender_type/tender_type.js')
            }
            if(window?.TenderMedicareVoucher==null){
                scriptUrls.push('/static/e_comm/components/POS/product_cart/tender_type/medicare_voucher.js')
            }
            if(window?.TenderGeneral==null){
                scriptUrls.push('/static/e_comm/components/POS/product_cart/tender_type/general.js')
            }
            if(window?.TenderFinViet==null){
                scriptUrls.push('/static/e_comm/components/POS/product_cart/tender_type/finviet.js')
            }
            if(window?.TenderVNPAY==null){
                scriptUrls.push('/static/e_comm/components/POS/product_cart/tender_type/vnpay.js')
            }
            if(window?.TenderMomo==null){
                scriptUrls.push('/static/e_comm/components/POS/product_cart/tender_type/momo.js')
            }
            if(window?.TenderZalo==null){
                scriptUrls.push('/static/e_comm/components/POS/product_cart/tender_type/zalo.js')
            }
            if(window?.TenderShopee==null){
                scriptUrls.push('/static/e_comm/components/POS/product_cart/tender_type/shopee.js')
            }
            if(window?.TenderGifteeVoucher==null){
                scriptUrls.push('/static/e_comm/components/POS/product_cart/tender_type/giftee.js')
            }
            if(window?.TenderUrBoxVoucher==null){
                scriptUrls.push('/static/e_comm/components/POS/product_cart/tender_type/urbox.js')
            }
            if(window?.TenderGotItVoucher==null){
                scriptUrls.push('/static/e_comm/components/POS/product_cart/tender_type/gotit.js')
            }
            loadScripts(scriptUrls)
                .then(() => {
                    console.log("All scripts loaded successfully.");
                })
                .catch(err => {
                    console.error(err); // Xử lý lỗi nếu có
                });
        }
    }, []); // Chạy chỉ một lần khi component mount
    const { paymentMethodList,tendersApplied,setTendersApplied,  totalAmountRemain,custCode,baskets, setBaskets,handleCloseModalTender, userInfo, carts, config} = props
    const [loading, setLoading] = useState(false)
    const {Row, Col, Button} = ReactBootstrap
    const [showModalTenderLine, setShowModalTenderLine] = useState(false)
    const [tenderSelected, setTenderSelected] = useState()
    const [focusedTender, setFocusedTender] = useState(null)

    const [isFormLoaded, setIsFormLoaded] = useState(false);
    // Gọi hàm này khi form đã load
    const groupedMethods = paymentMethodList?.reduce((acc, method, index) => {
    // Tạo bản sao của phương thức với chỉ số
    const methodWithIndex = { ...method, index }; // Thêm chỉ số vào phương thức
        (acc[method.type] = acc[method.type] || []).push(methodWithIndex);
        return acc;
    }, {});

    const hotkeyMap = useMemo(() => {
        const map = {};
        if (groupedMethods) {
            Object.values(groupedMethods).forEach(methods => {
                methods.forEach(method => {
                    // Đảm bảo hotkey là chữ hoa để khớp với event.key
                    if (method.value) {
                        map[method.value.toUpperCase()] = method;
                    }
                });
            });
        }
        return map;
    }, [groupedMethods]);

    // 1. Chỉ focus vào nút đầu tiên 1 lần duy nhất khi mount component (mở modal)
    useEffect(() => {
        const timer = setTimeout(() => {
            const buttons = document.querySelectorAll('.btn-tender-select');
            for (let button of buttons) {
                if (!button.disabled) {
                    button.focus(); // Gọi focus trên button đầu tiên không bị disabled
                    break;
                }
            }
        }, 150); // Để 150ms cho modal mở hoàn chỉnh
        
        return () => clearTimeout(timer);
    }, []);

    // 2. Quản lý sự kiện phím nóng (hotkeys) toàn cục
    useEffect(() => {
        const handleGlobalKeyDown = (event) => {
            if (showModalTenderLine) {
                return; 
            }
            if (hotkeyMap == null || Object.keys(hotkeyMap).length === 0) {
                return;
            }
            const pressedKey = event.key.toUpperCase();
            const method = hotkeyMap[pressedKey];

            if (method) {
                event.preventDefault(); 
                if (!isMethodDisabled(method)) {
                    handleTenderClick(method);
                }
            }
        };

        document.addEventListener('keydown', handleGlobalKeyDown);

        return () => {
            document.removeEventListener('keydown', handleGlobalKeyDown);
        };
    }, [hotkeyMap]);

    const handleTenderClick = (method) => {
        setTenderSelected(method.value)
        setShowModalTenderLine(true)        
    };
    const backdrop = document.querySelector('.modal-backdrop');
    if (backdrop) {
         //backdrop.classList.add('modal-backdrop-1');
    }
    
    const isMethodDisabled = (method) => {
        const isApplied = tendersApplied?.find(obj => obj.tender_code === method.value);
        const isNineAndNoCustomer = (method.value === '9' && (baskets?.basket?.cust_code === null || baskets?.basket?.cust_code === undefined));
        return isApplied || isNineAndNoCustomer;
    };

    const getTenderColor = (value, isFocused, isDisabled) => {
        if (isDisabled) {
            return {
                border: '1px solid #dee2e6',
                bg: '#e9ecef',
                color: '#6c757d',
                badgeBg: '#adb5bd'
            };
        }
        
        // Bảng màu chuẩn khớp với database: C = Cash, O = Momo, K = Zalo, J = ShopeePay, P/I = VNPAY, 9 = CRM, 1 = CK/CongNo
        const colors = {
            'C': { // Cash - Tiền mặt -> Màu Xanh lá cây (Thanh bình, tin cậy)
                border: '#198754',
                bg: isFocused ? '#e8f5e9' : '#f4faf6',
                color: '#198754',
                badgeBg: '#198754'
            },
            'O': { // Momo QR -> Màu Hồng sen thương hiệu
                border: '#d21f3c',
                bg: isFocused ? '#fce4ec' : '#fff0f5',
                color: '#d21f3c',
                badgeBg: '#d21f3c'
            },
            'K': { // ZaloPay QR -> Màu Xanh lam
                border: '#0084ff',
                bg: isFocused ? '#e1f5fe' : '#f1faff',
                color: '#0084ff',
                badgeBg: '#0084ff'
            },
            'J': { // ShopeePay QR -> Màu Cam đặc trưng
                border: '#ee4d2d',
                bg: isFocused ? '#fbe9e7' : '#fff3e0',
                color: '#ee4d2d',
                badgeBg: '#ee4d2d'
            },
            'P': { // VNPAY QR -> Màu Xanh dương thương hiệu
                border: '#005baa',
                bg: isFocused ? '#e3f2fd' : '#f0f7fc',
                color: '#005baa',
                badgeBg: '#005baa'
            },
            'I': { // VNPAY CARDS -> Màu Xanh dương nhạt
                border: '#007bff',
                bg: isFocused ? '#e7f3ff' : '#f4f9ff',
                color: '#007bff',
                badgeBg: '#007bff'
            },
            'W': { // FinViet QR -> Màu Xám đen công nghệ
                border: '#343a40',
                bg: isFocused ? '#e2e3e5' : '#f8f9fa',
                color: '#343a40',
                badgeBg: '#343a40'
            },
            '9': { // CRM Voucher -> Màu Vàng Gold/Cam ấm
                border: '#ffc107',
                bg: isFocused ? '#fffde7' : '#fffdf0',
                color: '#b78103',
                badgeBg: '#ffc107'
            },
            '1': { // Chuyển khoản / Công nợ -> Màu Slate xám thanh lịch
                border: '#6c757d',
                bg: isFocused ? '#f1f2f3' : '#fafbfc',
                color: '#495057',
                badgeBg: '#6c757d'
            }
        };

        const upperVal = value ? value.toUpperCase() : '';
        
        // So khớp trực tiếp hoặc tương đối
        let match = Object.keys(colors).find(key => upperVal === key);
        if (!match) {
            // Nếu không khớp trực tiếp, check xem có chứa ký tự không (ví dụ cho Voucher hoặc Platform)
            if (['6', '7', 'R', 'S'].includes(upperVal)) {
                // Nhóm các loại Voucher khác -> Màu Hồng phấn nhạt ngọt ngào
                return {
                    border: isFocused ? '2px solid #e685b5' : '1px solid #e685b5',
                    bg: isFocused ? '#fff0f6' : '#fff9fb',
                    color: '#e685b5',
                    badgeBg: '#e685b5'
                };
            }
            if (['3', '4', '5', 'L', 'T', 'H', 'E'].includes(upperVal)) {
                // Nhóm các sàn TMĐT / Đối tác giao hàng -> Màu Teal hiện đại
                return {
                    border: isFocused ? '2px solid #0ea5e9' : '1px solid #0ea5e9',
                    bg: isFocused ? '#f0f9ff' : '#fafefe',
                    color: '#0ea5e9',
                    badgeBg: '#0ea5e9'
                };
            }
        }

        if (match) {
            const scheme = colors[match];
            return {
                border: isFocused ? `2px solid ${scheme.border}` : `1px solid ${scheme.border}`,
                bg: scheme.bg,
                color: scheme.color,
                badgeBg: scheme.badgeBg
            };
        }

        // Mặc định tông màu Cyan thanh lịch
        return {
            border: isFocused ? '2px solid #0dcaf0' : '1px solid #0dcaf0',
            bg: isFocused ? '#e0f7fa' : '#fff',
            color: '#0dcaf0',
            badgeBg: '#0dcaf0'
        };
    };

    const handleContainerKeyDown = (event) => {
        if (showModalTenderLine) {
            return; 
        }

        // Di chuyển bằng phím mũi tên trực tiếp tại container để tránh bị Modal cướp sự kiện
        const arrowKeys = ['ArrowDown', 'ArrowRight', 'ArrowUp', 'ArrowLeft'];
        if (arrowKeys.includes(event.key)) {
            event.preventDefault();
            const buttons = document.querySelectorAll('.btn-tender-select');
            const enabledButtons = Array.from(buttons).filter(btn => !btn.disabled);
            if (enabledButtons.length === 0) return;
            
            const currentButtonIndex = enabledButtons.findIndex(btn => document.activeElement === btn);
            let nextIndex = 0;
            
            if (currentButtonIndex !== -1) {
                if (event.key === 'ArrowDown' || event.key === 'ArrowRight') {
                    nextIndex = (currentButtonIndex + 1) % enabledButtons.length;
                } else {
                    nextIndex = (currentButtonIndex - 1 + enabledButtons.length) % enabledButtons.length;
                }
            } else {
                nextIndex = 0;
            }
            
            enabledButtons[nextIndex].focus();
        }
    };

    return (
        <div onKeyDown={handleContainerKeyDown} tabIndex={-1} style={{ outline: 'none', width: '100%' }}>
            <LoadingComponent loading={loading} message="Wait" />
            {Object.keys(groupedMethods)?.map((type) => (
                <div key={type}>
                    <h5 style={{ 
                        marginTop: '15px', 
                        marginBottom: '8px', 
                        fontWeight: '600', 
                        color: '#495057',
                        borderLeft: '4px solid #0dcaf0',
                        paddingLeft: '10px' 
                    }}>
                        {type.charAt(0).toUpperCase() + type.slice(1)}
                    </h5>
                    <Row>
                        {groupedMethods[type]?.map((method, index) => {
                            const isDisabled = isMethodDisabled(method);
                            const isFocused = focusedTender === method.value;
                            const colors = getTenderColor(method.value, isFocused, isDisabled);
                            return (
                                <Col key={method.value} md={4} sm={6} xs={12}>
                                    <Button
                                        name="btn_tender"
                                        className="btn-tender-select"
                                        variant="light"
                                        tabIndex={0}
                                        onClick={() => handleTenderClick(method)}
                                        disabled={isDisabled}
                                        onFocus={() => setFocusedTender(method.value)}
                                        onBlur={() => setFocusedTender(null)}
                                        style={{
                                            width: '100%',
                                            marginBottom: '8px',
                                            padding: '6px 12px',
                                            borderRadius: '6px',
                                            display: 'flex',
                                            alignItems: 'center',
                                            justifyContent: 'space-between',
                                            fontWeight: '600',
                                            fontSize: '0.9em',
                                            transition: 'all 0.15s ease-in-out',
                                            border: colors.border,
                                            backgroundColor: colors.bg,
                                            color: colors.color,
                                            boxShadow: isDisabled 
                                                ? 'none' 
                                                : (isFocused ? '0 0 0 0.2rem rgba(13, 202, 240, 0.25)' : '0 1px 3px rgba(0,0,0,0.05)')
                                        }}                                 
                                    >
                                        <span style={{
                                            backgroundColor: colors.badgeBg,
                                            color: '#fff',
                                            padding: '2px 6px',
                                            borderRadius: '3px',
                                            fontSize: '0.8em',
                                            fontWeight: '700',
                                            textDecoration: 'none',
                                            minWidth: '20px',
                                            textAlign: 'center'
                                        }}>
                                            {method?.value}
                                        </span>
                                        <span style={{ display: 'flex', alignItems: 'center', gap: '6px', flexGrow: 1, justifyContent: 'center' }}>
                                            {method.icon} {method.key}
                                        </span>                                 
                                    </Button>
                                </Col>
                            );
                        })}
                    </Row>
                </div>
            ))}

            <PopupForm 
                title= {paymentMethodList?.find(obj=> obj.value==tenderSelected)?.key }                
                childComponent={POSTenderLine} show = {showModalTenderLine} 
                backdrop={"static"} fullscreen={true}
                setShowForm={setShowModalTenderLine} setShow={setShowModalTenderLine} handleCloseModalTenderLine={()=>setShowModalTenderLine(false)}
                 setTendersApplied={setTendersApplied}  tenderSelected={tenderSelected} baskets={baskets} handleCloseModalTender={handleCloseModalTender}
                 totalAmountRemain = {totalAmountRemain} setBaskets={setBaskets}   userInfo = {userInfo}
                 carts = {carts} config = {config} custCode = {custCode} paymentType={paymentMethodList?.find(obj=>obj.value==tenderSelected)}
                 classNameCustom="modal-custom-2"
            />
        </div>
    );
};

const POSTenderLine=(props)=>{
    const {tenderSelected, totalAmountRemain, handleCloseModalTenderLine, handleCloseModalTender,baskets, setBaskets, custCode, carts,userInfo, config,paymentType
    } = props
    const amountTenderPayRef = useRef(null);
    const [amountTenderPay, setAmountTenderPay] = useState(0)
    const {  Row, Col } =ReactBootstrap
     useEffect(() => {
        // Đặt amountTenderPay thành totalAmountRemain khi component được mount
        if (paymentType?.type=='voucher' || paymentType?.type=='payment'  ){
            setAmountTenderPay(0);
        }else{
            setAmountTenderPay(totalAmountRemain);
        }
        
    }, [totalAmountRemain]);

    useEffect(() => {
       
        if (amountTenderPayRef?.current){
            amountTenderPayRef.current.focus();
            amountTenderPayRef.current.select();
        }
       
    }, []);
    const backdrop = document.querySelector('.modal-backdrop');
    if (backdrop) {
        //backdrop.classList.add('modal-backdrop-2');
    }
    const handlePayment = () => {
        
        setBaskets(prev => {
            let basket = prev || { basket: { tenders: [] } }; // Khởi tạo nếu prev là null
            
            const existingTenderIndex = (basket?.basket?.tenders || [])?.findIndex(tender => tender.tender_code === tenderSelected);

            if (existingTenderIndex !== -1) {
                // Nếu tender đã tồn tại, cập nhật giá trị
                const updatedTenders = [...basket.basket.tenders];
                updatedTenders[existingTenderIndex].value = amountTenderPay; // Cập nhật giá trị collected
                updatedTenders[existingTenderIndex].contribution = (tenderSelected!='C' ? amountTenderPay : (amountTenderPay>totalAmountRemain? totalAmountRemain:amountTenderPay)) ||0;
                return {
                    ...basket,
                    basket: {
                        ...basket.basket,
                        tenders: updatedTenders
                    }
                };
            } else {
                // Nếu tender chưa tồn tại, thêm mới vào danh sách
                return {
                    ...basket,
                    basket: {
                        ...basket.basket,
                        tenders: [
                            ...basket.basket.tenders || [],
                            {
                                tender_code: tenderSelected,
                                value: amountTenderPay,
                                contribution:( tenderSelected!='C' ? amountTenderPay : (amountTenderPay>totalAmountRemain? totalAmountRemain:amountTenderPay) ) || 0,
                                basket_id: basket?.basket.basket_id
                            }
                        ]
                    }
                };
            }
        });
        // Đóng modal hoặc thực hiện hành động khác
        
        handleCloseModalTenderLine();
        if (totalAmountRemain <= amountTenderPay && handleCloseModalTender){           
            handleCloseModalTender()            
        }
    };    

    const handleAmountTenderPayChange = (e) => {
        const newValue = commonFunc.unFormatCurrency(e.target.value);
        console.log(newValue); // Xem giá trị mới
        setAmountTenderPay(newValue);
    };
    const texts = {
        paymentRemaining: {
            vi: "Còn lại:",
            en: "Remaining:"
        },
        paymentAmount: {
            vi: "Số tiền thanh toán:",
            en: "Payment Amount:"
        },
        close: {
            vi: "Đóng",
            en: "Close"
        },
        pay: {
            vi: "Thanh toán",
            en: "Pay"
        }
    };
    return (
    <div style={{ padding: '10px' }}>
        <Row style={{ 
            backgroundColor: '#f8f9fa', 
            border: '1px solid #dee2e6', 
            borderRadius: '8px', 
            padding: '20px 10px 10px 10px', 
            marginBottom: '20px',
            boxShadow: 'inset 0 1px 2px rgba(0,0,0,0.05)',
            marginRight: '0px',
            marginLeft: '0px'
        }}>
            <Col xs={6}>
                <TextInputCtl
                    label={texts.paymentRemaining[config?.lang] || texts.paymentRemaining.en}
                    placeholder={texts.paymentRemaining[config?.lang] || texts.paymentRemaining.en}
                    value={commonFunc.formatNumber(totalAmountRemain)}
                    onChange={null}
                    type='text'
                    required={false}
                    feedback={null}
                    onEnter={null}
                    size="sm"
                    autoFocus={false}
                    onFocus={null}
                    style={{ textAlign: 'right' }}
                    min={0}
                    styleInput={{ textAlign: 'right', fontWeight: '700', color: '#0d6efd', backgroundColor: '#e9ecef' }}
                    disabled={true}
                    tabIndex="-1"
                />
            </Col>
            <Col xs={6}>
                <TextInputCtl
                    label={texts.paymentAmount[config?.lang] || texts.paymentAmount.en}
                    placeholder={texts.paymentAmount[config?.lang] || texts.paymentAmount.en}
                    value={commonFunc.formatNumber(amountTenderPay)}
                    onChange={(e) => handleAmountTenderPayChange(e)}
                    type='text'
                    required={false}
                    feedback={null}
                    onEnter={handlePayment}
                    size="sm"
                    autoFocus={true}
                    onFocus={null}
                    style={{ textAlign: 'right' }}
                    min={0}
                    styleInput={{ textAlign: 'right', fontWeight: '700', color: '#dc3545', border: '1px solid #ced4da', borderRadius: '4px' }}
                    disabled={((paymentType?.type === 'voucher' || paymentType?.type === 'payment') ? true : false)}
                    tabIndex="1"
                    inputRef={amountTenderPayRef}
                />
            </Col>
        </Row>
        <Row>
            <TenderAdapter config={config} custCode={custCode} carts={carts} setBaskets={setBaskets}  baskets = {baskets}
            userInfo={userInfo} amountRemain={totalAmountRemain} tenderSelected={tenderSelected} 
            setAmountTenderPay={setAmountTenderPay} amountTenderPay={amountTenderPay} handleCloseModalTender={handleCloseModalTender} handleCloseModalTenderLine={handleCloseModalTenderLine}/>
        </Row>
        
    </div>
    );
};