

const ManageShiftClosing = (props) => {
    const {useMemo} = React;
    // Destructuring ReactBootstrap components and props
    const { Row, Col, Table, Card } = ReactBootstrap; // Assuming ReactBootstrap is passed via props or available in context
    const { userInfo, config, shift, handleClose } = props;
    
    // State management
    const [loading, setLoading] = useState(false);
    const [transactions, setTransactions] = useState(null);
    const [staffName, setStaffName] = useState(userInfo?.name);
    const [note, setNote] = useState('');
    const inputCodeRef = useRef(null);
    
    // --- BILINGUAL LABELS ---
    const isVi = config?.lang === 'vi';
    const LABELS = {
        title: isVi ? 'Xác Nhận Kết Ca' : 'Shift Closing Confirmation',
        staffName: isVi ? 'Tên Nhân Viên (*)' : 'Staff Name (*)',
        note: isVi ? 'Ghi Chú' : 'Note',
        reload: isVi ? 'Tải Lại' : 'Reload',
        confirm: isVi ? 'Xác Nhận Kết Ca' : 'Confirm Shift Close',
        close: isVi ? 'Đóng' : 'Close',
        dailyTotal: isVi ? 'TỔNG CỘNG TRONG NGÀY' : 'DAILY TOTAL',
        shiftSubtotal: isVi ? 'TỔNG CA ID' : 'SHIFT ID SUB-TOTAL',
        shiftId: isVi ? 'Mã Ca' : 'Shift ID',
        tenderCode: isVi ? 'Mã Tender' : 'Tender Code',
        tenderDesc: isVi ? 'Loại Thanh Toán' : 'Tender Type',
        transCount: isVi ? 'SL Bill' : 'Trans Count',
        totalAmount: isVi ? 'Tổng Số Tiền' : 'Total Amount',
        noTransactions: isVi ? 'Không tìm thấy giao dịch nào.' : 'No transactions found.',
        confirmAlert: isVi ? "Bạn có chắc muốn kết ca không?" : "Are you sure you want to close this shift?",
        closedBy: isVi ? 'Người Kết Ca' : 'Closed By', 
        statusShift: isVi ? 'Đang chờ xác nhận' : 'Pending Confirmation',
        branchInfo: isVi ? 'Cửa hàng' : 'Store',
    };

    // --- UTILITIES ---
    const formatCurrency = (amount) => {
        // Use 'vi-VN' locale for Vietnamese currency display
        return new Intl.NumberFormat('vi-VN').format(amount || 0);
    };

    // --- DATA TRANSFORMATION (Use useMemo for performance) ---
    const { subtotals, groupedTransactions, dailyTotalAmt, dailyTotalCount } = useMemo(() => {
        if (!transactions || !transactions.data) {
            return { subtotals: {}, groupedTransactions: {}, dailyTotalAmt: 0, dailyTotalCount: 0 };
        }

        const grouped = {};
        const subs = {};
        let dailyTotalAmt = 0;
        let dailyTotalCount = 0;

        transactions.data.forEach(trans => {
            const key = trans.shift_id;

            // Group transactions by shift_id
            if (!grouped[key]) {
                grouped[key] = [];
            }
            grouped[key].push(trans);

            // Calculate subtotals
            if (!subs[key]) {
                subs[key] = { total_cnt: 0, total_amt: 0 };
            }
            subs[key].total_cnt += trans.trans_cnt;
            subs[key].total_amt += trans.total_amt;
            
            // Calculate daily totals
            dailyTotalAmt += trans.total_amt;
            dailyTotalCount += trans.trans_cnt;
        });

        // Ensure keys are sorted for consistent display (optional but recommended)
        const sortedShiftIds = Object.keys(subs).sort((a, b) => a - b);
        const sortedSubtotals = {};
        const sortedGroupedTransactions = {};
        sortedShiftIds.forEach(id => {
            sortedSubtotals[id] = subs[id];
            sortedGroupedTransactions[id] = grouped[id];
        });

        return { 
            subtotals: sortedSubtotals, 
            groupedTransactions: sortedGroupedTransactions, 
            dailyTotalAmt, 
            dailyTotalCount 
        };
    }, [transactions]);


    // --- API CALLS ---
    const handleReloadSalesByShift = async () => {
        try {
            setLoading(true);
            const url = `/api/get-pos-transaction-by-shift?shift_id=${shift?.id}`;
            const resultObj = await commonApi.APIGETByURL(url, config);
            if (resultObj.status === 200) {
                
                setTransactions(resultObj.data);
            } else {
                // Use custom modal/toast instead of alert()
                console.error(resultObj?.data?.message || 'No transactions found for this shift');
                setTransactions({ data: [] });
            }
        } catch (e) {
            console.log("ERROR get-pos-transaction-by-shift", e);
            setTransactions({ data: [] });
        } finally {
            setLoading(false);
            if (inputCodeRef.current) {
                inputCodeRef.current.focus();
                inputCodeRef.current.select();
            }
        }
    };

    const handleFinishShift = async () => {
        const sw = typeof Swal !== 'undefined' ? Swal : (window.Swal || null);
        let userConfirmed = false;
        if (sw) {
            const { isConfirmed } = await sw.fire({
                title: isVi ? "Kết thúc ca?" : "Close Shift?",
                text: LABELS.confirmAlert,
                icon: "question",
                showCancelButton: true,
                confirmButtonColor: "#7c3aed",
                cancelButtonColor: "#64748b",
                confirmButtonText: isVi ? "Xác nhận" : "Confirm",
                cancelButtonText: isVi ? "Hủy" : "Cancel"
            });
            userConfirmed = isConfirmed;
        } else {
            userConfirmed = window.confirm(LABELS.confirmAlert);
        }
        if (!userConfirmed) {
            return;
        }

        if (transactions?.data?.find(obj=>obj.shift_id===shift?.id)?.length===0){
            if (sw) {
                sw.fire({
                    icon: 'warning',
                    title: isVi ? "Không có giao dịch nào để kết ca!" : "No transactions to close shift!",
                    confirmButtonColor: '#7c3aed'
                });
            } else {
                alert(isVi ? "Không có giao dịch nào để kết ca!" : "No transactions to close shift!");
            }
            return;
        }
        try {  
            setLoading(true);   
            const data = {
                "branch_no": 0, // Assuming this is correct
                "is_open": false,
                "staff_name": staffName, // Add required staff name
                "note": note, // Add note
                // Optional: Pass shift summary data if required by API
            };

            const url = `/api/create-or-update-mdc-store-shifts`;
            const resultObj = await commonApi.APIPOSTByURL(url, data, config);           
            
            if (resultObj.status === 201) {                
               props.setShift(null); // Assuming setShift is passed via props
               handleClose(); // Close the modal/component
               window.location.reload(); // Reload the page to reflect changes
            } else {
                console.error("Failed to close shift:", resultObj);
            }
        } catch (e) {                  
            console.log("ERROR create-or-update-mdc-store-shifts", e);
        } finally {
            setLoading(false);
        }
    };

    // --- LIFECYCLE ---
    useEffect(() => {
        handleReloadSalesByShift();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    // --- RENDER LOGIC ---

    // Check if data is available and ready for display
    if (!transactions) {
        return <LoadingComponent loading={true} message={isVi ? "Đang tải giao dịch..." : "Loading transactions..."} />;
    }

    if (transactions?.data?.length === 0) {
        return <div className="p-4 text-center text-gray-500">{LABELS.noTransactions}</div>;
    }

    return (
        <div className="p-1 space-y-1">
            <LoadingComponent loading={loading} message={isVi ? "Đang xử lý..." : "Processing..."} />
            {transactions?.data?.find(obj=>obj.shift_id===shift?.id)?.length>0 ?
                <h4 className="text-xl font-bold mb-1" style={{color:'red'}}>{LABELS.title} : {transactions?.data?.find(obj=>obj.shift_id===shift?.id)?.shift_name} ( {LABELS.branchInfo}: {  userInfo?.branch_no})</h4>:
                <h4 className="text-xl font-bold mb-1" style={{color:'red'}}>{LABELS.noTransactions} ( {LABELS.branchInfo}: {  userInfo?.branch_no})</h4>
            }
            
            {/* SECTION 1: INPUTS AND ACTIONS */}
            <Card className="shadow-sm">
                <Card.Body>
                    <Row className="g-3 align-items-end">
                        <Col xs={12} md={4}>
                            <TextInputCtl
                                id="txtStaffName"
                                label={LABELS.staffName}
                                placeholder={LABELS.staffName}
                                value={staffName}
                                onChange={(e) => setStaffName(e.target.value)}
                                type='text'
                                size="sm"
                                autoFocus={true}
                                inputRef={inputCodeRef}
                                tabIndex={1}
                            />
                            
                        </Col>
                        <Col xs={12} md={6}>
                            <TextInputCtl
                                id="txtNote"
                                label={LABELS.note}
                                placeholder={LABELS.note}
                                value={note}
                                onChange={(e) => setNote(e.target.value)}
                                type='text'
                                size="sm"
                                tabIndex={2}
                            />
                        </Col>
                        <Col xs={12} md={2} className="text-right">
                            <ButtonCtl
                                label={<><i className="fa fa-refresh mr-2" />{LABELS.reload}</>}
                                onClick={handleReloadSalesByShift}
                                variant='outline-primary'
                                type='button'
                                tabIndex={3}
                                style={{ width: '100%' }}
                            />
                        </Col>
                    </Row>
                </Card.Body>
            </Card>

            {/* SECTION 2: DAILY TOTAL SUMMARY (No Table used, prominent display) */}
            <Card className="shadow-lg bg-indigo-500 text-black">
                <Card.Body>
                    <h5 className="mb-1 font-semibold uppercase">{LABELS.dailyTotal}</h5>
                    <Row className="text-center">
                        <Col xs={6} className="border-r border-indigo-400">
                            <div className="text-sm opacity-90">{LABELS.transCount}</div>
                            <div className="text-3xl font-extrabold">{dailyTotalCount}</div>
                        </Col>
                        <Col xs={6}>
                            <div className="text-sm opacity-90">{LABELS.totalAmount}</div>
                            <div className="text-3xl font-extrabold">{formatCurrency(dailyTotalAmt)}</div>
                        </Col>
                    </Row>
                </Card.Body>
            </Card>

            {/* SECTION 3: DETAILED SHIFT BREAKDOWN (Grouped Tables) */}
            <div className="space-y-4 max-h-96 overflow-y-auto">
                {Object.entries(groupedTransactions).map(([shiftId, shiftTransactions]) => (
                    <Card key={shiftId} className="shadow-sm border-2 border-indigo-200">
                        {/* Subtotal Header */}
                        <Card.Header className="bg-indigo-100 font-semibold p-0 flex justify-between items-center" style={{display:'none'}}>
                            <span style={{color:'blue', fontStyle:'bold'}}>{LABELS.shiftSubtotal}:  {shiftTransactions[0]?.shift_name}</span>
                            <span style={{float:'right', fontStyle:'bold', color:'red'}} className="text-lg text-indigo-700">
                                {formatCurrency(subtotals[shiftId].total_amt)}
                            </span>
                        </Card.Header>

                        {/* Transaction Details Table */}
                        <Table striped hover responsive size="sm" className="mb-0">
                            <thead>
                                <tr className="text-xs">
                                    <th style={{width:'10%'}}>{LABELS.tenderCode}</th>
                                    <th style={{width:'60%'}}>{LABELS.tenderDesc}</th>
                                    <th style={{width:'10%'}} className="text-right">{LABELS.transCount}</th>
                                    <th style={{width:'20%'}} className="text-right">{LABELS.totalAmount}</th>
                                </tr>
                            </thead>
                            <tbody>
                                {shiftTransactions?.map((transaction, index) => (
                                    <tr key={index}>
                                        <td className="align-middle">{transaction.tender_code}</td>
                                        <td className="align-middle">{transaction.tender_desc}</td>
                                        <td className="text-right align-middle">{transaction.trans_cnt}</td>
                                        <td className="text-right align-middle">{formatCurrency(transaction.total_amt)}</td>
                                    </tr>
                                ))}
                            </tbody>
                            <tfoot className="bg-indigo-200/50 font-bold">
                                <tr style={{color:'red', fontWeight:'bold'}}>
                                    {shiftTransactions[0]?.staff_name  ? 
                                        <td colSpan={2} style={{color:shiftTransactions[0]?.shift_name?"blue":"red"}}>  {LABELS.shiftSubtotal}  {shiftTransactions[0]?.shift_name}  ( {LABELS.closedBy} : {  shiftTransactions[0]?.staff_name})</td>:
                                        <td colSpan={2}>  {LABELS.shiftSubtotal}  {shiftTransactions[0]?.shift_name} ({LABELS.statusShift}) </td>
                                    }
                                    
                                    <td className="text-right">{subtotals[shiftId].total_cnt}</td>
                                    <td className="text-right"><span  style={{float:'right', fontStyle:'bold', color:'red'}}>{formatCurrency(subtotals[shiftId].total_amt)}</span></td>
                                </tr>
                            </tfoot>
                        </Table>
                    </Card>
                ))}
            </div>

            {/* SECTION 4: FOOTER ACTIONS */}
            <Row className="pt-3 border-t">
                <Col xs={12} className="text-right space-x-2">
                    <ButtonCtl
                        label={<><i className="fa fa-window-close mr-2" />{LABELS.close}</>}
                        onClick={handleClose}
                        variant='secondary'
                        type='button'
                        tabIndex={11}
                    />
                    {transactions?.data?.find(obj=>obj.shift_id===shift?.id)?.length >0 &&
                          <ButtonCtl
                            label={<><i className="fa fa-check-square-o mr-2" />{LABELS.confirm}</>}
                            onClick={handleFinishShift}
                            variant='danger'
                            type='button'
                            disabled={staffName.trim() === ''} // Disable if staff name is empty
                            tabIndex={10}
                        />
                    }
                  
                </Col>
            </Row>
        </div>
    );
};