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

const Customers = () => {
    const navigate = useNavigate();
    const { showSuccess, showError } = useToast();

    const [loading, setLoading] = useState(true);
    const [customers, setCustomers] = useState([]);
    const [searchTerm, setSearchTerm] = useState('');
    const [roleFilter, setRoleFilter] = useState('all');
    const [currentPage, setCurrentPage] = useState(1);
    const [totalPages, setTotalPages] = useState(1);
    const [activeTab, setActiveTab] = useState('customers');
    const [syncing, setSyncing] = useState(false);
    const [googleSheetsEnabled, setGoogleSheetsEnabled] = useState(false);
    const [googleSheetsConnected, setGoogleSheetsConnected] = useState(false);
    const [deleteModalOpen, setDeleteModalOpen] = useState(false);
    const [customerToDelete, setCustomerToDelete] = useState(null);
    const [viewingCustomer, setViewingCustomer] = useState(null);
    const [viewModalOpen, setViewModalOpen] = useState(false);

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

    // Auto-search with debouncing
    useEffect(() => {
        if (activeTab === 'customers') {
            const timer = setTimeout(() => {
                loadCustomers();
            }, 300); // 300ms debounce

            return () => clearTimeout(timer);
        }
    }, [searchTerm, currentPage, roleFilter, 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 loadCustomers = async () => {
        try {
            setLoading(true);
            const response = await api.get('/customers', {
                page: currentPage,
                per_page: 20,
                search: searchTerm,
                role: roleFilter
            });

            if (response.success) {
                setCustomers(response.customers || []);
                setTotalPages(response.total_pages || 1);
            }
        } catch (err) {
            console.error('Load customers error:', err);
            showError('Failed to load customers: ' + err.message);
            setCustomers([]);
        } finally {
            setLoading(false);
        }
    };

    const handleSync = async () => {
        try {
            setSyncing(true);

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

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

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

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

    const handleClearFilters = () => {
        setSearchTerm('');
        setRoleFilter('all');
        setCurrentPage(1);
    };

    const handleDelete = (customer) => {
        setCustomerToDelete(customer);
        setDeleteModalOpen(true);
    };

    const confirmDelete = async () => {
        if (!customerToDelete) return;

        try {
            const response = await api.delete(`/customers/${customerToDelete.id}`);
            if (response.success) {
                showSuccess('Customer deleted successfully');
                loadCustomers();
            } else {
                throw new Error(response.message || 'Failed to delete customer');
            }
        } catch (err) {
            showError(err.message);
        } finally {
            setDeleteModalOpen(false);
            setCustomerToDelete(null);
        }
    };

    const handleView = async (customer) => {
        try {
            // Load full customer details
            const response = await api.get(`/customers/${customer.id}`);
            if (response.success) {
                // Add avatar_url from the list data if not present
                const customerData = response.customer;
                if (!customerData.avatar_url && customer.avatar_url) {
                    customerData.avatar_url = customer.avatar_url;
                }
                setViewingCustomer(customerData);
                setViewModalOpen(true);
            }
        } catch (err) {
            showError('Failed to load customer details: ' + err.message);
        }
    };

    // Customer List View
    return (
        <div className="page customers-page">
            <div className="page-container">
                {/* Header */}
                <div className="page-header">
                    <div className="page-title">
                        <h1>Customers</h1>
                        <p>Manage your WooCommerce customers</p>
                    </div>
                </div>

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

                {activeTab === 'customers' && (
                    <div className="customers-container">
                        <div className="page-header">
                            <div className="page-actions">
                                <button
                                    className="btn btn-primary btn-sm"
                                    onClick={() => navigate('/customers/add')}
                                >
                                    + Add Customer
                                </button>
                                <button
                                    className={`btn btn-primary btn-sm ${syncing ? 'btn-loading' : ''}`}
                                    onClick={handleSync}
                                    disabled={syncing}
                                >
                                    {syncing ? (
                                        <>
                                            <div className="spinner"></div>
                                            Exporting...
                                        </>
                                    ) : (
                                        '🔄 Export'
                                    )}
                                </button>
                            </div>
                        </div>

                        {/* Filters */}
                        <div className="filters-card">
                            <div className="filters-row">
                                <div className="filter-group">
                                    <input
                                        type="text"
                                        className="filter-input"
                                        placeholder="🔍 Search by name, email, username..."
                                        value={searchTerm}
                                        onChange={(e) => {
                                            setSearchTerm(e.target.value);
                                            setCurrentPage(1);
                                        }}
                                    />
                                </div>
                                <div className="filter-group">
                                    <select
                                        className="filter-select"
                                        value={roleFilter}
                                        onChange={(e) => {
                                            setRoleFilter(e.target.value);
                                            setCurrentPage(1);
                                        }}
                                    >
                                        <option value="all">All Roles</option>
                                        <option value="customer">Customer</option>
                                        <option value="shop_manager">Shop Manager</option>
                                        <option value="subscriber">Subscriber</option>
                                        <option value="contributor">Contributor</option>
                                        <option value="author">Author</option>
                                        <option value="editor">Editor</option>
                                        <option value="administrator">Administrator</option>
                                    </select>
                                </div>
                                {(searchTerm || roleFilter !== 'all') && (
                                    <button
                                        className="btn btn-secondary"
                                        onClick={handleClearFilters}
                                        title="Clear all filters"
                                    >
                                        ✕ Clear
                                    </button>
                                )}
                            </div>
                        </div>

                        {/* Customers Table */}
                        <div className="data-table-card">
                            {loading ? (
                                <LoadingState message="Loading customers..." />
                            ) : (
                                <>
                                    <div className="table-responsive">
                                        <table className="data-table">
                                            <thead>
                                                <tr>
                                                    <th>Customer</th>
                                                    <th>Email</th>
                                                    <th>Role</th>
                                                    <th>Orders</th>
                                                    <th>Total Spent</th>
                                                    <th>Registered</th>
                                                    <th className="actions-column">Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {customers.length === 0 ? (
                                                    <tr>
                                                        <td colSpan="7" className="empty-state">
                                                            <div className="empty-icon">👥</div>
                                                            <p>No customers found</p>
                                                        </td>
                                                    </tr>
                                                ) : (
                                                    customers.map(customer => (
                                                        <tr key={customer.id}>
                                                            <td>
                                                                <div className="customer-cell">
                                                                    {customer.avatar_url ? (
                                                                        <img
                                                                            src={customer.avatar_url}
                                                                            alt={customer.username}
                                                                            className="customer-avatar-img"
                                                                        />
                                                                    ) : (
                                                                        <div className="customer-avatar">
                                                                            {(customer.first_name?.charAt(0) || customer.username?.charAt(0) || 'U').toUpperCase()}
                                                                        </div>
                                                                    )}
                                                                    <div className="customer-info">
                                                                        <div className="customer-name">
                                                                            {customer.first_name} {customer.last_name}
                                                                        </div>
                                                                        <div className="customer-username">@{customer.username}</div>
                                                                    </div>
                                                                </div>
                                                            </td>
                                                            <td>{customer.email}</td>
                                                            <td>
                                                                <span className="role-badge">{customer.role}</span>
                                                            </td>
                                                            <td>{customer.orders_count || 0}</td>
                                                            <td>${customer.total_spent || '0.00'}</td>
                                                            <td>{new Date(customer.date_created).toLocaleDateString()}</td>
                                                            <td className="actions-column">
                                                                <div className="action-buttons">
                                                                    <button
                                                                        className="btn-icon"
                                                                        onClick={() => handleView(customer)}
                                                                        title="View"
                                                                    >
                                                                        👁️
                                                                    </button>
                                                                    <button
                                                                        className="btn-icon"
                                                                        onClick={() => navigate(`/customers/edit/${customer.id}`)}
                                                                        title="Edit"
                                                                    >
                                                                        ✏️
                                                                    </button>
                                                                    <button
                                                                        className="btn-icon btn-danger"
                                                                        onClick={() => handleDelete(customer)}
                                                                        title="Delete"
                                                                    >
                                                                        🗑️
                                                                    </button>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    ))
                                                )}
                                            </tbody>
                                        </table>
                                    </div>

                                    {/* Pagination */}
                                    {totalPages > 1 && (
                                        <div className="pagination">
                                            <button
                                                className="btn btn-sm btn-secondary"
                                                disabled={currentPage === 1}
                                                onClick={() => setCurrentPage(currentPage - 1)}
                                            >
                                                Previous
                                            </button>
                                            <span className="pagination-info">
                                                Page {currentPage} of {totalPages}
                                            </span>
                                            <button
                                                className="btn btn-sm btn-secondary"
                                                disabled={currentPage === totalPages}
                                                onClick={() => setCurrentPage(currentPage + 1)}
                                            >
                                                Next
                                            </button>
                                        </div>
                                    )}
                                </>
                            )}
                        </div>
                    </div>
                )}

                {activeTab === 'sync-settings' && (
                    <>
                        {!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>
                        )}
                        <CustomerSyncSettings customers={customers} />
                    </>
                )}

                {/* Customer View Modal - CV Style */}
                {viewModalOpen && viewingCustomer && (
                    <div className="modal-overlay" onClick={() => setViewModalOpen(false)}>
                        <div className="modal-content customer-cv-modal" onClick={(e) => e.stopPropagation()}>
                            <div className="modal-header">
                                <h3>Customer Profile</h3>
                                <button className="modal-close" onClick={() => setViewModalOpen(false)}>
                                    ✕
                                </button>
                            </div>
                            <div className="modal-body">
                                <div className="customer-cv">
                                    {/* Header Section */}
                                    <div className="cv-header">
                                        {viewingCustomer.avatar_url ? (
                                            <img
                                                src={viewingCustomer.avatar_url}
                                                alt={viewingCustomer.username}
                                                className="cv-avatar-img"
                                            />
                                        ) : (
                                            <div className="cv-avatar">
                                                {(viewingCustomer.first_name?.charAt(0) || viewingCustomer.username?.charAt(0) || 'U').toUpperCase()}
                                            </div>
                                        )}
                                        <div className="cv-header-info">
                                            <h2>{viewingCustomer.first_name} {viewingCustomer.last_name}</h2>
                                            <p className="cv-username">@{viewingCustomer.username}</p>
                                            <div className="cv-badges">
                                                <span className="cv-badge role">{viewingCustomer.role}</span>
                                                <span className="cv-badge">ID: {viewingCustomer.id}</span>
                                            </div>
                                        </div>
                                    </div>

                                    {/* Contact Information */}
                                    <div className="cv-section">
                                        <h3 className="cv-section-title">📧 Contact Information</h3>
                                        <div className="cv-grid">
                                            <div className="cv-item">
                                                <span className="cv-label">Email</span>
                                                <span className="cv-value">{viewingCustomer.email}</span>
                                            </div>
                                            {viewingCustomer.billing?.phone && (
                                                <div className="cv-item">
                                                    <span className="cv-label">Phone</span>
                                                    <span className="cv-value">{viewingCustomer.billing.phone}</span>
                                                </div>
                                            )}
                                        </div>
                                    </div>

                                    {/* Account Statistics */}
                                    <div className="cv-section">
                                        <h3 className="cv-section-title">📊 Account Statistics</h3>
                                        <div className="cv-stats">
                                            <div className="cv-stat-card">
                                                <div className="cv-stat-icon">🛒</div>
                                                <div className="cv-stat-info">
                                                    <div className="cv-stat-value">{viewingCustomer.orders_count || 0}</div>
                                                    <div className="cv-stat-label">Total Orders</div>
                                                </div>
                                            </div>
                                            <div className="cv-stat-card">
                                                <div className="cv-stat-icon">💰</div>
                                                <div className="cv-stat-info">
                                                    <div className="cv-stat-value">${viewingCustomer.total_spent || '0.00'}</div>
                                                    <div className="cv-stat-label">Total Spent</div>
                                                </div>
                                            </div>
                                            <div className="cv-stat-card">
                                                <div className="cv-stat-icon">📅</div>
                                                <div className="cv-stat-info">
                                                    <div className="cv-stat-value">
                                                        {new Date(viewingCustomer.date_created).toLocaleDateString()}
                                                    </div>
                                                    <div className="cv-stat-label">Member Since</div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    {/* Billing Address */}
                                    {viewingCustomer.billing && (
                                        <div className="cv-section">
                                            <h3 className="cv-section-title">🏠 Billing Address</h3>
                                            <div className="cv-address">
                                                {viewingCustomer.billing.company && (
                                                    <p><strong>{viewingCustomer.billing.company}</strong></p>
                                                )}
                                                <p>{viewingCustomer.billing.first_name} {viewingCustomer.billing.last_name}</p>
                                                {viewingCustomer.billing.address_1 && (
                                                    <>
                                                        <p>{viewingCustomer.billing.address_1}</p>
                                                        {viewingCustomer.billing.address_2 && <p>{viewingCustomer.billing.address_2}</p>}
                                                        <p>
                                                            {viewingCustomer.billing.city}
                                                            {viewingCustomer.billing.state && `, ${viewingCustomer.billing.state}`}
                                                            {viewingCustomer.billing.postcode && ` ${viewingCustomer.billing.postcode}`}
                                                        </p>
                                                        <p>{viewingCustomer.billing.country}</p>
                                                    </>
                                                )}
                                            </div>
                                        </div>
                                    )}

                                    {/* Shipping Address */}
                                    {viewingCustomer.shipping && viewingCustomer.shipping.address_1 && (
                                        <div className="cv-section">
                                            <h3 className="cv-section-title">📦 Shipping Address</h3>
                                            <div className="cv-address">
                                                {viewingCustomer.shipping.company && (
                                                    <p><strong>{viewingCustomer.shipping.company}</strong></p>
                                                )}
                                                <p>{viewingCustomer.shipping.first_name} {viewingCustomer.shipping.last_name}</p>
                                                <p>{viewingCustomer.shipping.address_1}</p>
                                                {viewingCustomer.shipping.address_2 && <p>{viewingCustomer.shipping.address_2}</p>}
                                                <p>
                                                    {viewingCustomer.shipping.city}
                                                    {viewingCustomer.shipping.state && `, ${viewingCustomer.shipping.state}`}
                                                    {viewingCustomer.shipping.postcode && ` ${viewingCustomer.shipping.postcode}`}
                                                </p>
                                                <p>{viewingCustomer.shipping.country}</p>
                                            </div>
                                        </div>
                                    )}
                                </div>
                            </div>
                            <div className="modal-footer">
                                <button
                                    className="btn btn-primary"
                                    onClick={() => {
                                        setViewModalOpen(false);
                                        navigate(`/customers/edit/${viewingCustomer.id}`);
                                    }}
                                >
                                    ✏️ Edit Customer
                                </button>
                                <button className="btn btn-secondary" onClick={() => setViewModalOpen(false)}>
                                    Close
                                </button>
                            </div>
                        </div>
                    </div>
                )}

                {/* Delete Confirmation Modal */}
                <ConfirmDialog
                    isOpen={deleteModalOpen}
                    onClose={() => setDeleteModalOpen(false)}
                    onConfirm={confirmDelete}
                    title="Confirm Delete"
                    confirmText="Delete Customer"
                    confirmButtonClass="btn-danger"
                >
                    <p>Are you sure you want to delete customer <strong>{customerToDelete?.display_name || customerToDelete?.username}</strong>?</p>
                    <p className="text-danger">This action cannot be undone.</p>
                </ConfirmDialog>

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

// Customer Editor Component (Add/Edit)
const CustomerEditor = ({ customerId }) => {
    const navigate = useNavigate();
    const { showSuccess, showError } = useToast();
    const [loading, setLoading] = useState(!!customerId);
    const [saving, setSaving] = useState(false);

    const [formData, setFormData] = useState({
        username: '',
        email: '',
        first_name: '',
        last_name: '',
        role: 'customer',
        password: '',
        billing: {
            first_name: '',
            last_name: '',
            company: '',
            address_1: '',
            address_2: '',
            city: '',
            state: '',
            postcode: '',
            country: 'US',
            phone: '',
            email: ''
        },
        shipping: {
            first_name: '',
            last_name: '',
            company: '',
            address_1: '',
            address_2: '',
            city: '',
            state: '',
            postcode: '',
            country: 'US'
        }
    });

    useEffect(() => {
        if (customerId) {
            loadCustomer();
        }
    }, [customerId]);

    const loadCustomer = async () => {
        try {
            setLoading(true);
            const response = await api.get(`/customers/${customerId}`);
            if (response.success) {
                setFormData({
                    ...formData,
                    ...response.customer,
                    password: '' // Never load password
                });
            }
        } catch (err) {
            showError('Failed to load customer: ' + err.message);
        } finally {
            setLoading(false);
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();

        try {
            setSaving(true);

            if (customerId) {
                const response = await api.put(`/customers/${customerId}`, formData);
                if (response.success) {
                    showSuccess('Customer updated successfully');
                    navigate('/customers');
                }
            } else {
                const response = await api.post('/customers', formData);
                if (response.success) {
                    showSuccess('Customer created successfully');
                    navigate('/customers');
                }
            }
        } catch (err) {
            showError(err.message);
        } finally {
            setSaving(false);
        }
    };

    const handleChange = (field, value) => {
        setFormData(prev => ({
            ...prev,
            [field]: value
        }));
    };

    const handleAddressChange = (type, field, value) => {
        setFormData(prev => ({
            ...prev,
            [type]: {
                ...prev[type],
                [field]: value
            }
        }));
    };

    const copyBillingToShipping = () => {
        setFormData(prev => ({
            ...prev,
            shipping: { ...prev.billing }
        }));
    };

    if (loading) {
        return (
            <div className="page">
                <div className="loading-state">
                    <div className="spinner"></div>
                    <p>Loading customer...</p>
                </div>
            </div>
        );
    }

    return (
        <div className="page customer-editor-page">
            <div className="page-container">
                {/* Header */}
                <div className="page-header">
                    <div className="page-title">
                        <button className="btn-back" onClick={() => navigate('/customers')}>
                            ← Back
                        </button>
                        <div>
                            <h1>{customerId ? 'Edit Customer' : 'Add New Customer'}</h1>
                            <p>{customerId ? `Update customer #${customerId}` : 'Create a new customer account'}</p>
                        </div>
                    </div>
                    <div className="page-actions">
                        <button
                            className="btn btn-secondary"
                            onClick={() => navigate('/customers')}
                        >
                            Cancel
                        </button>
                        <button
                            className="btn btn-primary"
                            onClick={handleSubmit}
                            disabled={saving}
                        >
                            {saving ? 'Saving...' : customerId ? 'Update Customer' : 'Create Customer'}
                        </button>
                    </div>
                </div>

                <form onSubmit={handleSubmit}>
                    <div className="editor-grid">
                        {/* Account Information */}
                        <div className="editor-section">
                            <div className="section-header">
                                <h3>Account Information</h3>
                            </div>
                            <div className="section-content">
                                <div className="form-row">
                                    <div className="form-group">
                                        <label>Username *</label>
                                        <input
                                            type="text"
                                            value={formData.username}
                                            onChange={(e) => handleChange('username', e.target.value)}
                                            disabled={!!customerId}
                                            required
                                        />
                                        {customerId && <small>Usernames cannot be changed</small>}
                                    </div>
                                    <div className="form-group">
                                        <label>Email *</label>
                                        <input
                                            type="email"
                                            value={formData.email}
                                            onChange={(e) => handleChange('email', e.target.value)}
                                            required
                                        />
                                    </div>
                                </div>

                                <div className="form-row">
                                    <div className="form-group">
                                        <label>First Name</label>
                                        <input
                                            type="text"
                                            value={formData.first_name}
                                            onChange={(e) => handleChange('first_name', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>Last Name</label>
                                        <input
                                            type="text"
                                            value={formData.last_name}
                                            onChange={(e) => handleChange('last_name', e.target.value)}
                                        />
                                    </div>
                                </div>

                                <div className="form-row">
                                    <div className="form-group">
                                        <label>Role</label>
                                        <select
                                            value={formData.role}
                                            onChange={(e) => handleChange('role', e.target.value)}
                                        >
                                            <option value="customer">Customer</option>
                                            <option value="shop_manager">Shop Manager</option>
                                            <option value="subscriber">Subscriber</option>
                                            <option value="contributor">Contributor</option>
                                            <option value="author">Author</option>
                                            <option value="editor">Editor</option>
                                            <option value="administrator">Administrator</option>
                                        </select>
                                    </div>
                                    <div className="form-group">
                                        <label>{customerId ? 'New Password (leave blank to keep current)' : 'Password *'}</label>
                                        <input
                                            type="password"
                                            value={formData.password}
                                            onChange={(e) => handleChange('password', e.target.value)}
                                            required={!customerId}
                                        />
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* Billing Address */}
                        <div className="editor-section">
                            <div className="section-header">
                                <h3>Billing Address</h3>
                            </div>
                            <div className="section-content">
                                <div className="form-row">
                                    <div className="form-group">
                                        <label>First Name</label>
                                        <input
                                            type="text"
                                            value={formData.billing.first_name}
                                            onChange={(e) => handleAddressChange('billing', 'first_name', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>Last Name</label>
                                        <input
                                            type="text"
                                            value={formData.billing.last_name}
                                            onChange={(e) => handleAddressChange('billing', 'last_name', e.target.value)}
                                        />
                                    </div>
                                </div>

                                <div className="form-group">
                                    <label>Company</label>
                                    <input
                                        type="text"
                                        value={formData.billing.company}
                                        onChange={(e) => handleAddressChange('billing', 'company', e.target.value)}
                                    />
                                </div>

                                <div className="form-group">
                                    <label>Address Line 1</label>
                                    <input
                                        type="text"
                                        value={formData.billing.address_1}
                                        onChange={(e) => handleAddressChange('billing', 'address_1', e.target.value)}
                                    />
                                </div>

                                <div className="form-group">
                                    <label>Address Line 2</label>
                                    <input
                                        type="text"
                                        value={formData.billing.address_2}
                                        onChange={(e) => handleAddressChange('billing', 'address_2', e.target.value)}
                                    />
                                </div>

                                <div className="form-row">
                                    <div className="form-group">
                                        <label>City</label>
                                        <input
                                            type="text"
                                            value={formData.billing.city}
                                            onChange={(e) => handleAddressChange('billing', 'city', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>State / County</label>
                                        <input
                                            type="text"
                                            value={formData.billing.state}
                                            onChange={(e) => handleAddressChange('billing', 'state', e.target.value)}
                                        />
                                    </div>
                                </div>

                                <div className="form-row">
                                    <div className="form-group">
                                        <label>Postcode / ZIP</label>
                                        <input
                                            type="text"
                                            value={formData.billing.postcode}
                                            onChange={(e) => handleAddressChange('billing', 'postcode', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>Country</label>
                                        <input
                                            type="text"
                                            value={formData.billing.country}
                                            onChange={(e) => handleAddressChange('billing', 'country', e.target.value)}
                                        />
                                    </div>
                                </div>

                                <div className="form-row">
                                    <div className="form-group">
                                        <label>Phone</label>
                                        <input
                                            type="tel"
                                            value={formData.billing.phone}
                                            onChange={(e) => handleAddressChange('billing', 'phone', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>Email</label>
                                        <input
                                            type="email"
                                            value={formData.billing.email}
                                            onChange={(e) => handleAddressChange('billing', 'email', e.target.value)}
                                        />
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* Shipping Address */}
                        <div className="editor-section">
                            <div className="section-header">
                                <h3>Shipping Address</h3>
                                <button
                                    type="button"
                                    className="btn btn-sm btn-secondary"
                                    onClick={copyBillingToShipping}
                                >
                                    Copy from Billing
                                </button>
                            </div>
                            <div className="section-content">
                                <div className="form-row">
                                    <div className="form-group">
                                        <label>First Name</label>
                                        <input
                                            type="text"
                                            value={formData.shipping.first_name}
                                            onChange={(e) => handleAddressChange('shipping', 'first_name', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>Last Name</label>
                                        <input
                                            type="text"
                                            value={formData.shipping.last_name}
                                            onChange={(e) => handleAddressChange('shipping', 'last_name', e.target.value)}
                                        />
                                    </div>
                                </div>

                                <div className="form-group">
                                    <label>Company</label>
                                    <input
                                        type="text"
                                        value={formData.shipping.company}
                                        onChange={(e) => handleAddressChange('shipping', 'company', e.target.value)}
                                    />
                                </div>

                                <div className="form-group">
                                    <label>Address Line 1</label>
                                    <input
                                        type="text"
                                        value={formData.shipping.address_1}
                                        onChange={(e) => handleAddressChange('shipping', 'address_1', e.target.value)}
                                    />
                                </div>

                                <div className="form-group">
                                    <label>Address Line 2</label>
                                    <input
                                        type="text"
                                        value={formData.shipping.address_2}
                                        onChange={(e) => handleAddressChange('shipping', 'address_2', e.target.value)}
                                    />
                                </div>

                                <div className="form-row">
                                    <div className="form-group">
                                        <label>City</label>
                                        <input
                                            type="text"
                                            value={formData.shipping.city}
                                            onChange={(e) => handleAddressChange('shipping', 'city', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>State / County</label>
                                        <input
                                            type="text"
                                            value={formData.shipping.state}
                                            onChange={(e) => handleAddressChange('shipping', 'state', e.target.value)}
                                        />
                                    </div>
                                </div>

                                <div className="form-row">
                                    <div className="form-group">
                                        <label>Postcode / ZIP</label>
                                        <input
                                            type="text"
                                            value={formData.shipping.postcode}
                                            onChange={(e) => handleAddressChange('shipping', 'postcode', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>Country</label>
                                        <input
                                            type="text"
                                            value={formData.shipping.country}
                                            onChange={(e) => handleAddressChange('shipping', 'country', e.target.value)}
                                        />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    );
};

export default Customers;
