const ManageBasketDraft = (props) => {
    const { getBasketsDraft, handleClose, setBaskets, config } = props;
    const { ListGroup, Row, Col } = ReactBootstrap;
    const [loading, setLoading] = useState(false);
    const btnOpenDraftRef = useRef(null);
    // Mẫu dữ liệu giỏ hàng tạm thời
    let basketListTmp = getBasketsDraft();
    const [basketList, setBasketList] = useState(basketListTmp)

    // Tính tổng số lượng cho mỗi giỏ hàng
    const calculateTotalQty = (items) => {
        return items?.reduce((total, item) => total + item.qty, 0);
    };

    const handleSelectBasket = (basket) => {
        handleOpenDraft(basket);
        handleClose(); // Đóng modal sau khi chọn
    };

    const handleOpenDraft = (basket) => {
        let jTmpBasket = getBasketsDraft();
        
        if (jTmpBasket?.length > 0) {
            const basketSelect = jTmpBasket.find(b => b.basket_id === basket.basket_id);
            if (basketSelect) {
                const updatedBasket = jTmpBasket.filter(b => b.basket_id !== basketSelect.basket_id);       
                commonFunc.setCookies('tmp_baskets', JSON.stringify(updatedBasket), undefined);            
                setBaskets(basketSelect);
            }
        }
    };

    const handleRemoveBasket = async (basket) => {
        const sw = typeof Swal !== 'undefined' ? Swal : (window.Swal || null);
        let confirmDelete = false;
        if (sw) {
            const { isConfirmed } = await sw.fire({
                title: "Xóa giỏ hàng nháp?",
                text: "Bạn có chắc muốn xóa basket này?",
                icon: "question",
                showCancelButton: true,
                confirmButtonColor: "#7c3aed",
                cancelButtonColor: "#64748b",
                confirmButtonText: "Xác nhận",
                cancelButtonText: "Hủy"
            });
            confirmDelete = isConfirmed;
        } else {
            confirmDelete = confirm("Bạn có chắc muốn xóa basket này?");
        }
        if (!confirmDelete) {
            return;
        }
        
        let jTmpBasket = getBasketsDraft();
        const updatedBasket = jTmpBasket.filter(b => b?.basket?.basket_id !== basket?.basket.basket_id);

        commonFunc.setCookies('tmp_baskets', JSON.stringify(updatedBasket), undefined);
        setBasketList(getBasketsDraft())
    };
    useEffect(() => {
        if (btnOpenDraftRef.current) {
            btnOpenDraftRef .current.focus(); // Tự động tập trung vào Button khi load
        }
    }, []); // Chạy chỉ một lần sau khi component render
    return (
        <>
            <LoadingComponent loading={loading} message="Wait" />        
            <ListGroup>
                {basketList?.map((basket) => (
                    <ListGroup.Item key={basket?.basket?.basket_id}>
                        <Row>
                            <Col xs={6}>
                                <strong>{config?.lang=='vi'?"Mã Giỏ Hàng:":"Basket ID:"}</strong> {basket?.basket?.basket_id}
                            </Col>                        
                            <Col xs={6}>
                                <strong>{config?.lang=='vi'?"Ngày:":"Date:"}</strong> {commonFunc.formatDate(new Date(basket?.basket?.basket_date),"DD-MM-YYYY HH:mm") }
                            </Col>
                        </Row>
                        <Row>
                            <Col xs={6}>
                                <strong>{config?.lang=='vi'?"Mã Khách Hàng:":"Customer Code:"}</strong> {basket?.basket?.cust_code}
                            </Col>
                            <Col xs={6}>
                                <strong>{config?.lang=='vi'?"Tổng SL:":"Total Q.ty:"}</strong> {calculateTotalQty(basket?.items)}
                            </Col>
                        </Row>
                        <Row>
                            <Col xs={6}>
                                {basket &&                         
                                <ButtonCtl                             
                                    label={<i class="fa fa-check-square-o" style={{paddingRight:4}} aria-hidden="true">{config?.lang=='vi'?"Chọn":"Select"}</i>}
                                    onClick={() => handleSelectBasket(basket)}
                                    variant='primary'
                                    type='button'
                                    style={{margin:'10px 0px 0px 10px', float:'left'}}
                                    tabIndex={1}
                                    refCtl={btnOpenDraftRef}
                                    />
                                }
                            </Col>
                            <Col xs={6}>
                                {basket &&                          
                                <ButtonCtl
                                    label={<i class="fa fa-window-close" style={{paddingRight:4}} aria-hidden="true">{config?.lang=='vi'?"Xóa":"Del"}</i>}
                                    onClick={() => handleRemoveBasket(basket)}
                                    variant='danger'
                                    type='button'
                                    style={{margin:'10px 0px 0px 10px', float:'right'}}
                                    tabIndex={2}
                                    />
                                }
                            </Col>
                        </Row>                        
                    </ListGroup.Item>
                ))}
                <ButtonCtl 
                    label={<i class="fa fa-window-close" style={{paddingRight:4}} aria-hidden="true">{config?.lang=='vi'?"Đóng":"Close"}</i>}
                    onClick={()=>handleClose()}
                    variant='secondary'
                    type='button'
                    style={{margin:'10px 0px 0px 10px', float:'right'}}
                    tabIndex={3}
                    />
            </ListGroup>
        </>
    );
};