import React from 'react';
import superagent from 'superagent';
import {
    Header, Segment, Form, Button, Icon, Table, Label, Divider,
    Grid, Message, Input, Dropdown, Modal, TextArea, Statistic, Loader
} from 'semantic-ui-react';
import ExperimentalWrapper from './ExperimentalWrapper.jsx';

// Status options for charge flags
const STATUS_OPTIONS = [
    { key: 'new', text: 'New', value: 'new' },
    { key: 'reviewed', text: 'Reviewed', value: 'reviewed' },
    { key: 'disputed', text: 'Disputed', value: 'disputed' },
    { key: 'resolved', text: 'Resolved', value: 'resolved' },
];

export default class DHLChargesPage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            // Data
            invoices: [],
            flaggedCharges: [],
            shipmentLookupResults: {},

            // UI State
            loading: false,
            loadingCharges: false,
            selectedInvoice: null,
            statusFilter: 'all',
            searchTrackingNumber: '',

            // Modal state
            editModalOpen: false,
            editingCharge: null,
            editStatus: '',
            editNotes: '',

            // CSV Upload state
            uploading: false,
            uploadResult: null,

            // Reconcile state
            reconcilingInvoiceId: null,

            // Clear all state
            clearing: false,
            clearConfirmOpen: false,
            clearResult: null,

            // Lookup state
            lookupModalOpen: false,
            lookupTrackingNumber: '',
            lookupResult: null,
            lookupLoading: false,

            // Fee breakdown expanded rows
            expandedChargeIds: {},

            // Raw data state
            rawDataExpanded: {},

            // Summary stats from API
            summary: null,

            // Selected invoice detail (with hydrated charges + shipment data)
            selectedInvoiceDetail: null,

            // Tab state for invoice detail view
            activeTab: 'charges'
        };
    }

    componentDidMount() {
        this.loadInvoices();
        this.loadFlaggedCharges();
        this.loadSummary();
    }

    async loadInvoices() {
        this.setState({ loading: true });
        try {
            const res = await superagent.get('/api/admin/dhl/invoices').accept('json');
            this.setState({ invoices: res.body.items || [] });
        } catch (error) {
            console.error('Failed to load invoices:', error);
        } finally {
            this.setState({ loading: false });
        }
    }

    async loadSummary() {
        try {
            const res = await superagent.get('/api/admin/dhl/invoices/summary').accept('json');
            this.setState({ summary: res.body });
        } catch (error) {
            console.error('Failed to load summary:', error);
        }
    }

    async loadFlaggedCharges(invoiceId) {
        this.setState({ loadingCharges: true });
        try {
            const query = {};
            if (invoiceId) {
                query.invoiceId = invoiceId;
            }
            const res = await superagent.get('/api/admin/dhl/charges/flagged')
                .query(query)
                .accept('json');
            this.setState({ flaggedCharges: res.body.items || [] });
        } catch (error) {
            console.error('Failed to load flagged charges:', error);
        } finally {
            this.setState({ loadingCharges: false });
        }
    }

    async uploadCSV(file) {
        this.setState({ uploading: true, uploadResult: null });
        try {
            const res = await superagent.post('/api/admin/dhl/invoices/upload-csv')
                .attach('file', file)
                .accept('json');
            this.setState({ uploadResult: res.body });
            await this.loadInvoices();
            await this.loadSummary();
        } catch (error) {
            console.error('CSV upload failed:', error);
            this.setState({ uploadResult: { error: error.response?.body?.error || error.message } });
        } finally {
            this.setState({ uploading: false });
        }
    }

    async clearAllData() {
        this.setState({ clearing: true, clearResult: null });
        try {
            const res = await superagent.delete('/api/admin/dhl/all').accept('json');
            this.setState({
                clearResult: res.body,
                clearConfirmOpen: false
            });
            await this.loadInvoices();
            await this.loadFlaggedCharges();
            await this.loadSummary();
        } catch (error) {
            console.error('Clear all failed:', error);
            this.setState({
                clearResult: { error: error.response?.body?.error || error.message },
                clearConfirmOpen: false
            });
        } finally {
            this.setState({ clearing: false });
        }
    }

    async reconcileInvoice(invoiceId) {
        this.setState({ reconcilingInvoiceId: invoiceId });
        try {
            await superagent.post('/api/admin/dhl/reconcile')
                .send({ invoiceId })
                .accept('json');
            // Reload both invoices and charges
            await this.loadInvoices();
            await this.loadFlaggedCharges(this.state.selectedInvoice);
        } catch (error) {
            console.error('Reconciliation failed:', error);
        } finally {
            this.setState({ reconcilingInvoiceId: null });
        }
    }

    async lookupShipment(trackingNumber) {
        this.setState({ lookupLoading: true });
        try {
            const res = await superagent.get('/api/admin/shipper/shipments')
                .query({ trackingNumber, limit: 1 });

            const shipments = res.body;
            if (shipments && shipments.items && shipments.items.length > 0) {
                const shipment = shipments.items[0];
                this.setState({
                    lookupResult: shipment,
                    shipmentLookupResults: {
                        ...this.state.shipmentLookupResults,
                        [trackingNumber]: shipment
                    }
                });
                return shipment;
            } else if (shipments && shipments.length > 0) {
                const shipment = shipments[0];
                this.setState({
                    lookupResult: shipment,
                    shipmentLookupResults: {
                        ...this.state.shipmentLookupResults,
                        [trackingNumber]: shipment
                    }
                });
                return shipment;
            } else {
                this.setState({ lookupResult: { notFound: true } });
                return null;
            }
        } catch (error) {
            console.error('Failed to lookup shipment:', error);
            this.setState({ lookupResult: { error: error.message } });
            return null;
        } finally {
            this.setState({ lookupLoading: false });
        }
    }

    openEditModal(charge) {
        this.setState({
            editModalOpen: true,
            editingCharge: charge,
            editStatus: charge.status,
            editNotes: charge.notes || ''
        });
    }

    async saveChargeEdits() {
        const { editingCharge, editStatus, editNotes } = this.state;
        try {
            await superagent.put(`/api/admin/dhl/charges/${editingCharge.uniqueId || editingCharge.id}`)
                .send({ status: editStatus, notes: editNotes })
                .accept('json');

            this.setState({ editModalOpen: false, editingCharge: null });
            // Reload charges
            await this.loadFlaggedCharges(this.state.selectedInvoice);
        } catch (error) {
            console.error('Failed to save charge edits:', error);
        }
    }

    openLookupModal(trackingNumber) {
        this.setState({
            lookupModalOpen: true,
            lookupTrackingNumber: trackingNumber,
            lookupResult: this.state.shipmentLookupResults[trackingNumber] || null
        });

        if (!this.state.shipmentLookupResults[trackingNumber]) {
            this.lookupShipment(trackingNumber);
        }
    }

    async selectInvoice(invoiceId) {
        this.setState({ selectedInvoice: invoiceId, activeTab: 'charges', selectedInvoiceDetail: null });
        this.loadFlaggedCharges(invoiceId);

        if (invoiceId) {
            // Find the invoice's numeric id for the API call
            const invoice = this.state.invoices.find(inv => (inv.uniqueId || inv.id) === invoiceId);
            if (invoice) {
                this.setState({ loadingCharges: true });
                try {
                    const res = await superagent.get(`/api/admin/dhl/invoices/${invoice.id}`).accept('json');
                    this.setState({ selectedInvoiceDetail: res.body });
                } catch (error) {
                    console.error('Failed to load invoice detail:', error);
                } finally {
                    this.setState({ loadingCharges: false });
                }
            }
        }
    }

    toggleRawData(invoiceId) {
        this.setState(prev => ({
            rawDataExpanded: {
                ...prev.rawDataExpanded,
                [invoiceId]: !prev.rawDataExpanded[invoiceId]
            }
        }));
    }

    formatDate(timestamp) {
        if (!timestamp) return '-';
        return new Date(timestamp).toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'short',
            day: 'numeric'
        });
    }

    formatCurrency(amount, currency = 'USD') {
        if (amount === null || amount === undefined) return '-';
        return new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: currency
        }).format(amount);
    }

    toggleFeeBreakdown(chargeId) {
        this.setState(prev => ({
            expandedChargeIds: {
                ...prev.expandedChargeIds,
                [chargeId]: !prev.expandedChargeIds[chargeId]
            }
        }));
    }

    renderFeeBreakdown(fb, currency) {
        if (!fb || typeof fb !== 'object') return null;
        const items = [];
        if (fb.weightCharge != null) items.push({ label: 'Weight Charge', amount: fb.weightCharge });
        if (fb.fuelSurcharge != null) items.push({ label: 'Fuel Surcharge', amount: fb.fuelSurcharge });
        if (fb.taxAdjustment != null) items.push({ label: 'Tax Adjustment', amount: fb.taxAdjustment });
        if (fb.invoiceFee != null) items.push({ label: 'Invoice Fee', amount: fb.invoiceFee });
        if (fb.otherCharges && fb.otherCharges.length > 0) {
            fb.otherCharges.forEach(oc => items.push({ label: `Other: ${oc.code}`, amount: oc.amount }));
        }
        if (fb.extraCharges && fb.extraCharges.length > 0) {
            fb.extraCharges.forEach(xc => items.push({ label: xc.name || xc.code, amount: xc.amount }));
        }
        if (fb.discounts && fb.discounts.length > 0) {
            fb.discounts.forEach(d => items.push({ label: `Discount: ${d.code}`, amount: d.amount }));
        }
        if (fb.totalExtraCharges != null) items.push({ label: 'Total Extra Charges', amount: fb.totalExtraCharges, bold: true });

        if (items.length === 0) return <span style={{ color: '#999' }}>No breakdown</span>;

        return (
            <Table compact size="small" basic="very" style={{ margin: 0 }}>
                <Table.Body>
                    {items.map((item, i) => (
                        <Table.Row key={i}>
                            <Table.Cell style={{ padding: '2px 8px', fontWeight: item.bold ? 'bold' : 'normal' }}>
                                {item.label}
                            </Table.Cell>
                            <Table.Cell textAlign="right" style={{ padding: '2px 8px', fontWeight: item.bold ? 'bold' : 'normal' }}>
                                {this.formatCurrency(item.amount, currency)}
                            </Table.Cell>
                        </Table.Row>
                    ))}
                </Table.Body>
            </Table>
        );
    }

    getStatusColor(status) {
        switch (status) {
            case 'new': return 'red';
            case 'reviewed': return 'yellow';
            case 'disputed': return 'orange';
            case 'resolved': return 'green';
            case 'pending': return 'yellow';
            case 'reconciled': return 'blue';
            default: return 'grey';
        }
    }

    getFilteredCharges() {
        const { flaggedCharges, statusFilter, selectedInvoice, searchTrackingNumber } = this.state;

        return flaggedCharges.filter(charge => {
            if (statusFilter !== 'all' && charge.status !== statusFilter) return false;
            if (selectedInvoice && charge.invoiceId !== selectedInvoice) return false;
            if (searchTrackingNumber && !charge.trackingNumber.toLowerCase().includes(searchTrackingNumber.toLowerCase())) return false;
            return true;
        });
    }

    calculateSummaryStats() {
        const { flaggedCharges } = this.state;

        const newCount = flaggedCharges.filter(c => c.status === 'new').length;
        const totalDiscrepancy = flaggedCharges
            .filter(c => c.discrepancyAmount !== null)
            .reduce((sum, c) => sum + c.discrepancyAmount, 0);
        const unmatched = flaggedCharges.filter(c => !c.bigShipmentId).length;

        return { newCount, totalDiscrepancy, unmatched };
    }

    render() {
        const {
            invoices, loading, loadingCharges, selectedInvoice, statusFilter,
            searchTrackingNumber, editModalOpen, editingCharge, editStatus,
            editNotes, uploading, uploadResult,
            reconcilingInvoiceId, lookupModalOpen, lookupTrackingNumber,
            lookupResult, lookupLoading, rawDataExpanded,
            summary, activeTab, clearing, clearConfirmOpen, clearResult,
            selectedInvoiceDetail
        } = this.state;

        const filteredCharges = this.getFilteredCharges();
        const stats = this.calculateSummaryStats();
        const selectedInvoiceData = invoices.find(inv => (inv.uniqueId || inv.id) === selectedInvoice);

        return (
            <ExperimentalWrapper title="DHL Charges Tracking">
                <Segment>
                    <Header as="h2">
                        <Icon name="dollar sign" />
                        <Header.Content>
                            DHL Charges Tracking
                            <Header.Subheader>
                                Track and validate DHL shipping charges against expected costs
                            </Header.Subheader>
                        </Header.Content>
                    </Header>
                </Segment>

                {/* Summary Statistics */}
                <Segment>
                    <Statistic.Group widths="six" size="small">
                        <Statistic color="blue">
                            <Statistic.Value>{summary ? summary.invoiceCount : '-'}</Statistic.Value>
                            <Statistic.Label>Invoices</Statistic.Label>
                        </Statistic>
                        <Statistic color="teal">
                            <Statistic.Value>{summary ? summary.totalChargeCount : '-'}</Statistic.Value>
                            <Statistic.Label>Total Charges</Statistic.Label>
                        </Statistic>
                        <Statistic color="blue">
                            <Statistic.Value>{summary ? this.formatCurrency(summary.totalValue) : '-'}</Statistic.Value>
                            <Statistic.Label>Total Invoice Value</Statistic.Label>
                        </Statistic>
                        <Statistic color="red">
                            <Statistic.Value>{stats.newCount}</Statistic.Value>
                            <Statistic.Label>New Flags</Statistic.Label>
                        </Statistic>
                        <Statistic color="orange">
                            <Statistic.Value>{this.formatCurrency(stats.totalDiscrepancy)}</Statistic.Value>
                            <Statistic.Label>Total Discrepancy</Statistic.Label>
                        </Statistic>
                        <Statistic color="grey">
                            <Statistic.Value>{stats.unmatched}</Statistic.Value>
                            <Statistic.Label>Unmatched</Statistic.Label>
                        </Statistic>
                    </Statistic.Group>
                </Segment>

                <Grid>
                    <Grid.Row>
                        <Grid.Column width={4}>
                            {/* Invoices List */}
                            <Segment>
                                <Header as="h3">
                                    <Icon name="file alternate" />
                                    Invoices
                                </Header>

                                <Button
                                    fluid
                                    primary
                                    loading={uploading}
                                    disabled={uploading}
                                    onClick={() => this.csvFileInput && this.csvFileInput.click()}
                                    style={{ marginBottom: '1em' }}
                                >
                                    <Icon name="upload" />
                                    Upload CSV
                                </Button>
                                <input
                                    ref={el => this.csvFileInput = el}
                                    type="file"
                                    accept=".csv"
                                    style={{ display: 'none' }}
                                    onChange={(e) => {
                                        const file = e.target.files[0];
                                        if (file) {
                                            this.uploadCSV(file);
                                            e.target.value = '';
                                        }
                                    }}
                                />

                                {uploadResult && (
                                    <Message
                                        positive={!uploadResult.error}
                                        negative={!!uploadResult.error}
                                        onDismiss={() => this.setState({ uploadResult: null })}
                                        style={{ marginBottom: '1em' }}
                                    >
                                        <Message.Header>
                                            {uploadResult.error ? 'Upload Failed' : 'CSV Uploaded'}
                                        </Message.Header>
                                        {uploadResult.error ? (
                                            <p>{uploadResult.error}</p>
                                        ) : (
                                            <p>
                                                {uploadResult.chargesCreated} charge(s) added{uploadResult.chargesUpdated > 0 ? `, ${uploadResult.chargesUpdated} replaced` : ''}.
                                                {(uploadResult.invoicesCreated > 0 || uploadResult.invoicesUpdated > 0) && (
                                                    <small style={{ display: 'block', marginTop: '0.3em', color: '#888' }}>
                                                        {uploadResult.invoicesCreated > 0 && `${uploadResult.invoicesCreated} invoice(s) created. `}
                                                        {uploadResult.invoicesUpdated > 0 && `${uploadResult.invoicesUpdated} invoice(s) updated.`}
                                                    </small>
                                                )}
                                                {uploadResult.errors && uploadResult.errors.length > 0 && (
                                                    <><br />{uploadResult.errors.length} warning(s).</>
                                                )}
                                            </p>
                                        )}
                                    </Message>
                                )}

                                <Button
                                    fluid
                                    color="red"
                                    basic
                                    loading={clearing}
                                    disabled={clearing}
                                    onClick={() => this.setState({ clearConfirmOpen: true })}
                                    style={{ marginBottom: '1em' }}
                                >
                                    <Icon name="trash" />
                                    Clear All Data
                                </Button>

                                <Modal
                                    size="small"
                                    open={clearConfirmOpen}
                                    onClose={() => this.setState({ clearConfirmOpen: false })}
                                >
                                    <Modal.Header>Clear All DHL Data</Modal.Header>
                                    <Modal.Content>
                                        <p>This will permanently delete <strong>all</strong> DHL invoices, charges, and flags. This action cannot be undone.</p>
                                        <p>Are you sure you want to continue?</p>
                                    </Modal.Content>
                                    <Modal.Actions>
                                        <Button onClick={() => this.setState({ clearConfirmOpen: false })}>
                                            Cancel
                                        </Button>
                                        <Button
                                            color="red"
                                            loading={clearing}
                                            onClick={() => this.clearAllData()}
                                        >
                                            <Icon name="trash" />
                                            Yes, Delete Everything
                                        </Button>
                                    </Modal.Actions>
                                </Modal>

                                {clearResult && (
                                    <Message
                                        positive={!clearResult.error}
                                        negative={!!clearResult.error}
                                        onDismiss={() => this.setState({ clearResult: null })}
                                        style={{ marginBottom: '1em' }}
                                    >
                                        <Message.Header>
                                            {clearResult.error ? 'Clear Failed' : 'Data Cleared'}
                                        </Message.Header>
                                        {clearResult.error ? (
                                            <p>{clearResult.error}</p>
                                        ) : (
                                            <p>
                                                Deleted {clearResult.invoicesDeleted} invoice(s), {clearResult.chargesDeleted} charge(s), {clearResult.flagsDeleted} flag(s).
                                            </p>
                                        )}
                                    </Message>
                                )}

                                <Button
                                    fluid
                                    basic
                                    color={selectedInvoice === null ? 'blue' : undefined}
                                    onClick={() => this.selectInvoice(null)}
                                    style={{ marginBottom: '0.5em' }}
                                >
                                    All Invoices
                                </Button>

                                {loading ? (
                                    <Loader active inline="centered" />
                                ) : invoices.map(invoice => {
                                    const invId = invoice.uniqueId || invoice.id;
                                    return (
                                        <Segment
                                            key={invId}
                                            raised={selectedInvoice === invId}
                                            color={selectedInvoice === invId ? 'blue' : undefined}
                                            style={{ cursor: 'pointer' }}
                                            onClick={() => this.selectInvoice(invId)}
                                        >
                                            <strong>{invoice.invoiceNumber}</strong>
                                            <br />
                                            <small>{this.formatDate(invoice.invoiceDate)}</small>
                                            <br />
                                            <Label size="tiny" color={this.getStatusColor(invoice.status)}>
                                                {invoice.status}
                                            </Label>
                                            <span style={{ float: 'right' }}>
                                                {this.formatCurrency(invoice.totalAmount)}
                                            </span>
                                            <br />
                                            <small>{invoice.chargeCount} charges</small>
                                            <div style={{ marginTop: '4px' }}>
                                                <Button
                                                    size="mini"
                                                    basic
                                                    color="blue"
                                                    loading={reconcilingInvoiceId === invId}
                                                    disabled={reconcilingInvoiceId === invId}
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        this.reconcileInvoice(invId);
                                                    }}
                                                >
                                                    Reconcile
                                                </Button>
                                                <Button
                                                    size="mini"
                                                    basic
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        this.toggleRawData(invId);
                                                    }}
                                                >
                                                    <Icon name="code" />
                                                    Raw
                                                </Button>
                                            </div>
                                            {rawDataExpanded[invId] && (
                                                <Segment
                                                    style={{
                                                        maxHeight: '200px',
                                                        overflow: 'auto',
                                                        marginTop: '4px'
                                                    }}
                                                    onClick={(e) => e.stopPropagation()}
                                                >
                                                    <pre style={{ fontSize: '10px', whiteSpace: 'pre-wrap' }}>
                                                        {JSON.stringify(invoice, null, 4)}
                                                    </pre>
                                                </Segment>
                                            )}
                                        </Segment>
                                    );
                                })}
                            </Segment>
                        </Grid.Column>

                        <Grid.Column width={12}>
                            {/* Filters */}
                            <Segment>
                                <Form>
                                    <Form.Group>
                                        <Form.Field width={6}>
                                            <label>Filter by Status</label>
                                            <Dropdown
                                                selection
                                                options={[
                                                    { key: 'all', text: 'All Statuses', value: 'all' },
                                                    ...STATUS_OPTIONS
                                                ]}
                                                value={statusFilter}
                                                onChange={(e, { value }) => this.setState({ statusFilter: value })}
                                            />
                                        </Form.Field>
                                        <Form.Field width={10}>
                                            <label>Search by Tracking Number</label>
                                            <Input
                                                icon="search"
                                                placeholder="Enter tracking number..."
                                                value={searchTrackingNumber}
                                                onChange={(e) => this.setState({ searchTrackingNumber: e.target.value })}
                                            />
                                        </Form.Field>
                                    </Form.Group>
                                </Form>
                            </Segment>

                            {/* Tabs when an invoice is selected */}
                            {selectedInvoiceData && (
                                <Segment>
                                    <Button.Group fluid>
                                        <Button
                                            primary={activeTab === 'charges'}
                                            basic={activeTab !== 'charges'}
                                            onClick={() => this.setState({ activeTab: 'charges' })}
                                        >
                                            <Icon name="list" />
                                            Invoice Charges ({selectedInvoiceDetail?.charges?.length || 0})
                                        </Button>
                                        <Button
                                            primary={activeTab === 'flagged'}
                                            basic={activeTab !== 'flagged'}
                                            onClick={() => this.setState({ activeTab: 'flagged' })}
                                        >
                                            <Icon name="flag" />
                                            Flagged Charges ({filteredCharges.length})
                                        </Button>
                                    </Button.Group>
                                </Segment>
                            )}

                            {/* Invoice Charges Table (only when invoice selected and charges tab active) */}
                            {selectedInvoiceData && activeTab === 'charges' && (
                                <Segment>
                                    <Header as="h3">
                                        <Icon name="list" />
                                        Invoice Charges - {selectedInvoiceData.invoiceNumber}
                                    </Header>
                                    {loadingCharges ? (
                                        <Loader active inline="centered" content="Loading charges..." />
                                    ) : (
                                        <>
                                            <Table compact celled>
                                                <Table.Header>
                                                    <Table.Row>
                                                        <Table.HeaderCell>Tracking #</Table.HeaderCell>
                                                        <Table.HeaderCell textAlign="right">DHL Invoiced</Table.HeaderCell>
                                                        <Table.HeaderCell textAlign="right">Label Price</Table.HeaderCell>
                                                        <Table.HeaderCell textAlign="right">Discrepancy</Table.HeaderCell>
                                                        <Table.HeaderCell>Currency</Table.HeaderCell>
                                                        <Table.HeaderCell>DHL Service</Table.HeaderCell>
                                                        <Table.HeaderCell>Label Provider</Table.HeaderCell>
                                                        <Table.HeaderCell>Label Service Level</Table.HeaderCell>
                                                        <Table.HeaderCell>Weight</Table.HeaderCell>
                                                        <Table.HeaderCell>Shipment Status</Table.HeaderCell>
                                                        <Table.HeaderCell>Shipment</Table.HeaderCell>
                                                        <Table.HeaderCell>Fees</Table.HeaderCell>
                                                    </Table.Row>
                                                </Table.Header>
                                                <Table.Body>
                                                    {(selectedInvoiceDetail?.charges || []).map((charge, idx) => {
                                                        const shipment = charge.shipment;
                                                        const label = shipment?.currentShippingLabel;
                                                        const quotedRate = charge.quotedRate;
                                                        const discrepancy = charge.discrepancy;
                                                        const chargeKey = charge.uniqueId || charge.id || idx;
                                                        const isExpanded = this.state.expandedChargeIds[chargeKey];
                                                        const fb = charge.feeBreakdown;
                                                        const hasFeeData = fb && typeof fb === 'object' && (
                                                            fb.weightCharge != null || fb.fuelSurcharge != null ||
                                                            (fb.extraCharges && fb.extraCharges.length > 0) ||
                                                            (fb.discounts && fb.discounts.length > 0) ||
                                                            (fb.otherCharges && fb.otherCharges.length > 0)
                                                        );
                                                        return (
                                                            <React.Fragment key={idx}>
                                                            <Table.Row negative={discrepancy != null && discrepancy > 0.01}>
                                                                <Table.Cell>
                                                                    {charge.trackingNumber ? (
                                                                        <a
                                                                            href="#"
                                                                            onClick={(e) => {
                                                                                e.preventDefault();
                                                                                this.openLookupModal(charge.trackingNumber);
                                                                            }}
                                                                        >
                                                                            {charge.trackingNumber}
                                                                        </a>
                                                                    ) : '-'}
                                                                </Table.Cell>
                                                                <Table.Cell textAlign="right">
                                                                    {this.formatCurrency(charge.amount, charge.currency)}
                                                                </Table.Cell>
                                                                <Table.Cell textAlign="right">
                                                                    {quotedRate != null ? this.formatCurrency(quotedRate, charge.currency) : '-'}
                                                                </Table.Cell>
                                                                <Table.Cell textAlign="right">
                                                                    {discrepancy != null ? (
                                                                        <Label color={discrepancy > 0.01 ? 'red' : discrepancy < -0.01 ? 'green' : 'grey'} size="small">
                                                                            {discrepancy > 0 ? '+' : ''}{this.formatCurrency(discrepancy, charge.currency)}
                                                                        </Label>
                                                                    ) : '-'}
                                                                </Table.Cell>
                                                                <Table.Cell>{charge.currency || '-'}</Table.Cell>
                                                                <Table.Cell>{charge.serviceType || '-'}</Table.Cell>
                                                                <Table.Cell>{label?.rate?.provider || '-'}</Table.Cell>
                                                                <Table.Cell>{label?.rate?.servicelevel_name || '-'}</Table.Cell>
                                                                <Table.Cell>{charge.weight || '-'}</Table.Cell>
                                                                <Table.Cell>
                                                                    {shipment ? (
                                                                        <Label size="small" color={
                                                                            shipment.status === 'Delivered' ? 'green' :
                                                                            shipment.status === 'Shipped' ? 'blue' :
                                                                            shipment.status === 'Error' ? 'red' : 'grey'
                                                                        }>
                                                                            {shipment.status}
                                                                        </Label>
                                                                    ) : '-'}
                                                                </Table.Cell>
                                                                <Table.Cell>
                                                                    {shipment ? (
                                                                        <a
                                                                            href={`#/shipments/${shipment.uniqueId}`}
                                                                            title={shipment.name || shipment.uniqueId}
                                                                        >
                                                                            <Icon name="external" />
                                                                            View
                                                                        </a>
                                                                    ) : (
                                                                        <span style={{ color: '#999' }}>No match</span>
                                                                    )}
                                                                </Table.Cell>
                                                                <Table.Cell textAlign="center">
                                                                    {hasFeeData ? (
                                                                        <Button
                                                                            icon={isExpanded ? 'chevron up' : 'chevron down'}
                                                                            size="mini"
                                                                            basic
                                                                            onClick={() => this.toggleFeeBreakdown(chargeKey)}
                                                                            title="Show fee breakdown"
                                                                        />
                                                                    ) : '-'}
                                                                </Table.Cell>
                                                            </Table.Row>
                                                            {isExpanded && hasFeeData && (
                                                                <Table.Row>
                                                                    <Table.Cell colSpan="12" style={{ background: '#f9f9f9', padding: '8px 16px' }}>
                                                                        <strong>Fee Breakdown</strong>
                                                                        {this.renderFeeBreakdown(fb, charge.currency)}
                                                                    </Table.Cell>
                                                                </Table.Row>
                                                            )}
                                                            </React.Fragment>
                                                        );
                                                    })}
                                                </Table.Body>
                                            </Table>
                                            {(!selectedInvoiceDetail?.charges || selectedInvoiceDetail.charges.length === 0) && (
                                                <Message info>
                                                    No charges found for this invoice.
                                                </Message>
                                            )}
                                        </>
                                    )}
                                </Segment>
                            )}

                            {/* Flagged Charges Table (shown when no invoice selected, or flagged tab active) */}
                            {(!selectedInvoiceData || activeTab === 'flagged') && (
                            <Segment>
                                <Header as="h3">
                                    <Icon name="flag" />
                                    Flagged Charges ({filteredCharges.length})
                                </Header>

                                {loadingCharges ? (
                                    <Loader active inline="centered" />
                                ) : (
                                    <Table compact celled>
                                        <Table.Header>
                                            <Table.Row>
                                                <Table.HeaderCell>Tracking #</Table.HeaderCell>
                                                <Table.HeaderCell>Invoice</Table.HeaderCell>
                                                <Table.HeaderCell textAlign="right">Invoiced</Table.HeaderCell>
                                                <Table.HeaderCell textAlign="right">Expected</Table.HeaderCell>
                                                <Table.HeaderCell>Carrier</Table.HeaderCell>
                                                <Table.HeaderCell>Service</Table.HeaderCell>
                                                <Table.HeaderCell textAlign="right">Discrepancy</Table.HeaderCell>
                                                <Table.HeaderCell>Reason</Table.HeaderCell>
                                                <Table.HeaderCell>Status</Table.HeaderCell>
                                                <Table.HeaderCell>Actions</Table.HeaderCell>
                                            </Table.Row>
                                        </Table.Header>
                                        <Table.Body>
                                            {filteredCharges.map(charge => (
                                                <Table.Row key={charge.uniqueId || charge.id} warning={charge.status === 'new'}>
                                                    <Table.Cell>
                                                        <a
                                                            href="#"
                                                            onClick={(e) => {
                                                                e.preventDefault();
                                                                this.openLookupModal(charge.trackingNumber);
                                                            }}
                                                        >
                                                            {charge.trackingNumber}
                                                        </a>
                                                        {charge.bigShipmentId && (
                                                            <div>
                                                                <small>
                                                                    <a href={`/shipper/shipment/${charge.bigShipmentId}`} target="_blank" rel="noopener noreferrer">
                                                                        View Shipment
                                                                    </a>
                                                                </small>
                                                            </div>
                                                        )}
                                                    </Table.Cell>
                                                    <Table.Cell>
                                                        <small>{charge.invoiceNumber}</small>
                                                    </Table.Cell>
                                                    <Table.Cell textAlign="right">
                                                        {this.formatCurrency(charge.invoicedAmount)}
                                                    </Table.Cell>
                                                    <Table.Cell textAlign="right">
                                                        {charge.expectedAmount
                                                            ? this.formatCurrency(charge.expectedAmount)
                                                            : <Label size="tiny">Unknown</Label>
                                                        }
                                                    </Table.Cell>
                                                    <Table.Cell>
                                                        {charge.shipmentData?.provider || '-'}
                                                    </Table.Cell>
                                                    <Table.Cell>
                                                        {charge.shipmentData?.servicelevelName || '-'}
                                                    </Table.Cell>
                                                    <Table.Cell textAlign="right" negative={charge.discrepancyPercent > 50}>
                                                        {charge.discrepancyAmount ? (
                                                            <>
                                                                {this.formatCurrency(charge.discrepancyAmount)}
                                                                <br />
                                                                <small>({charge.discrepancyPercent.toFixed(1)}%)</small>
                                                            </>
                                                        ) : '-'}
                                                    </Table.Cell>
                                                    <Table.Cell>
                                                        <small>{charge.flagReason}</small>
                                                        {charge.notes && (
                                                            <div style={{ marginTop: '4px', fontStyle: 'italic', color: '#666' }}>
                                                                Note: {charge.notes}
                                                            </div>
                                                        )}
                                                    </Table.Cell>
                                                    <Table.Cell>
                                                        <Label color={this.getStatusColor(charge.status)}>
                                                            {charge.status}
                                                        </Label>
                                                    </Table.Cell>
                                                    <Table.Cell>
                                                        <Button
                                                            size="tiny"
                                                            icon="edit"
                                                            onClick={() => this.openEditModal(charge)}
                                                        />
                                                    </Table.Cell>
                                                </Table.Row>
                                            ))}
                                        </Table.Body>
                                    </Table>
                                )}

                                {filteredCharges.length === 0 && !loadingCharges && (
                                    <Message info>
                                        No flagged charges match the current filters.
                                    </Message>
                                )}
                            </Segment>
                            )}
                        </Grid.Column>
                    </Grid.Row>
                </Grid>

                {/* Edit Charge Modal */}
                <Modal
                    open={editModalOpen}
                    onClose={() => this.setState({ editModalOpen: false })}
                    size="small"
                >
                    <Modal.Header>Edit Charge Flag</Modal.Header>
                    <Modal.Content>
                        {editingCharge && (
                            <Form>
                                <Form.Field>
                                    <label>Tracking Number</label>
                                    <Input value={editingCharge.trackingNumber} disabled />
                                </Form.Field>
                                <Form.Group widths="equal">
                                    <Form.Field>
                                        <label>Invoiced Amount</label>
                                        <Input value={this.formatCurrency(editingCharge.invoicedAmount)} disabled />
                                    </Form.Field>
                                    <Form.Field>
                                        <label>Expected Amount</label>
                                        <Input value={editingCharge.expectedAmount ? this.formatCurrency(editingCharge.expectedAmount) : 'Unknown'} disabled />
                                    </Form.Field>
                                </Form.Group>
                                <Form.Field>
                                    <label>Status</label>
                                    <Dropdown
                                        selection
                                        options={STATUS_OPTIONS}
                                        value={editStatus}
                                        onChange={(e, { value }) => this.setState({ editStatus: value })}
                                    />
                                </Form.Field>
                                <Form.Field>
                                    <label>Notes</label>
                                    <TextArea
                                        value={editNotes}
                                        onChange={(e) => this.setState({ editNotes: e.target.value })}
                                        placeholder="Add notes about this charge..."
                                    />
                                </Form.Field>
                            </Form>
                        )}
                    </Modal.Content>
                    <Modal.Actions>
                        <Button onClick={() => this.setState({ editModalOpen: false })}>
                            Cancel
                        </Button>
                        <Button primary onClick={() => this.saveChargeEdits()}>
                            <Icon name="save" />
                            Save
                        </Button>
                    </Modal.Actions>
                </Modal>

                {/* Shipment Lookup Modal */}
                <Modal
                    open={lookupModalOpen}
                    onClose={() => this.setState({ lookupModalOpen: false })}
                    size="small"
                >
                    <Modal.Header>Shipment Lookup: {lookupTrackingNumber}</Modal.Header>
                    <Modal.Content>
                        {lookupLoading ? (
                            <Loader active inline="centered">Looking up shipment...</Loader>
                        ) : lookupResult ? (
                            lookupResult.notFound ? (
                                <Message warning>
                                    <Message.Header>Shipment Not Found</Message.Header>
                                    <p>No shipment found with tracking number: {lookupTrackingNumber}</p>
                                </Message>
                            ) : lookupResult.error ? (
                                <Message negative>
                                    <Message.Header>Lookup Error</Message.Header>
                                    <p>{lookupResult.error}</p>
                                </Message>
                            ) : (
                                <>
                                    <Table definition>
                                        <Table.Body>
                                            <Table.Row>
                                                <Table.Cell width={4}>Shipment ID</Table.Cell>
                                                <Table.Cell>
                                                    <a href={`/shipper/shipment/${lookupResult.uniqueId}`} target="_blank" rel="noopener noreferrer">
                                                        {lookupResult.uniqueId}
                                                    </a>
                                                </Table.Cell>
                                            </Table.Row>
                                            <Table.Row>
                                                <Table.Cell>Status</Table.Cell>
                                                <Table.Cell>
                                                    <Label>{lookupResult.status}</Label>
                                                </Table.Cell>
                                            </Table.Row>
                                            <Table.Row>
                                                <Table.Cell>Order ID</Table.Cell>
                                                <Table.Cell>
                                                    {lookupResult.bigOrderId ? (
                                                        <a href={`/shop/order/${lookupResult.bigOrderId}`} target="_blank" rel="noopener noreferrer">
                                                            {lookupResult.bigOrderId}
                                                        </a>
                                                    ) : '-'}
                                                </Table.Cell>
                                            </Table.Row>
                                            <Table.Row>
                                                <Table.Cell>Created</Table.Cell>
                                                <Table.Cell>{this.formatDate(lookupResult.createdAt)}</Table.Cell>
                                            </Table.Row>
                                            {lookupResult.currentShippingLabel && (
                                                <>
                                                    <Table.Row>
                                                        <Table.Cell>Carrier</Table.Cell>
                                                        <Table.Cell>
                                                            {lookupResult.currentShippingLabel.rate?.provider || '-'}
                                                        </Table.Cell>
                                                    </Table.Row>
                                                    <Table.Row>
                                                        <Table.Cell>Service Level</Table.Cell>
                                                        <Table.Cell>
                                                            {lookupResult.currentShippingLabel.rate?.servicelevel_name || '-'}
                                                        </Table.Cell>
                                                    </Table.Row>
                                                    <Table.Row>
                                                        <Table.Cell>Quoted Rate</Table.Cell>
                                                        <Table.Cell>
                                                            {lookupResult.currentShippingLabel.rate?.amount
                                                                ? this.formatCurrency(parseFloat(lookupResult.currentShippingLabel.rate.amount))
                                                                : '-'}
                                                        </Table.Cell>
                                                    </Table.Row>
                                                </>
                                            )}
                                        </Table.Body>
                                    </Table>
                                </>
                            )
                        ) : null}
                    </Modal.Content>
                    <Modal.Actions>
                        <Button onClick={() => this.setState({ lookupModalOpen: false })}>
                            Close
                        </Button>
                        {lookupResult && !lookupResult.notFound && !lookupResult.error && (
                            <Button
                                primary
                                as="a"
                                href={`/shipper/shipment/${lookupResult.uniqueId}`}
                                target="_blank"
                            >
                                <Icon name="external" />
                                Open Shipment
                            </Button>
                        )}
                    </Modal.Actions>
                </Modal>
            </ExperimentalWrapper>
        );
    }
}
