import React, { useState, useEffect } from 'react';
import Toggle from './Toggle';

const WishlistSettings = ({ onBack }) => {
    const [activeTab, setActiveTab] = useState('settings');
    const [settings, setSettings] = useState({
        enable_wishlist: false,
        enable_floating_button: false,
        floating_button_position: 'bottom-right',
        show_on_shop_page: true,
        show_on_product_page: true,
        guest_wishlist_expiry: 30,
        wishlist_page_id: '',
        floating_button_style: 'circle',
        floating_button_color: '#e91e63',
        floating_button_text_color: '#ffffff',
        floating_button_size: 'medium',
        sidebar_width: 400,
        enable_quantity_controls: true,
        enable_total_calculation: true,
        show_product_images: true,
        redirect_after_add: false,
        auto_remove_after_cart: false,
        // Wishlist Button Settings
        wishlist_button_style: 'both', // 'icon', 'text', 'both'
        wishlist_button_shape: 'rounded', // 'rounded', 'square', 'circle'
        wishlist_button_color: '#e91e63',
        wishlist_button_text_color: '#ffffff',
        wishlist_button_border_color: '#e91e63',
        wishlist_button_text: 'Add to Wishlist',
        wishlist_button_text_remove: 'Remove from Wishlist'
    });
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);

    const tabs = [
        { id: 'settings', label: 'Settings', icon: 'fas fa-cog', description: 'Wishlist configuration' },
        { id: 'analytics', label: 'Analytics', icon: 'fas fa-chart-bar', description: 'Wishlist analytics (Coming Soon)' }
    ];

    const positionOptions = [
        { value: 'top-left', label: 'Top Left' },
        { value: 'top-right', label: 'Top Right' },
        { value: 'bottom-left', label: 'Bottom Left' },
        { value: 'bottom-right', label: 'Bottom Right' },
        { value: 'center-left', label: 'Center Left' },
        { value: 'center-right', label: 'Center Right' }
    ];

    const buttonStyles = [
        { value: 'circle', label: 'Circle' },
        { value: 'rounded', label: 'Rounded Rectangle' },
        { value: 'square', label: 'Square' }
    ];

    const buttonSizes = [
        { value: 'small', label: 'Small (40px)' },
        { value: 'medium', label: 'Medium (50px)' },
        { value: 'large', label: 'Large (60px)' }
    ];

    const wishlistButtonStyles = [
        { value: 'icon', label: 'Icon Only' },
        { value: 'text', label: 'Text Only' },
        { value: 'both', label: 'Icon + Text' }
    ];

    const wishlistButtonShapes = [
        { value: 'rounded', label: 'Rounded' },
        { value: 'square', label: 'Square' },
        { value: 'circle', label: 'Circle' }
    ];

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

    const loadSettings = async () => {
        setLoading(true);
        try {
            const response = await fetch(proddispAdmin.ajaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'proddisp_get_wishlist_settings',
                    nonce: proddispAdmin.nonce
                })
            });

            const data = await response.json();
            if (data.success) {
                setSettings(prev => ({
                    ...prev,
                    ...data.data
                }));
            }
        } catch (error) {
            console.error('Error loading wishlist settings:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleSettingChange = (key, value) => {
        setSettings(prev => ({
            ...prev,
            [key]: value
        }));
    };

    const handleSave = async () => {
        setSaving(true);
        try {
            const response = await fetch(proddispAdmin.ajaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'proddisp_save_wishlist_settings',
                    nonce: proddispAdmin.nonce,
                    settings: JSON.stringify(settings)
                })
            });

            const data = await response.json();
            if (data.success) {
                if (window.proddispToast) {
                    window.proddispToast.success('Wishlist settings saved successfully!');
                }
            } else {
                if (window.proddispToast) {
                    window.proddispToast.error(data.data?.message || 'Failed to save settings');
                }
            }
        } catch (error) {
            console.error('Error saving wishlist settings:', error);
            if (window.proddispToast) {
                window.proddispToast.error('Error saving settings. Please try again.');
            }
        } finally {
            setSaving(false);
        }
    };

    const renderSettingsTab = () => {
        return (
            <div className="wishlist-settings-content">
                {/* Basic Wishlist Settings */}
                <div className="setting-section">
                    <h3 className="section-title">
                        <i className="fas fa-heart"></i>
                        Basic Wishlist Settings
                    </h3>
                    
                    <div className="setting-group">
                        <Toggle
                            id="enable-wishlist"
                            checked={settings.enable_wishlist}
                            onChange={(e) => handleSettingChange('enable_wishlist', e.target.checked)}
                            label="Enable Product Wishlist"
                            description="Enable wishlist functionality on your shop and product pages"
                        />
                    </div>

                    <div className="setting-group">
                        <label htmlFor="guest-expiry">Guest Wishlist Expiry (days)</label>
                        <input
                            id="guest-expiry"
                            type="number"
                            value={settings.guest_wishlist_expiry}
                            onChange={(e) => handleSettingChange('guest_wishlist_expiry', parseInt(e.target.value))}
                            className="regular-text"
                            min="1"
                            max="365"
                        />
                        <p className="description">How many days to keep guest user wishlist items before auto-cleanup</p>
                    </div>
                </div>

                {/* Floating Button Settings */}
                <div className="setting-section">
                    <h3 className="section-title">
                        <i className="fas fa-mouse-pointer"></i>
                        Floating Wishlist Button
                    </h3>
                    
                    <div className="setting-group">
                        <Toggle
                            id="enable-floating-button"
                            checked={settings.enable_floating_button}
                            onChange={(e) => handleSettingChange('enable_floating_button', e.target.checked)}
                            label="Enable Floating Wishlist Button"
                            description="Show a floating button that opens the wishlist sidebar"
                        />
                    </div>

                    {settings.enable_floating_button && (
                        <>
                            <div className="setting-group">
                                <label htmlFor="button-position">Button Position</label>
                                <select
                                    id="button-position"
                                    value={settings.floating_button_position}
                                    onChange={(e) => handleSettingChange('floating_button_position', e.target.value)}
                                    className="regular-text"
                                >
                                    {positionOptions.map(option => (
                                        <option key={option.value} value={option.value}>
                                            {option.label}
                                        </option>
                                    ))}
                                </select>
                            </div>

                            <div className="setting-group">
                                <label htmlFor="button-style">Button Style</label>
                                <select
                                    id="button-style"
                                    value={settings.floating_button_style}
                                    onChange={(e) => handleSettingChange('floating_button_style', e.target.value)}
                                    className="regular-text"
                                >
                                    {buttonStyles.map(style => (
                                        <option key={style.value} value={style.value}>
                                            {style.label}
                                        </option>
                                    ))}
                                </select>
                            </div>

                            <div className="setting-group">
                                <label htmlFor="button-size">Button Size</label>
                                <select
                                    id="button-size"
                                    value={settings.floating_button_size}
                                    onChange={(e) => handleSettingChange('floating_button_size', e.target.value)}
                                    className="regular-text"
                                >
                                    {buttonSizes.map(size => (
                                        <option key={size.value} value={size.value}>
                                            {size.label}
                                        </option>
                                    ))}
                                </select>
                            </div>

                            <div className="setting-row">
                                <div className="setting-group">
                                    <label htmlFor="button-color">Button Color</label>
                                    <input
                                        id="button-color"
                                        type="color"
                                        value={settings.floating_button_color}
                                        onChange={(e) => handleSettingChange('floating_button_color', e.target.value)}
                                        className="color-picker"
                                    />
                                </div>

                                <div className="setting-group">
                                    <label htmlFor="button-text-color">Text Color</label>
                                    <input
                                        id="button-text-color"
                                        type="color"
                                        value={settings.floating_button_text_color}
                                        onChange={(e) => handleSettingChange('floating_button_text_color', e.target.value)}
                                        className="color-picker"
                                    />
                                </div>
                            </div>
                        </>
                    )}
                </div>

                {/* Display Settings */}
                <div className="setting-section">
                    <h3 className="section-title">
                        <i className="fas fa-eye"></i>
                        Display Settings
                    </h3>
                    
                    <div className="setting-group">
                        <Toggle
                            id="show-on-shop"
                            checked={settings.show_on_shop_page}
                            onChange={(e) => handleSettingChange('show_on_shop_page', e.target.checked)}
                            label="Show on Shop Page"
                            description="Display wishlist buttons on shop/archive pages"
                        />
                    </div>

                    <div className="setting-group">
                        <Toggle
                            id="show-on-product"
                            checked={settings.show_on_product_page}
                            onChange={(e) => handleSettingChange('show_on_product_page', e.target.checked)}
                            label="Show on Product Page"
                            description="Display wishlist buttons on single product pages"
                        />
                    </div>
                </div>

                {/* Wishlist Button Settings */}
                <div className="setting-section">
                    <h3 className="section-title">
                        <i className="fas fa-heart"></i>
                        Wishlist Button Design
                    </h3>
                    
                    <div className="setting-group">
                        <label htmlFor="wishlist-button-style">Button Content</label>
                        <select
                            id="wishlist-button-style"
                            value={settings.wishlist_button_style}
                            onChange={(e) => handleSettingChange('wishlist_button_style', e.target.value)}
                            className="regular-text"
                        >
                            {wishlistButtonStyles.map(style => (
                                <option key={style.value} value={style.value}>
                                    {style.label}
                                </option>
                            ))}
                        </select>
                        <p className="description">Choose what to display on wishlist buttons</p>
                    </div>

                    <div className="setting-group">
                        <label htmlFor="wishlist-button-shape">Button Shape</label>
                        <select
                            id="wishlist-button-shape"
                            value={settings.wishlist_button_shape}
                            onChange={(e) => handleSettingChange('wishlist_button_shape', e.target.value)}
                            className="regular-text"
                        >
                            {wishlistButtonShapes.map(shape => (
                                <option key={shape.value} value={shape.value}>
                                    {shape.label}
                                </option>
                            ))}
                        </select>
                    </div>

                    <div className="setting-row">
                        <div className="setting-group">
                            <label htmlFor="wishlist-button-color">Button Color</label>
                            <input
                                id="wishlist-button-color"
                                type="color"
                                value={settings.wishlist_button_color}
                                onChange={(e) => handleSettingChange('wishlist_button_color', e.target.value)}
                                className="color-picker"
                            />
                        </div>

                        <div className="setting-group">
                            <label htmlFor="wishlist-button-text-color">Text Color</label>
                            <input
                                id="wishlist-button-text-color"
                                type="color"
                                value={settings.wishlist_button_text_color}
                                onChange={(e) => handleSettingChange('wishlist_button_text_color', e.target.value)}
                                className="color-picker"
                            />
                        </div>
                    </div>

                    <div className="setting-group">
                        <label htmlFor="wishlist-button-border-color">Border Color</label>
                        <input
                            id="wishlist-button-border-color"
                            type="color"
                            value={settings.wishlist_button_border_color}
                            onChange={(e) => handleSettingChange('wishlist_button_border_color', e.target.value)}
                            className="color-picker"
                        />
                    </div>

                    {settings.wishlist_button_style !== 'icon' && (
                        <>
                            <div className="setting-group">
                                <label htmlFor="wishlist-button-text">Add to Wishlist Text</label>
                                <input
                                    id="wishlist-button-text"
                                    type="text"
                                    value={settings.wishlist_button_text}
                                    onChange={(e) => handleSettingChange('wishlist_button_text', e.target.value)}
                                    className="regular-text"
                                    placeholder="Add to Wishlist"
                                />
                            </div>

                            <div className="setting-group">
                                <label htmlFor="wishlist-button-text-remove">Remove from Wishlist Text</label>
                                <input
                                    id="wishlist-button-text-remove"
                                    type="text"
                                    value={settings.wishlist_button_text_remove}
                                    onChange={(e) => handleSettingChange('wishlist_button_text_remove', e.target.value)}
                                    className="regular-text"
                                    placeholder="Remove from Wishlist"
                                />
                            </div>
                        </>
                    )}
                </div>

                {/* Sidebar Settings */}
                <div className="setting-section">
                    <h3 className="section-title">
                        <i className="fas fa-sidebar"></i>
                        Wishlist Sidebar Settings
                    </h3>
                    
                    <div className="setting-group">
                        <label htmlFor="sidebar-width">Sidebar Width (px)</label>
                        <input
                            id="sidebar-width"
                            type="number"
                            value={settings.sidebar_width}
                            onChange={(e) => handleSettingChange('sidebar_width', parseInt(e.target.value))}
                            className="regular-text"
                            min="300"
                            max="600"
                        />
                        <p className="description">Width of the wishlist sidebar (300-600px)</p>
                    </div>

                    <div className="setting-group">
                        <Toggle
                            id="enable-quantity-controls"
                            checked={settings.enable_quantity_controls}
                            onChange={(e) => handleSettingChange('enable_quantity_controls', e.target.checked)}
                            label="Enable Quantity Controls"
                            description="Show increment/decrement buttons for product quantities"
                        />
                    </div>

                    <div className="setting-group">
                        <Toggle
                            id="enable-total-calculation"
                            checked={settings.enable_total_calculation}
                            onChange={(e) => handleSettingChange('enable_total_calculation', e.target.checked)}
                            label="Enable Total Calculation"
                            description="Show total price calculation based on quantities"
                        />
                    </div>

                    <div className="setting-group">
                        <Toggle
                            id="show-product-images"
                            checked={settings.show_product_images}
                            onChange={(e) => handleSettingChange('show_product_images', e.target.checked)}
                            label="Show Product Images"
                            description="Display product thumbnails in the sidebar"
                        />
                    </div>
                </div>

                {/* Advanced Settings */}
                <div className="setting-section">
                    <h3 className="section-title">
                        <i className="fas fa-cogs"></i>
                        Advanced Settings
                    </h3>
                    
                    <div className="setting-group">
                        <Toggle
                            id="redirect-after-add"
                            checked={settings.redirect_after_add}
                            onChange={(e) => handleSettingChange('redirect_after_add', e.target.checked)}
                            label="Redirect After Add to Wishlist"
                            description="Redirect to wishlist page after adding a product"
                        />
                    </div>

                    <div className="setting-group">
                        <Toggle
                            id="auto-remove-after-cart"
                            checked={settings.auto_remove_after_cart}
                            onChange={(e) => handleSettingChange('auto_remove_after_cart', e.target.checked)}
                            label="Auto Remove After Add to Cart"
                            description="Automatically remove items from wishlist when added to cart"
                        />
                    </div>
                </div>

                {/* Shortcode Information */}
                <div className="setting-section">
                    <h3 className="section-title">
                        <i className="fas fa-code"></i>
                        Shortcode Usage
                    </h3>
                    
                    <div className="shortcode-info">
                        <div className="shortcode-item">
                            <h4>Display Wishlist Page</h4>
                            <code>[product_wishlist]</code>
                            <p>Use this shortcode to display the wishlist on any page</p>
                        </div>
                        
                        <div className="shortcode-item">
                            <h4>Custom Wishlist Title</h4>
                            <code>[product_wishlist title="My Favorites"]</code>
                            <p>Display wishlist with a custom title</p>
                        </div>
                    </div>
                </div>
            </div>
        );
    };

    const renderAnalyticsTab = () => {
        return (
            <div className="wishlist-analytics-content">
                <div className="coming-soon-container">
                    <div className="coming-soon-icon">
                        <i className="fas fa-chart-line"></i>
                    </div>
                    <h3>Analytics Coming Soon</h3>
                    <p>Wishlist analytics and insights will be available in a future update.</p>
                    <div className="planned-features">
                        <h4>Planned Features:</h4>
                        <ul>
                            <li>Most wishlisted products</li>
                            <li>Wishlist conversion rates</li>
                            <li>User engagement metrics</li>
                            <li>Popular wishlist items</li>
                            <li>Wishlist abandonment tracking</li>
                        </ul>
                    </div>
                </div>
            </div>
        );
    };

    if (loading) {
        return (
            <div className="proddisp-loading-container">
                <div className="proddisp-loading">
                    <div className="loading-spinner">
                        <div className="spinner-ring"></div>
                    </div>
                    <h3>Loading wishlist settings...</h3>
                </div>
            </div>
        );
    }

    return (
        <div className="proddisp-wishlist-settings">
            {/* Header */}
            <div className="proddisp-editor-header">
                <div className="proddisp-header-left">
                    <button
                        className="button back-button"
                        onClick={onBack}
                    >
                        <i className="fas fa-arrow-left"></i>
                        Back
                    </button>
                    <div className="proddisp-page-info">
                        <h1>
                            <i className="fas fa-heart"></i>
                            Wishlist Settings
                        </h1>
                        <p>Configure wishlist functionality and appearance</p>
                    </div>
                </div>
                <div className="proddisp-header-right">
                    <button
                        className={`button button-primary save-button ${saving ? 'loading' : ''}`}
                        onClick={handleSave}
                        disabled={saving}
                    >
                        {saving ? (
                            <>
                                <i className="fas fa-spinner fa-spin"></i>
                                Saving...
                            </>
                        ) : (
                            <>
                                <i className="fas fa-save"></i>
                                Save Settings
                            </>
                        )}
                    </button>
                </div>
            </div>

            {/* Content */}
            <div className="proddisp-editor-content">
                <div className="proddisp-editor-sidebar">
                    <div className="proddisp-tabs">
                        {tabs.map(tab => (
                            <button
                                key={tab.id}
                                className={`proddisp-tab ${activeTab === tab.id ? 'active' : ''}`}
                                onClick={() => setActiveTab(tab.id)}
                                title={tab.description}
                            >
                                <i className={`tab-icon ${tab.icon}`}></i>
                                <span className="tab-label">{tab.label}</span>
                            </button>
                        ))}
                    </div>
                    <div className="proddisp-tab-content">
                        {activeTab === 'settings' && renderSettingsTab()}
                        {activeTab === 'analytics' && renderAnalyticsTab()}
                    </div>
                </div>

                {/* Preview Panel */}
                <div className="proddisp-editor-preview">
                    <div className="wishlist-preview-container">
                        <h3>Wishlist Preview</h3>
                        <div className="preview-info">
                            <p>This preview shows how your wishlist settings will appear to users.</p>
                            
                            {settings.enable_floating_button && (
                                <div className="floating-button-preview">
                                    <h4>Floating Button Preview</h4>
                                    <div 
                                        className={`floating-button-demo ${settings.floating_button_style} ${settings.floating_button_size}`}
                                        style={{
                                            backgroundColor: settings.floating_button_color,
                                            color: settings.floating_button_text_color
                                        }}
                                    >
                                        <i className="fas fa-heart"></i>
                                        <span className="button-count">3</span>
                                    </div>
                                    <p>Position: {positionOptions.find(p => p.value === settings.floating_button_position)?.label}</p>
                                </div>
                            )}

                            {settings.enable_wishlist && (
                                <div className="wishlist-button-preview">
                                    <h4>Wishlist Button Preview</h4>
                                    <div className="button-preview-container">
                                        <div className="button-preview-item">
                                            <span className="preview-label">Shop Page Button:</span>
                                            <div 
                                                className={`proddisp-wishlist-button loop-style ${settings.wishlist_button_shape}`}
                                                style={{
                                                    backgroundColor: 'transparent',
                                                    color: settings.wishlist_button_color,
                                                    borderColor: settings.wishlist_button_border_color
                                                }}
                                            >
                                                {(settings.wishlist_button_style === 'icon' || settings.wishlist_button_style === 'both') && (
                                                    <span className="proddisp-icon-heart">♡</span>
                                                )}
                                                {(settings.wishlist_button_style === 'text' || settings.wishlist_button_style === 'both') && (
                                                    <span className="proddisp-button-text">{settings.wishlist_button_text}</span>
                                                )}
                                            </div>
                                        </div>
                                        <div className="button-preview-item">
                                            <span className="preview-label">Product Page Button:</span>
                                            <div 
                                                className={`proddisp-wishlist-button single-style ${settings.wishlist_button_shape}`}
                                                style={{
                                                    backgroundColor: 'transparent',
                                                    color: settings.wishlist_button_color,
                                                    borderColor: settings.wishlist_button_border_color
                                                }}
                                            >
                                                {(settings.wishlist_button_style === 'icon' || settings.wishlist_button_style === 'both') && (
                                                    <span className="proddisp-icon-heart">♡</span>
                                                )}
                                                {(settings.wishlist_button_style === 'text' || settings.wishlist_button_style === 'both') && (
                                                    <span className="proddisp-button-text">{settings.wishlist_button_text}</span>
                                                )}
                                            </div>
                                        </div>
                                        <div className="button-preview-item">
                                            <span className="preview-label">In Wishlist:</span>
                                            <div 
                                                className={`proddisp-wishlist-button in-wishlist ${settings.wishlist_button_shape}`}
                                                style={{
                                                    backgroundColor: settings.wishlist_button_color,
                                                    color: settings.wishlist_button_text_color,
                                                    borderColor: settings.wishlist_button_color
                                                }}
                                            >
                                                {(settings.wishlist_button_style === 'icon' || settings.wishlist_button_style === 'both') && (
                                                    <span className="proddisp-icon-heart">♥</span>
                                                )}
                                                {(settings.wishlist_button_style === 'text' || settings.wishlist_button_style === 'both') && (
                                                    <span className="proddisp-button-text">{settings.wishlist_button_text_remove}</span>
                                                )}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            )}

                            <div className="settings-summary">
                                <h4>Current Settings</h4>
                                <ul>
                                    <li>Wishlist: {settings.enable_wishlist ? 'Enabled' : 'Disabled'}</li>
                                    <li>Floating Button: {settings.enable_floating_button ? 'Enabled' : 'Disabled'}</li>
                                    <li>Shop Page: {settings.show_on_shop_page ? 'Enabled' : 'Disabled'}</li>
                                    <li>Product Page: {settings.show_on_product_page ? 'Enabled' : 'Disabled'}</li>
                                    <li>Guest Expiry: {settings.guest_wishlist_expiry} days</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default WishlistSettings;