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

const QuickActions = () => {
    const { showSuccess, showError } = useToast();
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [showOrdersModal, setShowOrdersModal] = useState(false);

    const [frontendSettings, setFrontendSettings] = useState({
        orders_management: {
            enabled: false,
            default_statuses: {},
            custom_statuses: {},
            filter_settings: {},
            filter_sections: {}
        },
        products_management: {
            enabled: false
        },
        customer_management: {
            enabled: false
        }
    });

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

    const loadFrontendSettings = async () => {
        try {
            setLoading(true);
            const response = await api.getFrontendSettings();
            if (response.success) {
                setFrontendSettings(response.settings);
            }
        } catch (err) {
            console.error('Failed to load frontend settings:', err);
        } finally {
            setLoading(false);
        }
    };

    const handleToggle = async (module, value) => {
        try {
            setSaving(true);
            const updatedSettings = {
                ...frontendSettings,
                [module]: {
                    ...frontendSettings[module],
                    enabled: value
                }
            };

            const response = await api.saveFrontendSettings(updatedSettings);
            
            if (response.success) {
                setFrontendSettings(updatedSettings);
                showSuccess(`${module === 'orders_management' ? 'Orders' : 'Products'} Management ${value ? 'enabled' : 'disabled'} on frontend`);
            } else {
                throw new Error(response.message || 'Failed to save settings');
            }
        } catch (err) {
            showError(err.message);
        } finally {
            setSaving(false);
        }
    };

    const OrdersSettingsModal = () => {
        const [modalSettings, setModalSettings] = useState(frontendSettings.orders_management);

        const handleSave = async () => {
            try {
                setSaving(true);
                const updatedSettings = {
                    ...frontendSettings,
                    orders_management: modalSettings
                };

                const response = await api.saveFrontendSettings(updatedSettings);
                
                if (response.success) {
                    setFrontendSettings(updatedSettings);
                    setShowOrdersModal(false);
                    showSuccess('Orders settings saved successfully');
                } else {
                    throw new Error(response.message || 'Failed to save settings');
                }
            } catch (err) {
                showError(err.message);
            } finally {
                setSaving(false);
            }
        };

        return (
            <div className="modal-overlay" onClick={() => setShowOrdersModal(false)}>
                <div className="modal-content" onClick={(e) => e.stopPropagation()}>
                    <div className="modal-header">
                        <h2>Orders Management Settings</h2>
                        <button className="close-btn" onClick={() => setShowOrdersModal(false)}>×</button>
                    </div>
                    <div className="modal-body">
                        <div className="settings-section">
                            <h3>Default Statuses</h3>
                            <p className="description">Configure which default order statuses to show on frontend</p>
                            {/* Add status checkboxes here */}
                        </div>

                        <div className="settings-section">
                            <h3>Custom Statuses</h3>
                            <p className="description">Configure custom order statuses</p>
                            {/* Add custom status configuration here */}
                        </div>

                        <div className="settings-section">
                            <h3>Filter Settings</h3>
                            <p className="description">Configure order filters</p>
                            {/* Add filter settings here */}
                        </div>

                        <div className="settings-section">
                            <h3>Filter Sections</h3>
                            <p className="description">Configure which filter sections to display</p>
                            {/* Add filter sections here */}
                        </div>
                    </div>
                    <div className="modal-footer">
                        <button className="btn btn-secondary" onClick={() => setShowOrdersModal(false)}>
                            Cancel
                        </button>
                        <button className="btn btn-primary" onClick={handleSave} disabled={saving}>
                            {saving ? 'Saving...' : 'Save Settings'}
                        </button>
                    </div>
                </div>
            </div>
        );
    };

    if (loading) {
        return <div className="loading">Loading Quick Actions...</div>;
    }

    return (
        <div className="quick-actions-container">
            <h2>Quick Actions</h2>
            <p className="description">Control what features are available on the frontend dashboard</p>

            <div className="quick-actions-grid">
                {/* Orders Management */}
                <div className="quick-action-card">
                    <div className="card-header">
                        <div className="card-icon">📦</div>
                        <h3>Orders Management</h3>
                    </div>
                    <p className="card-description">
                        Enable order management on the frontend dashboard with full functionality
                    </p>
                    <div className="card-controls">
                        <label className="toggle-switch">
                            <input
                                type="checkbox"
                                checked={frontendSettings.orders_management.enabled}
                                onChange={(e) => handleToggle('orders_management', e.target.checked)}
                                disabled={saving}
                            />
                            <span className="toggle-slider"></span>
                        </label>
                        <span className="toggle-label">
                            {frontendSettings.orders_management.enabled ? 'Enabled' : 'Disabled'}
                        </span>
                        {frontendSettings.orders_management.enabled && (
                            <button 
                                className="btn btn-icon" 
                                onClick={() => setShowOrdersModal(true)}
                                title="Configure Orders Settings"
                            >
                                ⚙️
                            </button>
                        )}
                    </div>
                </div>

                {/* Products Management */}
                <div className="quick-action-card">
                    <div className="card-header">
                        <div className="card-icon">🛍️</div>
                        <h3>Products Management</h3>
                    </div>
                    <p className="card-description">
                        Enable product management on the frontend dashboard
                    </p>
                    <div className="card-controls">
                        <label className="toggle-switch">
                            <input
                                type="checkbox"
                                checked={frontendSettings.products_management.enabled}
                                onChange={(e) => handleToggle('products_management', e.target.checked)}
                                disabled={saving}
                            />
                            <span className="toggle-slider"></span>
                        </label>
                        <span className="toggle-label">
                            {frontendSettings.products_management.enabled ? 'Enabled' : 'Disabled'}
                        </span>
                    </div>
                </div>

                {/* Customer Management */}
                <div className="quick-action-card">
                    <div className="card-header">
                        <div className="card-icon">👥</div>
                        <h3>Customer Management</h3>
                    </div>
                    <p className="card-description">
                        Manage customers, track activity, and handle user accounts
                    </p>
                    <div className="card-controls">
                        <label className="toggle-switch">
                            <input
                                type="checkbox"
                                checked={frontendSettings.customer_management?.enabled || false}
                                onChange={(e) => handleToggle('customer_management', e.target.checked)}
                                disabled={saving}
                            />
                            <span className="toggle-slider"></span>
                        </label>
                        <span className="toggle-label">
                            {frontendSettings.customer_management?.enabled ? 'Enabled' : 'Disabled'}
                        </span>
                    </div>
                </div>
            </div>

            {showOrdersModal && <OrdersSettingsModal />}

            <style jsx>{`
                .quick-actions-container {
                    padding: 20px;
                }

                .quick-actions-grid {
                    display: grid;
                    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
                    gap: 20px;
                    margin-top: 20px;
                }

                .quick-action-card {
                    background: white;
                    border: 1px solid #e0e0e0;
                    border-radius: 8px;
                    padding: 20px;
                    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
                }

                .card-header {
                    display: flex;
                    align-items: center;
                    gap: 12px;
                    margin-bottom: 12px;
                }

                .card-icon {
                    font-size: 32px;
                }

                .card-header h3 {
                    margin: 0;
                    font-size: 18px;
                    font-weight: 600;
                }

                .card-description {
                    color: #666;
                    font-size: 14px;
                    margin-bottom: 16px;
                }

                .card-controls {
                    display: flex;
                    align-items: center;
                    gap: 12px;
                }

                .toggle-switch {
                    position: relative;
                    display: inline-block;
                    width: 50px;
                    height: 24px;
                }

                .toggle-switch input {
                    opacity: 0;
                    width: 0;
                    height: 0;
                }

                .toggle-slider {
                    position: absolute;
                    cursor: pointer;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    background-color: #ccc;
                    transition: 0.4s;
                    border-radius: 24px;
                }

                .toggle-slider:before {
                    position: absolute;
                    content: "";
                    height: 18px;
                    width: 18px;
                    left: 3px;
                    bottom: 3px;
                    background-color: white;
                    transition: 0.4s;
                    border-radius: 50%;
                }

                input:checked + .toggle-slider {
                    background-color: #2196F3;
                }

                input:checked + .toggle-slider:before {
                    transform: translateX(26px);
                }

                input:disabled + .toggle-slider {
                    opacity: 0.5;
                    cursor: not-allowed;
                }

                .toggle-label {
                    font-size: 14px;
                    font-weight: 500;
                }

                .btn-icon {
                    background: #f5f5f5;
                    border: 1px solid #ddd;
                    border-radius: 4px;
                    padding: 6px 12px;
                    cursor: pointer;
                    font-size: 16px;
                }

                .btn-icon:hover {
                    background: #e0e0e0;
                }

                .modal-overlay {
                    position: fixed;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    background: rgba(0,0,0,0.5);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    z-index: 1000;
                }

                .modal-content {
                    background: white;
                    border-radius: 8px;
                    width: 90%;
                    max-width: 600px;
                    max-height: 80vh;
                    overflow: auto;
                }

                .modal-header {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    padding: 20px;
                    border-bottom: 1px solid #e0e0e0;
                }

                .modal-header h2 {
                    margin: 0;
                    font-size: 20px;
                }

                .close-btn {
                    background: none;
                    border: none;
                    font-size: 28px;
                    cursor: pointer;
                    color: #666;
                }

                .modal-body {
                    padding: 20px;
                }

                .settings-section {
                    margin-bottom: 24px;
                }

                .settings-section h3 {
                    font-size: 16px;
                    margin-bottom: 8px;
                }

                .settings-section .description {
                    color: #666;
                    font-size: 14px;
                    margin-bottom: 12px;
                }

                .modal-footer {
                    display: flex;
                    justify-content: flex-end;
                    gap: 12px;
                    padding: 20px;
                    border-top: 1px solid #e0e0e0;
                }

                .btn {
                    padding: 8px 16px;
                    border-radius: 4px;
                    border: none;
                    cursor: pointer;
                    font-size: 14px;
                    font-weight: 500;
                }

                .btn-primary {
                    background: #2196F3;
                    color: white;
                }

                .btn-primary:hover {
                    background: #1976D2;
                }

                .btn-primary:disabled {
                    opacity: 0.5;
                    cursor: not-allowed;
                }

                .btn-secondary {
                    background: #f5f5f5;
                    color: #333;
                }

                .btn-secondary:hover {
                    background: #e0e0e0;
                }
            `}</style>
        </div>
    );
};

export default QuickActions;
