import React from 'react';
import superagent from 'superagent';
import { Segment, Header, Message, Button, Icon, Table, Modal, Label } from 'semantic-ui-react';

import * as ApiUtils from '../CloudApi/ApiUtils.js';
import BigShipperWrapper from './BigShipperWrapper.jsx';
import BigApiErrorMessage from '../CloudApi/BigApiErrorMessage.jsx';
import BigOrdersQueryEnhanced from '../BigOrders/BigOrdersQueryEnhanced.jsx';
import BigOrderTableCells from '../BigOrders/BigOrderTableCells.jsx';
import ApiButtonModal from '../CloudApi/ApiButtonModal.jsx';

export default class BigBatchShipper extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            shipperResults: [],
            selectedOrders: new Set(),
            processingOrders: new Set(),
            completedOrders: new Set(),
            batchShippingInProgress: false,
            showResultsModal: false,
            batchShippingResults: [],
            showCancelModal: false,
            showErrorModal: false,
            batchError: null,
            processingLog: [],
            logExpanded: false,
            batchShippingMode: null, // null = not selected, 'labelsOnly' or 'generateAll'
        };
        this.cancelRequested = false;
        this.printIframeRefs = {};
    }

    async componentDidMount() {
        try {
            let schemas = await ApiUtils.getFabricatorSchemas();
            this.setState({ schemas });
        } catch (e) {
            console.log(e);
        }
    }

    addLogEntry(message, type = 'info') {
        const entry = {
            id: Date.now() + Math.random(),
            timestamp: new Date().toLocaleTimeString(),
            message,
            type
        };
        this.setState(prevState => ({
            processingLog: [...prevState.processingLog, entry]
        }));
        console.log(`[${entry.timestamp}] ${message}`);
    }

    clearLog() {
        this.setState({ processingLog: [] });
    }

    async onUpdateQuery(params) {
        this.setState({ loading: true, shipperResults: [], selectedOrders: new Set() });
        let shipperResults = [];

        try {
            const result = await superagent.get(`/api/admin/shipper/next3?${params.toString()}`);
            shipperResults = result.body;
        } catch (e) {
            console.log(e);
        }

        this.setState({
            shipperResults,
            loading: false
        });
    }

    toggleOrderSelection(bigOrderId) {
        const selectedOrders = new Set(this.state.selectedOrders);
        if (selectedOrders.has(bigOrderId)) {
            selectedOrders.delete(bigOrderId);
        } else {
            selectedOrders.add(bigOrderId);
        }
        this.setState({ selectedOrders });
    }

    selectAllOrders() {
        const selectedOrders = new Set();
        this.state.shipperResults.forEach(result => {
            selectedOrders.add(result.bigOrder.id);
        });
        this.setState({ selectedOrders });
    }

    deselectAllOrders() {
        this.setState({ selectedOrders: new Set() });
    }

    printShippingLabel(shipmentId, labelUrl) {
        return new Promise((resolve, reject) => {
            this.addLogEntry(`Loading label for printing: ${labelUrl}`, 'info');

            // Create a hidden iframe for printing
            const iframe = document.createElement('iframe');
            iframe.style.position = 'absolute';
            iframe.style.left = '-9999px';
            iframe.style.width = '1px';
            iframe.style.height = '1px';
            iframe.src = `/file/${encodeURIComponent(labelUrl)}#toolbar=0&navpanes=0&scrollbar=0`;

            // Store reference
            this.printIframeRefs[shipmentId] = iframe;

            // Set a timeout in case the iframe fails to load
            const loadTimeout = setTimeout(() => {
                this.addLogEntry(`Label load timeout for shipment ${shipmentId}`, 'warning');
                resolve(); // Continue anyway to not block batch processing
            }, 10000);

            // Handle load errors
            iframe.onerror = (e) => {
                clearTimeout(loadTimeout);
                this.addLogEntry(`Failed to load label for shipment ${shipmentId}: ${e}`, 'error');
                resolve(); // Continue anyway
            };

            // When the iframe loads, print it
            iframe.onload = () => {
                clearTimeout(loadTimeout);
                this.addLogEntry(`Label loaded, sending to printer (shipment ${shipmentId})...`, 'info');

                try {
                    iframe.focus();
                    iframe.contentWindow.print();
                    this.addLogEntry(`Print command sent for shipment ${shipmentId}`, 'success');
                } catch (e) {
                    this.addLogEntry(`Error sending print command: ${e.message}`, 'error');
                    console.error('Error printing label:', e);
                }

                // In kiosk mode with silent printing, print() returns immediately
                // Give a short delay to ensure the print job is queued
                setTimeout(() => {
                    resolve();
                }, 500);
            };

            // Add to document
            document.body.appendChild(iframe);
        });
    }

    cleanupPrintIframes() {
        // Remove all print iframes
        Object.values(this.printIframeRefs).forEach(iframe => {
            if (iframe && iframe.parentNode) {
                iframe.parentNode.removeChild(iframe);
            }
        });
        this.printIframeRefs = {};
    }

    async onCreateShipment(bigOrderId, shipmentGroupId) {
        this.setState({ loading: true });
        try {
            const res = await superagent.post(`/api/admin/shipper/shipment`).send({
                bigOrderId,
                shipmentGroupId
            });
            window.location.href = `/shipper/shipment/${res.body.id}`;
        } catch (e) {
            console.log(e);
            this.setState({ loading: false });
        }
    }

    async processSingleOrder(bigOrderId) {
        try {
            // Find the shipment for this order
            const shipperResult = this.state.shipperResults.find(r => r.bigOrder.id === bigOrderId);
            if (!shipperResult) {
                throw new Error('Shipment not found for order');
            }

            const shipmentGroupId = shipperResult.shipmentGroupId;
            this.addLogEntry(`Processing order ${bigOrderId} with shipment group ${shipmentGroupId}`, 'info');

            // Step 1: Create shipment
            this.addLogEntry(`Creating shipment for order ${bigOrderId}...`, 'info');
            const createRes = await superagent.post(`/api/admin/shipper/shipment`).send({
                bigOrderId,
                shipmentGroupId
            });
            const shipmentId = createRes.body.id;
            this.addLogEntry(`Created shipment ${shipmentId}`, 'success');

            // Get shipment details
            let shipmentRes = await superagent.get(`/api/admin/shipper/shipment/${shipmentId}`).accept('json');
            let bigShipment = shipmentRes.body.bigShipment;
            this.addLogEntry(`Shipment status: ${bigShipment.status}, ${bigShipment.inventorySlots.length} inventory slot(s)`, 'info');

            // Step 2: Picking - automatically pick all items
            if (bigShipment.status === "Picking") {
                this.addLogEntry(`Starting picking phase...`, 'info');

                // Log all inventory slots
                for (const slot of bigShipment.inventorySlots) {
                    this.addLogEntry(`  Slot ${slot.id}: ${slot.productType} - status: ${slot.status}`, 'info');
                }

                // Pick all inventory slots that need to be picked
                for (const inventorySlot of bigShipment.inventorySlots) {
                    if (inventorySlot.status !== "InventoryItemAdded") {
                        this.addLogEntry(`  Picking ${inventorySlot.productType} (slot ${inventorySlot.id})...`, 'info');
                        await superagent.put(`/api/admin/shipper/shipment/${shipmentId}`)
                            .send({
                                action: "PickInventoryItem",
                                inventorySlotId: inventorySlot.id,
                            });
                        this.addLogEntry(`  Picked ${inventorySlot.productType} successfully`, 'success');
                    } else {
                        this.addLogEntry(`  Slot ${inventorySlot.id} (${inventorySlot.productType}) already picked`, 'info');
                    }
                }

                // Refresh shipment to get updated inventory slot statuses after picking
                this.addLogEntry(`Refreshing shipment status after picking...`, 'info');
                shipmentRes = await superagent.get(`/api/admin/shipper/shipment/${shipmentId}`).accept('json');
                bigShipment = shipmentRes.body.bigShipment;

                // Log updated slot statuses
                for (const slot of bigShipment.inventorySlots) {
                    this.addLogEntry(`  Slot ${slot.id}: ${slot.productType} - status: ${slot.status}`, 'info');
                }

                // Verify all items have been picked before finishing
                const unpickedItems = bigShipment.inventorySlots.filter(
                    slot => slot.status !== "InventoryItemAdded"
                );

                if (unpickedItems.length > 0) {
                    const unpickedTypes = unpickedItems.map(slot => `${slot.productType} (${slot.status})`).join(", ");
                    this.addLogEntry(`ERROR: ${unpickedItems.length} item(s) not picked: ${unpickedTypes}`, 'error');
                    throw new Error(`Cannot finish picking: ${unpickedItems.length} item(s) not picked (${unpickedTypes})`);
                }

                // Finish picking
                this.addLogEntry(`All items picked, finishing picking phase...`, 'info');
                await superagent.put(`/api/admin/shipper/shipment/${shipmentId}`)
                    .send({ action: "FinishPicking" });
                this.addLogEntry(`Picking phase completed`, 'success');

                // Refresh shipment status
                shipmentRes = await superagent.get(`/api/admin/shipper/shipment/${shipmentId}`).accept('json');
                bigShipment = shipmentRes.body.bigShipment;
                this.addLogEntry(`Shipment status: ${bigShipment.status}`, 'info');
            }

            // Step 3: Generate and print shipping label
            if (bigShipment.status === "PrepareShippingLabel") {
                this.addLogEntry(`Generating shipping label...`, 'info');
                await superagent.put(`/api/admin/shipper/shipment/${shipmentId}`)
                    .send({ action: "GenerateShippingLabel" });

                // Refresh shipment status to get the label
                shipmentRes = await superagent.get(`/api/admin/shipper/shipment/${shipmentId}`).accept('json');
                bigShipment = shipmentRes.body.bigShipment;

                // Print the shipping label
                if (bigShipment.currentShippingLabel) {
                    const labelUrl = bigShipment.currentShippingLabel.upload_label_url || bigShipment.currentShippingLabel.uploadLabelUrl;
                    if (labelUrl) {
                        this.addLogEntry(`Printing shipping label...`, 'info');
                        await this.printShippingLabel(shipmentId, labelUrl);
                        this.addLogEntry(`Label sent to printer`, 'success');
                    }
                }
            }

            // Step 4: Packing
            if (bigShipment.status === "PrepareShippingLabel") {
                this.addLogEntry(`Starting packing phase...`, 'info');
                await superagent.put(`/api/admin/shipper/shipment/${shipmentId}`)
                    .send({ action: "StartPacking" });

                await superagent.put(`/api/admin/shipper/shipment/${shipmentId}`)
                    .send({ action: "FinishPacking" });
                this.addLogEntry(`Packing phase completed`, 'success');

                // Refresh shipment status
                shipmentRes = await superagent.get(`/api/admin/shipper/shipment/${shipmentId}`).accept('json');
                bigShipment = shipmentRes.body.bigShipment;
            }

            // Step 5: Complete shipment (only if generateAll mode)
            if (this.state.batchShippingMode === 'generateAll') {
                if (bigShipment.status === "PreparingToShip") {
                    this.addLogEntry(`Completing shipment...`, 'info');
                    await superagent.put(`/api/admin/shipper/shipment/${shipmentId}`)
                        .send({ action: "ShipIt" });
                    this.addLogEntry(`Shipment completed`, 'success');

                    // Refresh shipment status
                    shipmentRes = await superagent.get(`/api/admin/shipper/shipment/${shipmentId}`).accept('json');
                    bigShipment = shipmentRes.body.bigShipment;
                }
            } else if (this.state.batchShippingMode === 'labelsOnly' && bigShipment.status === "PreparingToShip") {
                this.addLogEntry(`Label generated - skipping fulfillment (labels only mode)`, 'info');
            }


            this.addLogEntry(`Order ${bigOrderId} completed successfully (shipment ${shipmentId})`, 'success');
            return {
                bigOrderId,
                shipmentId,
                success: true,
                message: `Shipment ${shipmentId} created and processed successfully`
            };
        } catch (error) {
            this.addLogEntry(`ERROR processing order ${bigOrderId}: ${error.message || error}`, 'error');
            console.error('Error processing order:', bigOrderId, error);
            // Re-throw the error so it can be caught by onBatchShip
            throw {
                bigOrderId,
                originalError: error,
                message: error.message || error.toString(),
                status: error.status,
                response: error.response
            };
        }
    }

    async onBatchShip() {
        this.cancelRequested = false;
        this.clearLog();
        this.setState({
            batchShippingInProgress: true,
            batchShippingResults: [],
            batchError: null
        });

        const selectedOrderIds = Array.from(this.state.selectedOrders);
        const results = [];

        this.addLogEntry(`Starting batch shipping for ${selectedOrderIds.length} order(s)`, 'info');

        try {
            // Process each order in series
            for (const bigOrderId of selectedOrderIds) {
                // Check if cancellation was requested
                if (this.cancelRequested) {
                    results.push({
                        bigOrderId,
                        success: false,
                        message: 'Cancelled by user'
                    });
                    continue;
                }

                // Mark order as processing
                this.setState(prevState => ({
                    processingOrders: new Set(prevState.processingOrders).add(bigOrderId)
                }));

                try {
                    const result = await this.processSingleOrder(bigOrderId);
                    results.push(result);

                    // Mark order as completed
                    this.setState(prevState => {
                        const newProcessing = new Set(prevState.processingOrders);
                        newProcessing.delete(bigOrderId);
                        const newCompleted = new Set(prevState.completedOrders);
                        newCompleted.add(bigOrderId);
                        const newSelected = new Set(prevState.selectedOrders);
                        newSelected.delete(bigOrderId);

                        return {
                            processingOrders: newProcessing,
                            completedOrders: newCompleted,
                            selectedOrders: newSelected
                        };
                    });
                } catch (error) {
                    // Stop processing immediately on error
                    console.error('Error processing order, stopping batch:', bigOrderId, error);

                    // Mark current order as failed and remove from processing
                    this.setState(prevState => {
                        const newProcessing = new Set(prevState.processingOrders);
                        newProcessing.delete(bigOrderId);

                        return {
                            processingOrders: newProcessing,
                            batchShippingInProgress: false,
                            batchError: error,
                            showErrorModal: true
                        };
                    });

                    // Cleanup and stop
                    this.cancelRequested = false;
                    this.cleanupPrintIframes();
                    return; // Exit the function immediately
                }
            }

            // All orders processed successfully - show results modal
            this.setState({
                batchShippingInProgress: false,
                batchShippingResults: results,
                showResultsModal: true
            });

            // Cleanup print iframes after a delay (to ensure printing is complete)
            setTimeout(() => {
                this.cleanupPrintIframes();
            }, 5000);
        } catch (unexpectedError) {
            // Handle any unexpected errors
            console.error('Unexpected error in batch processing:', unexpectedError);
            this.setState({
                batchShippingInProgress: false,
                batchError: unexpectedError,
                showErrorModal: true
            });
            this.cleanupPrintIframes();
        }

        this.cancelRequested = false;
    }

    closeResultsModal() {
        this.setState({ showResultsModal: false });
    }

    closeErrorModal() {
        this.setState({ showErrorModal: false, batchError: null });
    }

    onRequestCancel() {
        this.setState({ showCancelModal: true });
    }

    closeCancelModal() {
        this.setState({ showCancelModal: false });
    }

    onConfirmCancel() {
        this.cancelRequested = true;
        this.setState({ showCancelModal: false });
    }

    render() {
        if (!this.state.schemas) return null;

        const allSelected = this.state.shipperResults.length > 0 &&
            this.state.shipperResults.every(result => this.state.selectedOrders.has(result.bigOrder.id));

        let bigShipperResults = null;
        if (this.state.shipperResults && this.state.shipperResults.length > 0) {
            bigShipperResults = this.state.shipperResults.map((result) => {
                const isSelected = this.state.selectedOrders.has(result.bigOrder.id);
                const isProcessing = this.state.processingOrders.has(result.bigOrder.id);
                const isCompleted = this.state.completedOrders.has(result.bigOrder.id);
                const isDisabled = isProcessing || isCompleted || this.state.batchShippingInProgress;

                return (
                    <Table.Row
                        key={result.bigOrder.id}
                        style={{ cursor: isDisabled ? 'default' : 'pointer' }}
                        onClick={(e) => {
                            if (!isDisabled) {
                                e.stopPropagation();
                                this.toggleOrderSelection(result.bigOrder.id);
                            }
                        }}
                        positive={isSelected && !isCompleted}
                        active={isCompleted}
                    >
                        <Table.Cell collapsing onClick={(e) => e.stopPropagation()}>
                            {isProcessing && (
                                <Icon name='circle notched' loading color='blue' />
                            )}
                            {isCompleted && (
                                <Icon name='check circle' color='green' size='large' />
                            )}
                            {!isProcessing && !isCompleted && (
                                <input
                                    type="checkbox"
                                    checked={isSelected}
                                    onChange={() => this.toggleOrderSelection(result.bigOrder.id)}
                                    disabled={this.state.batchShippingInProgress}
                                    style={{ cursor: this.state.batchShippingInProgress ? 'not-allowed' : 'pointer' }}
                                />
                            )}
                        </Table.Cell>
                        <BigOrderTableCells
                            bigOrder={result.bigOrder}
                            shipmentGroupId={result.shipmentGroupId}
                        />
                    </Table.Row>
                );
            });
        } else {
            bigShipperResults = (
                <Table.Row>
                    <Table.Cell colSpan="10">
                        <Message warning>
                            <Message.Header>No big orders to ship</Message.Header>
                            <p>There are no big orders to ship with this selection!</p>
                        </Message>
                    </Table.Cell>
                </Table.Row>
            );
        }

        const successCount = this.state.batchShippingResults.filter(r => r.success).length;
        const failureCount = this.state.batchShippingResults.filter(r => !r.success).length;

        return (
            <BigShipperWrapper title="📦 Batch Shipper" loading={this.state.loading}>
                <Modal
                    dimmer="inverted"
                    closeOnEscape={true}
                    closeOnDimmerClick={true}
                    closeIcon
                    onClose={this.closeErrorModal.bind(this)}
                    open={this.state.showErrorModal}
                >
                    <Header icon='exclamation triangle' content='Batch Shipping Error' color='red' />
                    <Modal.Content>
                        <Message error>
                            <Message.Header>An error occurred during batch processing</Message.Header>
                            <p>Processing has been stopped to prevent further issues.</p>
                        </Message>
                        {this.state.batchError && (
                            <Segment>
                                <Header as="h4">Error Details</Header>
                                <Table celled>
                                    <Table.Body>
                                        <Table.Row>
                                            <Table.Cell><strong>Order ID:</strong></Table.Cell>
                                            <Table.Cell>{this.state.batchError.bigOrderId}</Table.Cell>
                                        </Table.Row>
                                        <Table.Row>
                                            <Table.Cell><strong>Error Message:</strong></Table.Cell>
                                            <Table.Cell>{this.state.batchError.message}</Table.Cell>
                                        </Table.Row>
                                        {this.state.batchError.status && (
                                            <Table.Row>
                                                <Table.Cell><strong>HTTP Status:</strong></Table.Cell>
                                                <Table.Cell>{this.state.batchError.status}</Table.Cell>
                                            </Table.Row>
                                        )}
                                        {this.state.batchError.response && this.state.batchError.response.body && (
                                            <Table.Row>
                                                <Table.Cell><strong>Server Response:</strong></Table.Cell>
                                                <Table.Cell>
                                                    <pre style={{ maxHeight: '200px', overflow: 'auto' }}>
                                                        {JSON.stringify(this.state.batchError.response.body, null, 2)}
                                                    </pre>
                                                </Table.Cell>
                                            </Table.Row>
                                        )}
                                    </Table.Body>
                                </Table>
                            </Segment>
                        )}
                        <BigApiErrorMessage error={this.state.batchError ? this.state.batchError.originalError : null} />
                    </Modal.Content>
                    <Modal.Actions>
                        <Button color='blue' onClick={this.closeErrorModal.bind(this)}>
                            <Icon name='checkmark' />
                            Close
                        </Button>
                    </Modal.Actions>
                </Modal>

                <Modal
                    dimmer="inverted"
                    closeOnEscape={true}
                    closeOnDimmerClick={true}
                    closeIcon
                    onClose={this.closeCancelModal.bind(this)}
                    open={this.state.showCancelModal}
                >
                    <Header icon='stop' content='Cancel Batch Shipping' />
                    <Modal.Content>
                        <Message warning>
                            <Message.Header>Are you sure you want to cancel?</Message.Header>
                            <p>This will stop processing any remaining orders. Orders that have already been processed will remain completed.</p>
                        </Message>
                    </Modal.Content>
                    <Modal.Actions>
                        <Button onClick={this.closeCancelModal.bind(this)}>
                            <Icon name='arrow left' />
                            No, Continue Processing
                        </Button>
                        <Button color='red' onClick={this.onConfirmCancel.bind(this)}>
                            <Icon name='stop' />
                            Yes, Cancel Processing
                        </Button>
                    </Modal.Actions>
                </Modal>

                <Modal
                    dimmer="inverted"
                    closeOnEscape={true}
                    closeOnDimmerClick={true}
                    closeIcon
                    onClose={this.closeResultsModal.bind(this)}
                    open={this.state.showResultsModal}
                >
                    <Header icon='shipping fast' content='Batch Shipping Results' />
                    <Modal.Content>
                        <Segment>
                            <Header as="h3">
                                <Icon name='check circle' color='green' />
                                Batch Shipping Complete!
                            </Header>
                            <p>Processed {this.state.batchShippingResults.length} orders</p>
                            {successCount > 0 && (
                                <Message positive>
                                    <Message.Header>
                                        <Icon name='check' />
                                        {successCount} order{successCount !== 1 ? 's' : ''} processed successfully
                                    </Message.Header>
                                </Message>
                            )}
                            {failureCount > 0 && (
                                <Message negative>
                                    <Message.Header>
                                        <Icon name='warning sign' />
                                        {failureCount} order{failureCount !== 1 ? 's' : ''} failed
                                    </Message.Header>
                                </Message>
                            )}
                        </Segment>
                        {this.state.batchShippingResults.length > 0 && (
                            <Table celled>
                                <Table.Header>
                                    <Table.Row>
                                        <Table.HeaderCell>Order ID</Table.HeaderCell>
                                        <Table.HeaderCell>Status</Table.HeaderCell>
                                        <Table.HeaderCell>Message</Table.HeaderCell>
                                    </Table.Row>
                                </Table.Header>
                                <Table.Body>
                                    {this.state.batchShippingResults.map((result) => (
                                        <Table.Row key={result.bigOrderId} positive={result.success} negative={!result.success}>
                                            <Table.Cell>{result.bigOrderId}</Table.Cell>
                                            <Table.Cell>
                                                {result.success ? (
                                                    <Label color='green'>
                                                        <Icon name='check' />
                                                        Success
                                                    </Label>
                                                ) : (
                                                    <Label color='red'>
                                                        <Icon name='x' />
                                                        Failed
                                                    </Label>
                                                )}
                                            </Table.Cell>
                                            <Table.Cell>{result.message}</Table.Cell>
                                        </Table.Row>
                                    ))}
                                </Table.Body>
                            </Table>
                        )}
                    </Modal.Content>
                    <Modal.Actions>
                        <Button color='blue' onClick={this.closeResultsModal.bind(this)}>
                            <Icon name='checkmark' />
                            Close
                        </Button>
                    </Modal.Actions>
                </Modal>

                <div style={{
                    position: 'relative',
                    pointerEvents: this.state.batchShippingInProgress ? 'none' : 'auto',
                    opacity: this.state.batchShippingInProgress ? 0.5 : 1
                }}>
                    <BigOrdersQueryEnhanced limit={1000} schemas={this.state.schemas} onQueryUpdated={this.onUpdateQuery.bind(this)} />
                    {this.state.batchShippingInProgress && (
                        <div style={{
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            backgroundColor: 'rgba(255, 255, 255, 0.3)',
                            zIndex: 1000
                        }}>
                            <Message warning>
                                <Icon name='lock' />
                                Query disabled during batch processing
                            </Message>
                        </div>
                    )}
                </div>

                {this.state.loading && <Header as='h2'>Looking for orders to ship...</Header>}

                {this.state.shipperResults && this.state.shipperResults.length > 0 && (
                    <>
                        <Segment>
                            <Header as='h2'>
                                📦 Showing {this.state.shipperResults.length} Orders Ready To Ship
                                {this.state.selectedOrders.size > 0 && ` • ${this.state.selectedOrders.size} Selected`}
                                {this.state.batchShippingInProgress && (
                                    <span>
                                        {' • '}
                                        <Icon name='circle notched' loading color='blue' />
                                        Processing...
                                    </span>
                                )}
                            </Header>
                            <Button
                                primary={!allSelected}
                                onClick={allSelected ? this.deselectAllOrders.bind(this) : this.selectAllOrders.bind(this)}
                                disabled={this.state.batchShippingInProgress}
                            >
                                <Icon name={allSelected ? 'minus square outline' : 'check square outline'} />
                                {allSelected ? 'Deselect All' : 'Select All'}
                            </Button>
                            <ApiButtonModal
                                color="green"
                                size="medium"
                                icon="shipping fast"
                                text="Start Batch Shipping"
                                disabled={this.state.selectedOrders.size === 0 || this.state.batchShippingInProgress}
                                loading={this.state.batchShippingInProgress}
                                cancel
                                modalIcon="shipping fast"
                                modalButtonText="Start Batch Shipping Process"
                                onConfirm={this.onBatchShip.bind(this)}
                                onShowModal={() => this.setState({ batchShippingMode: null })}
                                confirmDisabled={this.state.batchShippingMode === null}
                                closeImmediately={true}
                            >
                                <p>You are about to start the batch shipping process for <strong>{this.state.selectedOrders.size}</strong> selected orders.</p>
                                <p>This will create shipments for all selected orders that are ready to ship.</p>
                                <div style={{ marginBottom: '1em' }}>
                                    <label style={{ display: 'block', marginBottom: '0.5em', fontWeight: 'bold' }}>Select shipping mode:</label>
                                    <Button.Group fluid vertical>
                                        <Button
                                            basic={this.state.batchShippingMode !== 'labelsOnly'}
                                            color={this.state.batchShippingMode === 'labelsOnly' ? 'green' : 'grey'}
                                            onClick={() => this.setState({ batchShippingMode: 'labelsOnly' })}
                                            style={{ textAlign: 'left', cursor: 'pointer' }}
                                        >
                                            <Icon name="tag" />
                                            Generate labels only
                                        </Button>
                                        <Button
                                            basic={this.state.batchShippingMode !== 'generateAll'}
                                            color={this.state.batchShippingMode === 'generateAll' ? 'green' : 'grey'}
                                            onClick={() => this.setState({ batchShippingMode: 'generateAll' })}
                                            style={{ textAlign: 'left', cursor: 'pointer' }}
                                        >
                                            <Icon name="shipping fast" />
                                            Generate Labels and mark orders as fulfilled
                                        </Button>
                                    </Button.Group>
                                </div>
                                <Message warning>
                                    <Message.Header>Important</Message.Header>
                                    <p>Please review the selected orders before proceeding. This action will start the shipping process for all selected orders.</p>
                                </Message>
                            </ApiButtonModal>
                            {this.state.batchShippingInProgress && (
                                <Button
                                    color="red"
                                    size="medium"
                                    icon="stop"
                                    content="Cancel Processing"
                                    onClick={this.onRequestCancel.bind(this)}
                                />
                            )}
                        </Segment>
                    </>
                )}

                {/* Processing Log */}
                {this.state.processingLog.length > 0 && (() => {
                    const lastEntry = this.state.processingLog[this.state.processingLog.length - 1];
                    const getEntryColor = (type) =>
                        type === 'error' ? '#ff6b6b' :
                            type === 'warning' ? '#ffd43b' :
                                type === 'success' ? '#69db7c' : '#fff';

                    return (
                        <Segment>
                            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: this.state.logExpanded ? '10px' : 0 }}>
                                <div
                                    style={{ display: 'flex', alignItems: 'center', cursor: 'pointer', flex: 1 }}
                                    onClick={() => this.setState({ logExpanded: !this.state.logExpanded })}
                                >
                                    <Icon name={this.state.logExpanded ? 'chevron down' : 'chevron right'} />
                                    <span style={{ fontWeight: 'bold', marginRight: '10px' }}>Processing Log</span>
                                    <Label size="tiny" circular>{this.state.processingLog.length}</Label>
                                </div>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                                    {!this.state.logExpanded && (
                                        <span style={{
                                            fontFamily: 'monospace',
                                            fontSize: '12px',
                                            color: getEntryColor(lastEntry.type),
                                            backgroundColor: '#1b1c1d',
                                            padding: '4px 8px',
                                            borderRadius: '4px',
                                            maxWidth: '400px',
                                            overflow: 'hidden',
                                            textOverflow: 'ellipsis',
                                            whiteSpace: 'nowrap'
                                        }}>
                                            {lastEntry.message}
                                        </span>
                                    )}
                                    {!this.state.batchShippingInProgress && (
                                        <Button
                                            size="tiny"
                                            basic
                                            onClick={(e) => { e.stopPropagation(); this.clearLog(); }}
                                        >
                                            Clear
                                        </Button>
                                    )}
                                </div>
                            </div>
                            {this.state.logExpanded && (
                                <div style={{
                                    maxHeight: '300px',
                                    overflowY: 'auto',
                                    fontFamily: 'monospace',
                                    fontSize: '12px',
                                    backgroundColor: '#1b1c1d',
                                    color: '#fff',
                                    padding: '10px',
                                    borderRadius: '4px'
                                }}
                                    ref={(el) => {
                                        if (el) el.scrollTop = el.scrollHeight;
                                    }}
                                >
                                    {this.state.processingLog.map((entry) => (
                                        <div key={entry.id} style={{
                                            marginBottom: '2px',
                                            color: getEntryColor(entry.type)
                                        }}>
                                            <span style={{ color: '#868e96' }}>[{entry.timestamp}]</span>{' '}
                                            {entry.type === 'error' && <Icon name="times circle" />}
                                            {entry.type === 'warning' && <Icon name="exclamation triangle" />}
                                            {entry.type === 'success' && <Icon name="check circle" />}
                                            {entry.message}
                                        </div>
                                    ))}
                                </div>
                            )}
                        </Segment>
                    );
                })()}

                {!this.state.loading && (
                    <Table celled selectable>
                        <Table.Header>
                            <Table.Row>
                                <Table.HeaderCell collapsing></Table.HeaderCell>
                                <Table.HeaderCell width={2}>Order # / Priority</Table.HeaderCell>
                                <Table.HeaderCell width={1}>Created</Table.HeaderCell>
                                <Table.HeaderCell width={1}>Updated</Table.HeaderCell>
                                <Table.HeaderCell collapsing>Customer</Table.HeaderCell>
                                <Table.HeaderCell width={2}>Products</Table.HeaderCell>
                                <Table.HeaderCell collapsing>IPD</Table.HeaderCell>
                                <Table.HeaderCell width={1}>Status</Table.HeaderCell>
                            </Table.Row>
                        </Table.Header>
                        <Table.Body>
                            {bigShipperResults}
                        </Table.Body>
                    </Table>
                )}

            </BigShipperWrapper>
        );
    }
}
