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

const ProductSyncConfig = ({ onClose, onSuccess }) => {
    const { showSuccess, showError } = useToast();
    const [loading, setLoading] = useState(false);
    const [saving, setSaving] = useState(false);
    const [syncing, setSyncing] = useState(false);
    const [fields, setFields] = useState({});
    const [spreadsheetUrl, setSpreadsheetUrl] = useState('');
    const [sheetName, setSheetName] = useState('Products');

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

    const loadFields = async () => {
        try {
            setLoading(true);
            const response = await api.getProductSyncFields();
            if (response.success) {
                setFields(response.fields);
            } else {
                showError('Failed to load product sync fields');
            }
        } catch (err) {
            showError('Error loading fields: ' + err.message);
        } finally {
            setLoading(false);
        }
    };

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

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

    const saveFieldSettings = async () => {
        try {
            setSaving(true);

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

            const response = await api.updateProductSyncFields(fieldSettings);
            if (response.success) {
                showSuccess('Product sync fields updated successfully');
            } else {
                showError('Failed to update fields: ' + response.message);
            }
        } catch (err) {
            showError('Error saving fields: ' + err.message);
        } finally {
            setSaving(false);
        }
    };

    const syncAllProducts = async () => {
        if (!spreadsheetUrl.trim()) {
            showError('Please enter a Google Sheets URL');
            return;
        }

        try {
            setSyncing(true);
            const response = await api.syncAllProducts(spreadsheetUrl, sheetName);

            if (response.success) {
                showSuccess(response.message);
                if (onSuccess) onSuccess();
            } else {
                showError('Sync failed: ' + response.message);
            }
        } catch (err) {
            showError('Sync error: ' + err.message);
        } finally {
            setSyncing(false);
        }
    };

    const getEnabledFieldsCount = () => {
        return Object.values(fields).filter(field => field.enabled).length;
    };

    if (loading) {
        return (
            <div className="product-sync-config">
                <div className="loading-center">
                    <div className="spinner"></div>
                    <p>Loading product export configuration...</p>
                </div>
            </div>
        );
    }

    return (
        <div className="product-sync-config">
            <div className="modal-overlay" onClick={onClose}>
                <div className="modal-content" onClick={e => e.stopPropagation()}>
                    <div className="modal-header">
                        <h2>📦 Product Export Configuration</h2>
                        <button className="modal-close" onClick={onClose}>×</button>
                    </div>

                    <div className="modal-body">
                        {/* Field Configuration */}
                        <div className="config-section">
                            <h3>Select Fields to Export</h3>
                            <p className="section-description">
                                Choose which product fields you want to sync to Google Sheets.
                                You can rearrange these fields in your spreadsheet later.
                            </p>

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

                            <div className="fields-summary">
                                <strong>{getEnabledFieldsCount()} fields selected</strong>
                            </div>

                            <div className="config-actions">
                                <button
                                    className={`btn btn-primary ${saving ? 'btn-loading' : ''}`}
                                    onClick={saveFieldSettings}
                                    disabled={saving}
                                >
                                    {saving ? (
                                        <>
                                            <div className="spinner"></div>
                                            Saving...
                                        </>
                                    ) : (
                                        '💾 Save Field Settings'
                                    )}
                                </button>
                            </div>
                        </div>

                        {/* Export Configuration */}
                        <div className="config-section">
                            <h3>Export to Google Sheets</h3>
                            <p className="section-description">
                                Export your WooCommerce products to a Google Sheets spreadsheet.
                            </p>

                            <div className="sync-form">
                                <div className="form-group">
                                    <label htmlFor="spreadsheet-url">Google Sheets URL</label>
                                    <input
                                        id="spreadsheet-url"
                                        type="url"
                                        value={spreadsheetUrl}
                                        onChange={(e) => setSpreadsheetUrl(e.target.value)}
                                        placeholder="https://docs.google.com/spreadsheets/d/..."
                                        className="form-control"
                                    />
                                    <small className="form-help">
                                        Copy the URL from your Google Sheets browser address bar
                                    </small>
                                </div>

                                <div className="form-group">
                                    <label htmlFor="sheet-name">Sheet Tab Name</label>
                                    <input
                                        id="sheet-name"
                                        type="text"
                                        value={sheetName}
                                        onChange={(e) => setSheetName(e.target.value)}
                                        placeholder="Products"
                                        className="form-control"
                                    />
                                    <small className="form-help">
                                        Name of the sheet tab where products will be synced
                                    </small>
                                </div>

                                <div className="sync-actions">
                                    <button
                                        className={`btn btn-success btn-lg ${syncing ? 'btn-loading' : ''}`}
                                        onClick={syncAllProducts}
                                        disabled={syncing || !spreadsheetUrl.trim()}
                                    >
                                        {syncing ? (
                                            <>
                                                <div className="spinner"></div>
                                                Syncing Products...
                                            </>
                                        ) : (
                                            '🚀 Export All Products'
                                        )}
                                    </button>
                                </div>
                            </div>
                        </div>

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

                            <div className="preview-table">
                                <div className="preview-header">
                                    {Object.entries(fields)
                                        .filter(([, field]) => field.enabled)
                                        .map(([key, field]) => (
                                            <div key={key} className="preview-column">
                                                {field.label}
                                            </div>
                                        ))
                                    }
                                </div>
                                <div className="preview-row">
                                    {Object.entries(fields)
                                        .filter(([, field]) => field.enabled)
                                        .map(([key]) => (
                                            <div key={key} className="preview-cell">
                                                Sample data...
                                            </div>
                                        ))
                                    }
                                </div>
                            </div>
                        </div>
                    </div>

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

export default ProductSyncConfig;
