import React, { useState, useEffect } from 'react';
import api from '../utils/api';
import { useToast } from '../App';

const ProductSyncSettings = ({ products }) => {
    const { showSuccess, showError } = useToast();
    const [syncFields, setSyncFields] = useState({});
    const [loadingFields, setLoadingFields] = useState(false);
    const [savingFields, setSavingFields] = useState(false);
    const [syncingAll, setSyncingAll] = useState(false);

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

    const loadSyncFields = async () => {
        try {
            setLoadingFields(true);
            const response = await api.getProductSyncFields();
            console.log('Product Sync Fields Response:', response);
            if (response.success) {
                console.log('Fields loaded:', response.fields);
                setSyncFields(response.fields);
            } else {
                showError('Failed to load product sync fields');
            }
        } catch (err) {
            console.error('Error loading product sync fields:', err);
            showError('Error loading fields: ' + err.message);
        } finally {
            setLoadingFields(false);
        }
    };

    const handleFieldToggle = (fieldKey, enabled) => {
        if (fieldKey === 'product_id') return; // Product 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.updateProductSyncFields(fieldSettings);
            if (response.success) {
                showSuccess('Product sync fields updated successfully');

                // Now sync all products
                await syncAllProductsNow();
            } else {
                showError('Failed to update fields: ' + response.message);
            }
        } catch (err) {
            showError('Error saving fields: ' + err.message);
        } finally {
            setSavingFields(false);
        }
    };

    const syncAllProductsNow = 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?.products?.tabName || 'Products';

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

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

            if (response.success) {
                showSuccess(response.message || 'Products synced successfully');
            } else {
                showError('Sync failed: ' + response.message);
            }
        } catch (err) {
            showError('Sync error: ' + err.message);
        } finally {
            setSyncingAll(false);
        }
    };

    return (
        <div className="sync-settings-container">
            <div className="card">
                <div className="card-header">
                    <h3>📊 Product Export Configuration</h3>
                    <p>Configure which product 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 products to Google Sheets.
                                    Changes are saved automatically and will apply to all future syncs.
                                </p>

                                <div className="fields-grid">
                                    {Object.keys(syncFields).length === 0 ? (
                                        <div className="empty-state">
                                            <p>No sync fields available. Please check your configuration.</p>
                                        </div>
                                    ) : (
                                        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 === 'product_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 === 'product_id'} // Product 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 Products'
                                        )}
                                    </button>

                                    <button
                                        className={`btn btn-success btn-lg ${syncingAll ? 'btn-loading' : ''}`}
                                        onClick={syncAllProductsNow}
                                        disabled={syncingAll}
                                    >
                                        {syncingAll ? (
                                            <>
                                                <div className="spinner"></div>
                                                Syncing All Products...
                                            </>
                                        ) : (
                                            '🚀 Export All Products 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 === 'product_id' ? '12345' :
                                                        key === 'product_name' ? 'Sample Product' :
                                                            key === 'sku' ? 'SKU-001' :
                                                                key === 'regular_price' ? '$99.99' :
                                                                    key === 'stock_quantity' ? '50' :
                                                                        key === 'stock_status' ? 'In Stock' :
                                                                            '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 Products:</span>
                                        <span className="status-value">{products.length}</span>
                                    </div>
                                </div>
                            </div>
                        </>
                    )}
                </div>
            </div>
        </div>
    );
};

export default ProductSyncSettings;
