import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { DatePicker } from 'antd';
import dayjs from 'dayjs';
import api from '../utils/api';
import { useToast } from '../App';
import LoadingState from '../components/LoadingState';
import ConfirmDialog from '../components/ConfirmDialog';

const { RangePicker } = DatePicker;


// Order View Modal Component
const OrderViewModal = ({ order, onClose }) => {
    if (!order) return null;

    const formatCurrency = (amount, currency = 'USD') => {
        return new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: currency
        }).format(amount);
    };

    const formatDate = (dateString) => {
        return new Date(dateString).toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    };

    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal-content modal-large" onClick={(e) => e.stopPropagation()}>
                <div className="modal-header">
                    <h3>Order Details #{order?.number || order?.id}</h3>
                    <button type="button" className="modal-close" onClick={onClose}>
                        ✕
                    </button>
                </div>

                <div className="modal-body">
                    <div className="order-details-grid">
                        {/* Order Information */}
                        <div className="order-section">
                            <h4>Order Information</h4>
                            <div className="detail-row">
                                <span className="label">Order Number:</span>
                                <span className="value">#{order.number || order.id}</span>
                            </div>
                            <div className="detail-row">
                                <span className="label">Status:</span>
                                <span className={`chip ${order.status}`}>{order.status}</span>
                            </div>
                            <div className="detail-row">
                                <span className="label">Date Created:</span>
                                <span className="value">{formatDate(order.date_created)}</span>
                            </div>
                            <div className="detail-row">
                                <span className="label">Total:</span>
                                <span className="value font-semibold">{formatCurrency(order.total, order.currency)}</span>
                            </div>
                        </div>

                        {/* Customer Information */}
                        <div className="order-section">
                            <h4>Customer Information</h4>
                            <div className="detail-row">
                                <span className="label">Name:</span>
                                <span className="value">{order.customer?.name || order.billing?.first_name + ' ' + order.billing?.last_name || 'N/A'}</span>
                            </div>
                            <div className="detail-row">
                                <span className="label">Email:</span>
                                <span className="value">{order.customer?.email || order.billing?.email || 'N/A'}</span>
                            </div>
                            <div className="detail-row">
                                <span className="label">Phone:</span>
                                <span className="value">{order.billing?.phone || 'N/A'}</span>
                            </div>
                        </div>

                        {/* Billing Address */}
                        {order.billing && (
                            <div className="order-section">
                                <h4>Billing Address</h4>
                                <div className="address-block">
                                    <div>{order.billing.first_name} {order.billing.last_name}</div>
                                    <div>{order.billing.address_1}</div>
                                    {order.billing.address_2 && <div>{order.billing.address_2}</div>}
                                    <div>{order.billing.city}, {order.billing.state} {order.billing.postcode}</div>
                                    <div>{order.billing.country}</div>
                                </div>
                            </div>
                        )}

                        {/* Shipping Address */}
                        {order.shipping && (
                            <div className="order-section">
                                <h4>Shipping Address</h4>
                                <div className="address-block">
                                    <div>{order.shipping.first_name} {order.shipping.last_name}</div>
                                    <div>{order.shipping.address_1}</div>
                                    {order.shipping.address_2 && <div>{order.shipping.address_2}</div>}
                                    <div>{order.shipping.city}, {order.shipping.state} {order.shipping.postcode}</div>
                                    <div>{order.shipping.country}</div>
                                </div>
                            </div>
                        )}
                    </div>

                    {/* Order Items */}
                    {order.line_items && order.line_items.length > 0 && (
                        <div className="order-section">
                            <h4>Order Items</h4>
                            <div className="items-table">
                                <table>
                                    <thead>
                                        <tr>
                                            <th>Product</th>
                                            <th>SKU</th>
                                            <th>Quantity</th>
                                            <th>Price</th>
                                            <th>Total</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {order.line_items.map((item, index) => (
                                            <tr key={index}>
                                                <td>{item.name}</td>
                                                <td>{item.sku || 'N/A'}</td>
                                                <td>{item.quantity}</td>
                                                <td>{formatCurrency(item.price, order.currency)}</td>
                                                <td>{formatCurrency(item.total, order.currency)}</td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    )}

                    {/* Order Notes */}
                    {order.customer_note && (
                        <div className="order-section">
                            <h4>Customer Notes</h4>
                            <div className="notes-block">
                                {order.customer_note}
                            </div>
                        </div>
                    )}
                </div>

                <div className="modal-footer">
                    <button type="button" className="btn btn-secondary" onClick={onClose}>
                        Close
                    </button>
                </div>
            </div>
        </div>
    );
};

const Orders = () => {
    const { showSuccess, showError } = useToast();
    const navigate = useNavigate();
    const [orders, setOrders] = useState([]);
    const [loading, setLoading] = useState(true);
    const [page, setPage] = useState(0);
    const [rowsPerPage, setRowsPerPage] = useState(25);
    const [totalCount, setTotalCount] = useState(0);
    const [selected, setSelected] = useState([]);
    const [viewDialogOpen, setViewDialogOpen] = useState(false);
    const [viewingOrder, setViewingOrder] = useState(null);
    const [syncing, setSyncing] = useState(false);
    const [syncingOrders, setSyncingOrders] = useState(new Set());
    const [activeTab, setActiveTab] = useState('orders');
    const [confirmDialog, setConfirmDialog] = useState({ isOpen: false, action: null, data: null });
    const [googleSheetsEnabled, setGoogleSheetsEnabled] = useState(false);
    const [googleSheetsConnected, setGoogleSheetsConnected] = useState(false);
    const [syncFields, setSyncFields] = useState({
        order_id: { label: 'Order ID', type: 'number', enabled: true },
        order_status: { label: 'Order Status', type: 'text', enabled: true },
        order_total: { label: 'Total Price', type: 'currency', enabled: true },
        product_names: { label: 'Product Names', type: 'text', enabled: true },
        product_skus: { label: 'Product SKUs', type: 'text', enabled: false },
        total_items: { label: 'Total Items', type: 'number', enabled: false },
        customer_name: { label: 'Customer Name', type: 'text', enabled: true },
        customer_email: { label: 'Customer Email', type: 'email', enabled: false },
        order_date: { label: 'Order Date', type: 'date', enabled: true },
        payment_method: { label: 'Payment Method', type: 'text', enabled: false },
        billing_address: { label: 'Billing Address', type: 'text', enabled: false },
        shipping_address: { label: 'Shipping Address', type: 'text', enabled: false }
    });
    const [loadingFields, setLoadingFields] = useState(false);
    const [savingFields, setSavingFields] = useState(false);
    const [syncingAll, setSyncingAll] = useState(false);

    // Filters
    const [filters, setFilters] = useState({
        search: '',
        status: '',
        dateFrom: '',
        dateTo: ''
    });
    const [dateRange, setDateRange] = useState([null, null]);

    const orderStatuses = [
        { value: '', label: 'All Statuses' },
        { value: 'pending', label: 'Pending' },
        { value: 'processing', label: 'Processing' },
        { value: 'on-hold', label: 'On Hold' },
        { value: 'completed', label: 'Completed' },
        { value: 'cancelled', label: 'Cancelled' },
        { value: 'refunded', label: 'Refunded' }
    ];

    useEffect(() => {
        loadSettings();
    }, []);

    useEffect(() => {
        if (activeTab === 'orders') {
            loadOrders();
        } else if (activeTab === 'sync-settings') {
            loadSyncFields();
        }
    }, [page, rowsPerPage, filters, activeTab]);

    const loadSettings = async () => {
        try {
            const response = await api.getSettings();
            if (response.success && response.settings) {
                setGoogleSheetsEnabled(response.settings.google_sheets_mode_enabled || false);
                setGoogleSheetsConnected(response.settings.google_sheets_connected || false);
            }
        } catch (err) {
            console.error('Failed to load settings:', err);
        }
    };

    const loadOrders = async () => {
        try {
            setLoading(true);

            const params = {
                page: page + 1,
                per_page: rowsPerPage
            };

            if (filters.search && filters.search.trim()) {
                params.search = filters.search.trim();
            }

            if (filters.status) {
                params.status = filters.status;
            }

            const response = await api.getOrders(params);

            if (response.success) {
                setOrders(response.orders || []);
                setTotalCount(response.total || 0);
            } else {
                throw new Error(response.message || 'Failed to load orders');
            }
        } catch (err) {
            showError(err.message);
        } finally {
            setLoading(false);
        }
    };

    const handleFilterChange = (field, value) => {
        setFilters(prev => ({
            ...prev,
            [field]: value
        }));
        setPage(0);
    };

    const handleDateRangeChange = (dates) => {
        setDateRange(dates);
        if (dates && dates[0] && dates[1]) {
            setFilters(prev => ({
                ...prev,
                dateFrom: dates[0].format('YYYY-MM-DD'),
                dateTo: dates[1].format('YYYY-MM-DD')
            }));
        } else {
            setFilters(prev => ({
                ...prev,
                dateFrom: '',
                dateTo: ''
            }));
        }
        setPage(0);
    };

    const clearFilters = () => {
        setFilters({
            search: '',
            status: '',
            dateFrom: '',
            dateTo: ''
        });
        setDateRange([null, null]);
        setPage(0);
    };

    const handleSelectAll = (event) => {
        if (event.target.checked) {
            setSelected(orders.map(order => order.id));
        } else {
            setSelected([]);
        }
    };

    const handleSelectOne = (orderId) => {
        setSelected(prev => {
            if (prev.includes(orderId)) {
                return prev.filter(id => id !== orderId);
            } else {
                return [...prev, orderId];
            }
        });
    };

    const handleEditOrder = (order) => {
        navigate(`/orders/edit/${order.id}`);
    };

    const handleViewOrder = (order) => {
        navigate(`/orders/view/${order.id}`);
    };


    const handleSync = async () => {
        try {
            setSyncing(true);
            const response = await api.syncOrders();

            if (response.success) {
                await loadOrders();
                showSuccess('Orders synced successfully');
            } else {
                throw new Error(response.message || 'Sync failed');
            }
        } catch (err) {
            showError(err.message);
        } finally {
            setSyncing(false);
        }
    };

    const handleSyncSingleOrder = async (orderId) => {
        try {
            setSyncingOrders(prev => new Set([...prev, orderId]));

            // Get spreadsheet settings from backend
            const settingsResponse = await api.getSettings();
            const spreadsheetUrl = settingsResponse.settings?.spreadsheet_url;
            const sheetName = settingsResponse.settings?.sheet_configs?.orders?.tabName || 'Orders';

            if (!spreadsheetUrl) {
                showError('Please configure Google Sheets URL in Settings first');
                return;
            }

            const response = await api.syncSingleOrder(orderId, spreadsheetUrl, sheetName);

            if (response.success) {
                showSuccess(`Order #${orderId} synced successfully`);
            } else {
                throw new Error(response.message || 'Sync failed');
            }
        } catch (err) {
            showError(err.message);
        } finally {
            setSyncingOrders(prev => {
                const newSet = new Set(prev);
                newSet.delete(orderId);
                return newSet;
            });
        }
    };

    const loadSyncFields = async () => {
        try {
            setLoadingFields(true);
            const response = await api.getOrderSyncFields();
            if (response.success) {
                setSyncFields(response.fields);
            } else {
                showError('Failed to load sync fields');
            }
        } catch (err) {
            showError('Error loading sync fields: ' + err.message);
        } finally {
            setLoadingFields(false);
        }
    };

    const handleFieldToggle = (fieldKey, enabled) => {
        if (fieldKey === 'order_id') return; // Order ID is always enabled

        setSyncFields(prev => ({
            ...prev,
            [fieldKey]: {
                ...prev[fieldKey],
                enabled: enabled
            }
        }));
    };

    const saveSyncFields = async () => {
        try {
            setSavingFields(true);

            // Prepare field settings for API
            const fieldSettings = {};
            Object.keys(syncFields).forEach(key => {
                fieldSettings[key] = syncFields[key].enabled;
            });

            const response = await api.updateOrderSyncFields(fieldSettings);

            if (response.success) {
                showSuccess('Sync fields updated successfully');
                // Auto sync all orders after saving settings
                await syncAllOrdersNow();
            } else {
                showError('Failed to update fields: ' + response.message);
            }
        } catch (err) {
            showError('Error saving fields: ' + err.message);
        } finally {
            setSavingFields(false);
        }
    };

    const syncAllOrdersNow = async () => {
        try {
            setSyncingAll(true);

            // Get spreadsheet settings from backend
            const settingsResponse = await api.getSettings();

            const spreadsheetUrl = settingsResponse.settings?.spreadsheet_url;
            const sheetName = settingsResponse.settings?.sheet_configs?.orders?.tabName || 'Orders';

            if (!spreadsheetUrl) {
                showError('Please configure Google Sheets URL in Settings first');
                return;
            }

            const response = await api.syncAllOrders(spreadsheetUrl, sheetName);

            if (response.success) {
                showSuccess(response.message);
                await loadOrders(); // Refresh orders list
            } else {
                showError('Sync failed: ' + response.message);
            }
        } catch (err) {
            showError('Sync error: ' + err.message);
        } finally {
            setSyncingAll(false);
        }
    };

    const handleExport = async () => {
        try {
            const response = await api.exportOrders(filters, 'csv');

            if (response.success && response.download_url) {
                window.open(response.download_url, '_blank');
                showSuccess('Export started successfully');
            }
        } catch (err) {
            showError(err.message);
        }
    };

    const handleBulkStatusUpdate = (status) => {
        if (selected.length === 0) {
            showError('Please select orders to update');
            return;
        }

        const statusLabels = {
            'processing': 'Processing',
            'completed': 'Completed',
            'cancelled': 'Cancelled',
            'on-hold': 'On Hold',
            'pending': 'Pending',
            'refunded': 'Refunded'
        };

        setConfirmDialog({
            isOpen: true,
            action: 'bulkStatusUpdate',
            data: { status, statusLabel: statusLabels[status] || status, count: selected.length }
        });
    };

    const executeBulkStatusUpdate = async () => {
        const { status } = confirmDialog.data;

        try {
            const response = await api.bulkUpdateOrderStatus(selected, status);

            if (response.success) {
                showSuccess(response.message);
                setSelected([]);
                await loadOrders();
            } else {
                showError(response.message || 'Failed to update orders');
            }
        } catch (err) {
            showError(err.message);
        }
    };

    const handleBulkDelete = async () => {
        if (selected.length === 0) {
            showError('Please select orders to delete');
            return;
        }

        setConfirmDialog({
            isOpen: true,
            action: 'bulkDelete',
            data: { count: selected.length }
        });
    };

    const executeBulkDelete = async () => {
        try {
            let deleted = 0;
            for (const orderId of selected) {
                try {
                    const response = await api.deleteOrder(orderId, true);
                    if (response.success) {
                        deleted++;
                    }
                } catch (err) {
                    console.error(`Failed to delete order ${orderId}:`, err);
                }
            }

            if (deleted > 0) {
                showSuccess(`Successfully deleted ${deleted} orders`);
                setSelected([]);
                await loadOrders();
            } else {
                showError('Failed to delete orders');
            }
        } catch (err) {
            showError(err.message);
        }
    };

    const getStatusChipClass = (status) => {
        const statusClasses = {
            pending: 'chip-warning',
            processing: 'chip-primary',
            'on-hold': 'chip-warning',
            completed: 'chip-success',
            cancelled: 'chip-danger',
            refunded: 'chip-secondary'
        };
        return statusClasses[status] || 'chip-secondary';
    };

    const formatCurrency = (amount, currency = 'USD') => {
        return new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: currency
        }).format(amount);
    };

    const formatDate = (dateString) => {
        return new Date(dateString).toLocaleDateString();
    };

    const handlePageChange = (newPage) => {
        setPage(newPage);
    };

    const handleRowsPerPageChange = (event) => {
        setRowsPerPage(parseInt(event.target.value, 10));
        setPage(0);
    };

    // Only show full-page loader on initial load (no orders yet and no filters applied)
    const isInitialLoad = loading && orders.length === 0 && !filters.search && !filters.status;

    if (isInitialLoad) {
        return (
            <div className="page">
                <div className="container container-xl">
                    <LoadingState message="Loading orders..." />
                </div>
            </div>
        );
    }

    return (
        <div className="page orders">
            <div className="container container-xl">
                {/* Header */}
                <div className="page-header">
                    <div className="page-title">
                        <h1>📦 Orders</h1>
                        <p>Manage your WooCommerce orders</p>
                    </div>
                </div>

                {/* Tab Navigation */}
                <div className="tab-navigation">
                    <button
                        className={`tab-button ${activeTab === 'orders' ? 'active' : ''}`}
                        onClick={() => setActiveTab('orders')}
                    >
                        📦 Orders List
                    </button>
                    {googleSheetsEnabled && (
                        <button
                            className={`tab-button ${activeTab === 'sync-settings' ? 'active' : ''}`}
                            onClick={() => setActiveTab('sync-settings')}
                        >
                            📊 Export Settings
                        </button>
                    )}
                </div>

                {activeTab === 'orders' && (
                    <div className="orders-container">
                        <div className="page-header">
                            <div className="page-actions">
                                <button
                                    className="btn btn-success btn-sm"
                                    onClick={() => navigate('/orders/add')}
                                >
                                    +  Create Order
                                </button>
                                <button
                                    className="btn btn-secondary btn-sm"
                                    onClick={handleExport}
                                >
                                    📥 Export CSV
                                </button>
                                <button
                                    className={`btn btn-primary btn-sm ${syncing ? 'btn-loading' : ''}`}
                                    onClick={handleSync}
                                    disabled={syncing}
                                >
                                    {syncing ? (
                                        <>
                                            <div className="spinner"></div>
                                            Exporting...
                                        </>
                                    ) : (
                                       '🔄 Export to GS'
                                    )}
                                </button>
                                <button
                                    className="btn btn-secondary btn-sm"
                                    onClick={loadOrders}
                                    disabled={loading}
                                >
                                    🔄 Refresh
                                </button>
                            </div>
                        </div>

                        {/* Filters Bar */}
                        <div className="filters-bar">
                            <div className="filters-row">
                                <div className="filter-item filter-search">
                                    <input
                                        type="text"
                                        placeholder="🔍 Search orders..."
                                        value={filters.search}
                                        onChange={(e) => handleFilterChange('search', e.target.value)}
                                        className="search-input"
                                    />
                                </div>
                                <div className="filter-item">
                                    <select
                                        value={filters.status}
                                        onChange={(e) => handleFilterChange('status', e.target.value)}
                                        className="filter-select"
                                    >
                                        {orderStatuses.map(status => (
                                            <option key={status.value} value={status.value}>
                                                {status.label}
                                            </option>
                                        ))}
                                    </select>
                                </div>
                                <div className="filter-item filter-date-range">
                                    <RangePicker
                                        value={dateRange}
                                        onChange={handleDateRangeChange}
                                        placeholder={['From Date', 'To Date']}
                                        format="YYYY-MM-DD"
                                        allowClear
                                        size="middle"
                                        className="date-range-picker"
                                        style={{ width: '280px' }}
                                    />
                                </div>
                                <div className="filter-item">
                                    <button
                                        className="btn btn-secondary btn-clear"
                                        onClick={clearFilters}
                                        title="Clear all filters"
                                    >
                                        ✕ Clear
                                    </button>
                                </div>
                            </div>
                        </div>

                        {/* Bulk Actions */}
                        {selected.length > 0 && (
                            <div className="card mb-4">
                                <div className="card-content">
                                    <div className="bulk-actions flex items-center justify-between">
                                        <div className="bulk-info">
                                            <strong>{selected.length} orders selected</strong>
                                        </div>
                                        <div className="bulk-buttons flex gap-2">
                                            <button
                                                className="btn btn-primary btn-sm"
                                                onClick={() => navigate('/orders/bulk-edit', { state: { selectedOrders: selected } })}
                                            >
                                                ✏️ Bulk Edit
                                            </button>
                                            <button
                                                className="btn btn-primary btn-sm"
                                                onClick={() => handleBulkStatusUpdate('processing')}
                                            >
                                                Mark as Processing
                                            </button>
                                            <button
                                                className="btn btn-success btn-sm"
                                                onClick={() => handleBulkStatusUpdate('completed')}
                                            >
                                                Mark as Completed
                                            </button>
                                            <button
                                                className="btn btn-danger btn-sm"
                                                onClick={() => handleBulkStatusUpdate('cancelled')}
                                            >
                                                Cancel Orders
                                            </button>
                                            <button
                                                className="btn btn-danger btn-sm"
                                                onClick={handleBulkDelete}
                                            >
                                                Delete Orders
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        )}

                        {/* Orders Table */}
                        <div className="card">
                            <div className="table-container">
                                <table className="orders-table">
                                    <thead>
                                        <tr>
                                            <th className="checkbox-col">
                                                <input
                                                    type="checkbox"
                                                    checked={orders.length > 0 && selected.length === orders.length}
                                                    onChange={handleSelectAll}
                                                />
                                            </th>
                                            <th>Order</th>
                                            <th>Status</th>
                                            <th>Customer</th>
                                            <th>Total</th>
                                            <th>Date</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {loading ? (
                                            <tr>
                                                <td colSpan="7" className="text-center">
                                                    <LoadingState message="Loading orders..." />
                                                </td>
                                            </tr>
                                        ) : orders.length === 0 ? (
                                            <tr>
                                                <td colSpan="7" className="text-center">
                                                    <div className="empty-state">
                                                        <div className="empty-icon">📦</div>
                                                        <p>No orders found</p>
                                                        <p className="text-gray-600">Try adjusting your filters or sync data</p>
                                                    </div>
                                                </td>
                                            </tr>
                                        ) : (
                                            orders.map((order) => (
                                                <tr key={order.id} className="order-row">
                                                    <td className="checkbox-col">
                                                        <input
                                                            type="checkbox"
                                                            checked={selected.includes(order.id)}
                                                            onChange={() => handleSelectOne(order.id)}
                                                        />
                                                    </td>
                                                    <td>
                                                        <div className="order-info">
                                                            <div className="order-number">
                                                                #{order.number || order.id}
                                                            </div>
                                                            <div className="order-items text-gray-600">
                                                                {order.items_count} items
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div className={`chip ${getStatusChipClass(order.status)}`}>
                                                            {order.status}
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div className="customer-info">
                                                            <div className="customer-name">
                                                                {order.customer?.name || 'N/A'}
                                                            </div>
                                                            <div className="customer-email text-gray-600">
                                                                {order.customer?.email || 'N/A'}
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div className="order-total font-semibold">
                                                            {formatCurrency(order.total, order.currency || 'USD')}
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div className="order-date">
                                                            {formatDate(order.date_created)}
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div className="order-actions flex gap-1">
                                                            <button
                                                                className="btn btn-secondary btn-sm"
                                                                onClick={() => handleEditOrder(order)}
                                                                title="Edit Order"
                                                            >
                                                                ✏️
                                                            </button>
                                                            <button
                                                                className="btn btn-secondary btn-sm"
                                                                onClick={() => handleViewOrder(order)}
                                                                title="View Order"
                                                            >
                                                                👁️
                                                            </button>
                                                            {/* <button
                                                                className={`btn btn-primary btn-sm ${syncingOrders.has(order.id) ? 'btn-loading' : ''}`}
                                                                onClick={() => handleSyncSingleOrder(order.id)}
                                                                disabled={syncingOrders.has(order.id)}
                                                                title="Sync to Google Sheets"
                                                            >
                                                                {syncingOrders.has(order.id) ? (
                                                                    <div className="spinner"></div>
                                                                ) : (
                                                                    '📊'
                                                                )}
                                                            </button> */}
                                                        </div>
                                                    </td>
                                                </tr>
                                            ))
                                        )}
                                    </tbody>
                                </table>
                            </div>

                            {/* Pagination */}
                            {totalCount > 0 && (
                                <div className="table-pagination">
                                    <div className="pagination-info">
                                        Showing {page * rowsPerPage + 1} to {Math.min((page + 1) * rowsPerPage, totalCount)} of {totalCount} orders
                                    </div>
                                    <div className="pagination-controls flex items-center gap-2">
                                        <select
                                            value={rowsPerPage}
                                            onChange={handleRowsPerPageChange}
                                            className="rows-per-page"
                                        >
                                            <option value={10}>10 per page</option>
                                            <option value={25}>25 per page</option>
                                            <option value={50}>50 per page</option>
                                            <option value={100}>100 per page</option>
                                        </select>
                                        <button
                                            className="btn btn-secondary btn-sm"
                                            onClick={() => handlePageChange(page - 1)}
                                            disabled={page === 0}
                                        >
                                            ← Previous
                                        </button>
                                        <span className="page-info">
                                            Page {page + 1} of {Math.ceil(totalCount / rowsPerPage)}
                                        </span>
                                        <button
                                            className="btn btn-secondary btn-sm"
                                            onClick={() => handlePageChange(page + 1)}
                                            disabled={(page + 1) * rowsPerPage >= totalCount}
                                        >
                                            Next →
                                        </button>
                                    </div>
                                </div>
                            )}
                        </div>

                    </div>
                )}

                {activeTab === 'sync-settings' && (
                    <div className="sync-settings-container">
                        {!googleSheetsConnected && (
                            <div className="alert alert-warning" style={{ marginBottom: '20px' }}>
                                <div className="alert-content">
                                    <strong>⚠️ Google Sheets Not Connected</strong>
                                    <p style={{ margin: '8px 0 0 0' }}>
                                        Please configure Google Sheets from <a href="#/settings?tab=google-sheets" style={{ color: 'inherit', textDecoration: 'underline' }}>Settings → 📊 Google Sheets</a> to use the export feature.
                                    </p>
                                </div>
                            </div>
                        )}
                        <div className="card">
                            <div className="card-header">
                                <h3>📊 Order Export Configuration</h3>
                                <p>Configure which order fields to sync to Google Sheets</p>
                            </div>
                            <div className="card-content">
                                {loadingFields ? (
                                    <div className="loading-center">
                                        <div className="spinner"></div>
                                        <p>Loading sync fields...</p>
                                    </div>
                                ) : (
                                    <>
                                        <div className="sync-fields-section">
                                            <h4>Select Fields to Export</h4>
                                            <p className="section-description">
                                                Toggle the fields you want to include when syncing orders to Google Sheets.
                                                Changes are saved automatically and will apply to all future syncs.
                                            </p>

                                            <div className="fields-grid">
                                                {Object.entries(syncFields).map(([key, field]) => (
                                                    <div key={key} className={`field-item ${field.enabled ? 'enabled' : 'disabled'}`}>
                                                        <div className="field-header">
                                                            <div className="field-info">
                                                                <span className="field-name">{field.label}</span>
                                                                {key === 'order_id' && (
                                                                    <span className="field-required">(Required)</span>
                                                                )}
                                                                <div className="field-type">{field.type}</div>
                                                            </div>
                                                            <label className="switch">
                                                                <input
                                                                    type="checkbox"
                                                                    checked={field.enabled}
                                                                    onChange={(e) => handleFieldToggle(key, e.target.checked)}
                                                                    disabled={key === 'order_id'} // Order ID always enabled
                                                                />
                                                                <span className="slider"></span>
                                                            </label>
                                                        </div>
                                                    </div>
                                                ))}
                                            </div>

                                            <div className="fields-summary">
                                                <strong>
                                                    {Object.values(syncFields).filter(field => field.enabled).length} fields selected
                                                </strong>
                                            </div>

                                            <div className="sync-actions">
                                                <button
                                                    className={`btn btn-primary ${savingFields ? 'btn-loading' : ''}`}
                                                    onClick={saveSyncFields}
                                                    disabled={savingFields}
                                                >
                                                    {savingFields ? (
                                                        <>
                                                            <div className="spinner"></div>
                                                            Saving & Syncing...
                                                        </>
                                                    ) : (
                                                        '💾 Save & Export All Orders'
                                                    )}
                                                </button>

                                                <button
                                                    className={`btn btn-success btn-lg ${syncingAll ? 'btn-loading' : ''}`}
                                                    onClick={syncAllOrdersNow}
                                                    disabled={syncingAll}
                                                >
                                                    {syncingAll ? (
                                                        <>
                                                            <div className="spinner"></div>
                                                            Syncing All Orders...
                                                        </>
                                                    ) : (
                                                        '🚀 Export All Orders Now'
                                                    )}
                                                </button>
                                            </div>
                                        </div>

                                        {/* Preview Section */}
                                        <div className="preview-section">
                                            <h4>Google Sheets Preview</h4>
                                            <p className="section-description">
                                                This is how your Google Sheets columns will look:
                                            </p>

                                            <div className="preview-table">
                                                <div className="preview-header">
                                                    {Object.entries(syncFields)
                                                        .filter(([, field]) => field.enabled)
                                                        .map(([key, field]) => (
                                                            <div key={key} className="preview-column">
                                                                {field.label}
                                                            </div>
                                                        ))
                                                    }
                                                </div>
                                                <div className="preview-row">
                                                    {Object.entries(syncFields)
                                                        .filter(([, field]) => field.enabled)
                                                        .map(([key]) => (
                                                            <div key={key} className="preview-cell">
                                                                {key === 'order_id' ? '12345' :
                                                                    key === 'order_status' ? 'Completed' :
                                                                        key === 'order_total' ? '$99.99' :
                                                                            key === 'product_names' ? 'Product A, Product B' :
                                                                                key === 'customer_name' ? 'John Doe' :
                                                                                    'Sample data...'}
                                                            </div>
                                                        ))
                                                    }
                                                </div>
                                            </div>
                                        </div>

                                        {/* Export Status */}
                                        <div className="sync-status-section">
                                            <h4>Export Status</h4>
                                            <div className="status-info">
                                                <div className="status-item">
                                                    <span className="status-label">Google Sheets:</span>
                                                    <span className="status-value">Connected ✅</span>
                                                </div>
                                                <div className="status-item">
                                                    <span className="status-label">Last Export:</span>
                                                    <span className="status-value">Never</span>
                                                </div>
                                                <div className="status-item">
                                                    <span className="status-label">Total Orders:</span>
                                                    <span className="status-value">{orders.length}</span>
                                                </div>
                                            </div>
                                        </div>
                                    </>
                                )}
                            </div>
                        </div>
                    </div>
                )}

                {/* View Order Modal */}
                {viewDialogOpen && (
                    <OrderViewModal
                        order={viewingOrder}
                        onClose={() => {
                            setViewDialogOpen(false);
                            setViewingOrder(null);
                        }}
                    />
                )}

                {/* Confirmation Dialog */}
                <ConfirmDialog
                    isOpen={confirmDialog.isOpen}
                    onClose={() => setConfirmDialog({ isOpen: false, action: null, data: null })}
                    onConfirm={() => {
                        if (confirmDialog.action === 'bulkDelete') {
                            executeBulkDelete();
                        } else if (confirmDialog.action === 'bulkStatusUpdate') {
                            executeBulkStatusUpdate();
                        }
                        setConfirmDialog({ isOpen: false, action: null, data: null });
                    }}
                    title={confirmDialog.action === 'bulkStatusUpdate' ? 'Confirm Status Update' : 'Confirm Delete'}
                    confirmText={confirmDialog.action === 'bulkStatusUpdate' ? 'Update Status' : 'Delete Orders'}
                    confirmButtonClass={confirmDialog.action === 'bulkDelete' ? 'btn-danger' : 'btn-primary'}
                >
                    {confirmDialog.action === 'bulkDelete' && (
                        <>
                            <p>Are you sure you want to delete <strong>{confirmDialog.data?.count} orders</strong>?</p>
                            <p className="text-danger">This action cannot be undone.</p>
                        </>
                    )}
                    {confirmDialog.action === 'bulkStatusUpdate' && (
                        <p>Are you sure you want to mark <strong>{confirmDialog.data?.count} orders</strong> as <strong>{confirmDialog.data?.statusLabel}</strong>?</p>
                    )}
                </ConfirmDialog>

            </div>
        </div>
    );
};


export default Orders;