import React, { useState, useEffect } from 'react';
import { Shield, Settings, Clock, Eye, EyeOff } from 'lucide-react';
import NoticeModal from '../NoticeModal/NoticeModal';
import './configure.scss';

const Configure = () => {
    const [apiUrl, setApiUrl] = useState('');
    const [apiKey, setApiKey] = useState('');
    const [showApiKey, setShowApiKey] = useState(false);
    const [testButtonText, setTestButtonText] = useState('Test Connection');
    const [isTestButtonDisabled, setIsTestButtonDisabled] = useState(false);
    const [activeFaq, setActiveFaq] = useState(null);

    const [modalConfig, setModalConfig] = useState({
        isOpen: false,
        type: 'confirmation',
        title: '',
        message: '',
        onConfirm: () => { },
        confirmText: 'Confirm',
        declineText: 'Cancel',
        mode: 'success'
    });

    const closeModal = () => {
        setModalConfig(prev => ({ ...prev, isOpen: false }));
    };

    useEffect(() => {
        // Load saved values on component mount
        loadApiSettings();
    }, []);

    const loadApiSettings = async () => {
        try {
            const settings = await makeAjaxRequest('get_api_settings');
            if (settings) {
                setApiUrl(settings.api_url || 'https://functiondeck.com/');
                setApiKey(settings.api_key || '890b75e99a1c2fb0a586c5efeae2c30e');
            }
        } catch (error) {
            console.error('Error loading API settings:', error);
        }
    };

    const makeAjaxRequest = async (action, data = {}) => {
        const formData = new FormData();
        formData.append('action', action);
        formData.append('nonce', appLocalizer.nonce);

        Object.entries(data).forEach(([key, value]) => {
            if (Array.isArray(value) || typeof value === 'object') {
                formData.append(key, JSON.stringify(value));
            } else {
                formData.append(key, value);
            }
        });

        try {
            const response = await fetch(appLocalizer.admin_ajax, {
                method: 'POST',
                credentials: 'same-origin',
                body: formData,
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const responseData = await response.json();
            if (responseData.success) {
                return responseData.data;
            } else {
                throw new Error(responseData.data || 'Ajax request failed');
            }
        } catch (error) {
            console.error(`Ajax error in ${action}:`, error);
            throw error;
        }
    };

    const handleSaveSettings = async (e) => {
        e.preventDefault();

        try {
            await makeAjaxRequest('update_api_settings', {
                api_url: apiUrl,
                api_key: apiKey
            });
            setModalConfig({
                isOpen: true,
                type: 'toast',
                title: 'success!',
                message: 'API settings saved successfully!',
                position: 'top-right'
            });
            setTimeout(closeModal, 3000);
        } catch (error) {
            console.error('Error saving API settings:', error);
            setModalConfig({
                isOpen: true,
                type: 'toast',
                title: 'warning!',
                message: 'Error saving API settings.',
                position: 'top-right'
            });
            setTimeout(closeModal, 3000);
        }
    };

    // Format API key to show only first 8 characters and rest as asterisks when hidden
    const getDisplayApiKey = () => {
        if (showApiKey) {
            return apiKey;
        } else {
            // If API key is empty or less than 8 chars, handle appropriately
            if (!apiKey || apiKey.length <= 8) {
                return apiKey.substring(0, Math.min(apiKey.length, 8)) +
                    '*'.repeat(Math.max(0, apiKey.length - 8));
            } else {
                const visiblePart = apiKey.substring(0, 8);
                const hiddenPart = '*'.repeat(apiKey.length - 8);
                return visiblePart + hiddenPart;
            }
        }
    };

    const toggleFaq = (index) => {
        setActiveFaq(activeFaq === index ? null : index);
    };

    const faqs = [
        {
            question: "What is the Vulnerabilities Scanner. How it work?",
            answer: "The Vulnerabilities Scanner operates through four key steps to identify potential security threats on your website. It thoroughly scans your site's directory files, plugins, and themes, detecting vulnerabilities by matching security patterns. Since plugins or themes can sometimes introduce hidden malicious code, regular scanning helps keep your site secure.This scanner enhances security by cross-referencing data from multiple trusted sources, including the FunctionDeck Security Database, WPVulnerability Database, and the National Vulnerability Database. Vulnerabilities Scanner scan each file from the site directory to identify malicious code. If your site is ever compromised or injected with malicious code, this tool can help pinpoint the root cause. As this is a beta version, your feedback and collaboration are highly valued!"
        },
        {
            question: "What is an API key?",
            answer: "An API key is a unique identifier used to authenticate requests to our security scanning service from FunctionDeck database, ensuring that only authorized users can access the API. In this beta version, a default API key is included. However, in the future, we may transition to a unique key for each site to enhance security."
        },
        {
            question: "Where can I find my API key?",
            answer: "Your default API key is provided in your scanner configure tab. You can also request a new key if needed."
        },
        {
            question: "Why is my connection test failing?",
            answer: "Connection tests might fail due to incorrect API credentials, server issues, or network problems. Double-check your API URL and key, ensure your internet connection is stable, and try again."
        },
        {
            question: "How often should I update my API key?",
            answer: "We recommend updating your API key every 90 days as a security best practice. You can generate a new key by contact us at Functiondeck supports."
        },
        {
            question: "Do I need to manually scan every day?",
            answer: "We recommend performing a daily scan to maintain your site's security. In the future, we plan to introduce automatic scheduled scans that will run at specific times and notify you with a detailed scan report in activity log also in slack and mail. However, since this is a beta version, manual scanning is required for now."
        },
        {
            question: "How do the Exclusion Settings work?",
            answer: "The Exclusion Settings allow you to specify which paths, file patterns, PHP functions, directories, plugins, or themes should be skipped during the security scan. This helps you customize the scanning process based on your needs."
        },
        {
            question: "Why is the core file excluded?",
            answer: "WordPress core files are generally secure and less likely to contain malicious code. Excluding them allows the scanner to focus on more vulnerable areas, such as uploads, plugins and themes directories, ensuring a faster and more efficient scan. However, if you're concerned or suspect a security breach, you can include WordPress core files in the scan to help identify any injected malicious code."
        },
    ];

    return (
        <div className="configure-content">
            <div className="config-layout">
                <div className="config-main">
                    <div className="settings-card">
                        <h2>API Configuration</h2>
                        <p className="settings-description">
                            Configure the API settings for the security scanner. These settings are used to connect to the security service.
                        </p>
                        <p className='api-notice'>
                            If you have any issues with API Keys, you can contact us at{' '}
                            <a href="https://functiondeck.com/support/" target="_blank" rel="noopener noreferrer">
                                Functiondeck
                            </a>
                            {' '}supports.
                        </p>

                        <form onSubmit={handleSaveSettings} className="api-settings-form">
                            <div className="form-group">
                                <label className='security-api-label' htmlFor="api-url">API URL</label>
                                <input
                                    type="url"
                                    id="api-url"
                                    value={apiUrl}
                                    onChange={(e) => setApiUrl(e.target.value)}
                                    placeholder="Enter API URL"
                                    className="form-input api-keys"
                                />
                            </div>

                            <div className="form-group">
                                <label className='security-api-label' htmlFor="api-key">API Key</label>
                                <div className="input-with-icon">
                                    <input
                                        type={showApiKey ? "text" : "password"}
                                        id="api-key"
                                        value={apiKey}
                                        onChange={(e) => setApiKey(e.target.value)}
                                        placeholder="Enter API Key"
                                        className="form-input api-keys"
                                    />
                                    <button
                                        type="button"
                                        className="toggle-visibility"
                                        onClick={() => setShowApiKey(!showApiKey)}
                                        aria-label={showApiKey ? "Hide API key" : "Show API key"}
                                    >
                                        {showApiKey ? <EyeOff size={20} /> : <Eye size={20} />}
                                    </button>
                                </div>
                                <div className="api-key-display">
                                    {getDisplayApiKey()}
                                </div>
                            </div>

                            <div className="form-actions">
                                <button type="submit" className="button button-primary save-keys">Save Settings</button>
                            </div>
                        </form>
                    </div>

                    <div className="connection-test">
                        <h3>Test Connection</h3>
                        <p>Verify that your API credentials are working correctly.</p>
                        <button
                            type="button"
                            className="button test-connection-button"
                            disabled={isTestButtonDisabled}
                            onClick={async () => {
                                setTestButtonText('Testing...');
                                setIsTestButtonDisabled(true);

                                try {
                                    const result = await makeAjaxRequest('test_api_connection', {
                                        api_url: apiUrl,
                                        api_key: apiKey
                                    });
                                    setModalConfig({
                                        isOpen: true,
                                        type: 'toast',
                                        mode: 'success',
                                        title: 'success!',
                                        message: 'Connection Successful.',
                                        position: 'top-right'
                                    });
                                    setTimeout(closeModal, 3000);
                                } catch (error) {
                                    console.error('Error testing connection:', error);
                                    setModalConfig({
                                        isOpen: true,
                                        type: 'toast',
                                        mode: 'error',
                                        title: 'Error!',
                                        message: 'Could not connect to the API. Please verify your API Configurations.',
                                        position: 'top-right'
                                    });
                                    setTimeout(closeModal, 3000);
                                } finally {
                                    setTestButtonText('Test Connection');
                                    setIsTestButtonDisabled(false);
                                }
                            }}
                        >
                            {testButtonText}
                        </button>
                    </div>
                </div>

                <div className="config-sidebar">
                    <div className="setup-guide">
                        <h3>Getting Started Guide</h3>
                        <div className="guide-steps">

                            <div className="guide-step">
                                <div className="step-number">1</div>
                                <div className="step-content">
                                    <h4>API Configuration</h4>
                                    <p>You will get default keys for the site. Incase of failed connection reach us at <a href="https://functiondeck.com/register" target="_blank" rel="noopener noreferrer">Functiondeck</a> to receive your API credentials</p>
                                </div>
                            </div>
                            <div className="guide-step">
                                <div className="step-number">2</div>
                                <div className="step-content">
                                    <h4>Configure API Settings</h4>
                                    <p>Enter your API URL and API Key in the form</p>
                                </div>
                            </div>
                            <div className="guide-step">
                                <div className="step-number">3</div>
                                <div className="step-content">
                                    <h4>Test Connection</h4>
                                    <p>Verify your connection is working</p>
                                </div>
                            </div>
                            <div className="guide-step">
                                <div className="step-number">4</div>
                                <div className="step-content">
                                    <h4>Start Scanning</h4>
                                    <p>Navigate to the Security Scanner tab</p>
                                </div>
                            </div>

                            <div className="guide-step">
                                <div className="step-number">🥶</div>
                                <div className="step-content">
                                    <h4>Understand the Status</h4>
                                    <span className="scan-status status-vulnerable">Vulnerable</span>{' '}
                                    <span className="scan-status status-critical">Critical</span>{' '}
                                    <span className="scan-status status-secure">Secure</span>{' '}
                                    <span className="scan-status status-warning">Warning</span>
                                    <br />
                                    <br />
                                    <p style={{ color: '#000' }}>
                                        <strong style={{ color: '#ff4d4d' }}>Vulnerable</strong> and <strong style={{ color: '#dc3545' }}>Critical</strong> indicate that the scanner has detected potentially dangerous security patterns. If these patterns are found in the <strong>core WordPress directory</strong> and your site is <strong>up to date</strong>, they may be harmless as <strong>WordPress core files</strong> sometimes include such patterns for specific functionalities. However, if the issue is detected in a <strong>plugin</strong> or <strong>theme</strong>, consider reaching out to the <strong>developer</strong> for support or switching to a more <strong>secure alternative</strong>.
                                    </p>
                                    <br />

                                    <p style={{ color: '#000' }}>
                                        <strong style={{ color: '#16a34a' }}>Secure</strong> means your site is in <strong>excellent condition</strong>, with <strong>no security threats detected</strong>.
                                    </p>
                                    <br />

                                    <p style={{ color: '#000' }}>
                                        <strong style={{ color: '#d97706' }}>Warning</strong> suggests that while your site is <strong>generally secure</strong>, some <strong>plugins</strong> or <strong>themes</strong> may have <strong>minor concerns</strong>. These are typically <strong>low-risk</strong> but should be reviewed to ensure the <strong>highest level of security</strong>.
                                    </p>
                                </div>

                            </div>

                        </div>
                    </div>

                    <div className="scan-faq-section">
                        <h3>Frequently Asked Questions</h3>
                        <div className="scan-faq-list">
                            {faqs.map((faq, index) => (
                                <div className={`scan-faq-item ${activeFaq === index ? 'active' : ''}`} key={index}>
                                    <div className="scan-faq-question" onClick={() => toggleFaq(index)}>
                                        {faq.question}
                                        <span className="scan-faq-toggle">{activeFaq === index ? '−' : '+'}</span>
                                    </div>
                                    {activeFaq === index && (
                                        <div className="scan-faq-answer">
                                            {faq.answer}
                                        </div>
                                    )}
                                </div>
                            ))}
                        </div>
                    </div>

                </div>
            </div>
            <NoticeModal
                isOpen={modalConfig.isOpen}
                onClose={closeModal}
                onConfirm={modalConfig.onConfirm}
                onDecline={closeModal}
                type={modalConfig.type}
                mode={modalConfig.mode}
                title={modalConfig.title}
                message={modalConfig.message}
                confirmText={modalConfig.confirmText}
                declineText={modalConfig.declineText}
                position={modalConfig.position || 'center'}
                autoClose={modalConfig.type === 'toast'}
                autoCloseTime={3000}
            />
        </div >
    );
};

export default Configure;