import React, { useState, useEffect } from 'react';
import CloseIcon from '@mui/icons-material/Close';
import SaveIcon from '@mui/icons-material/Save';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import LinkIcon from '@mui/icons-material/Link';
import { getNonce } from '../Helpers';

interface Integration {
    id: string;
    name: string;
    description: string;
    icon: string;
    config: any;
    fields: ConfigField[];
}

interface ConfigField {
    name: string;
    label: string;
    type: string;
    required?: boolean;
    sensitive?: boolean;
    placeholder?: string;
    description?: string;
    options?: Array<{ value: string; label: string }>;
}

interface IntegrationModalProps {
    integration: Integration;
    isOpen: boolean;
    onClose: () => void;
    onSave: (integrationId: string, config: any) => void;
    onTest: (integrationId: string, config: any) => Promise<string>;
}

const IntegrationModal: React.FC<IntegrationModalProps> = ({
    integration,
    isOpen,
    onClose,
    onSave,
    onTest
}) => {
    const [config, setConfig] = useState<any>({});
    const [testing, setTesting] = useState(false);
    const [testResult, setTestResult] = useState<{ success: boolean; message: string } | null>(null);
    const [saving, setSaving] = useState(false);
    const [activeTab, setActiveTab] = useState<'settings' | 'hints'>('settings');
    const [connecting, setConnecting] = useState(false);

    useEffect(() => {
        if (isOpen) {
            // Initialize config with existing values
            setConfig(integration.config || {});
            setTestResult(null);
            setActiveTab('settings');
        }
    }, [isOpen, integration]);

    const handleChange = (fieldName: string, value: any) => {
        setConfig((prev: any) => ({
            ...prev,
            [fieldName]: value
        }));
        setTestResult(null); // Clear test result when config changes
    };

    const handleTest = async () => {
        setTesting(true);
        setTestResult(null);

        try {
            const message = await onTest(integration.id, config);
            setTestResult({ success: true, message });
        } catch (error: any) {
            setTestResult({ success: false, message: error });
        } finally {
            setTesting(false);
        }
    };

    const handleSave = () => {
        setSaving(true);
        onSave(integration.id, config);
        // Reset saving state after a delay (will be handled by parent component)
        setTimeout(() => setSaving(false), 1000);
    };

    const handleConnectToGoogle = async () => {
        setConnecting(true);
        setTestResult(null);

        try {
            const response = await fetch((window as any).ajaxurl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'simpleform_get_oauth_url',
                    nonce: getNonce(),
                    integration_id: integration.id,
                }),
            });

            const data = await response.json();

            if (data.success) {
                // Redirect to Google authorization
                window.location.href = data.data.auth_url;
            } else {
                setTestResult({
                    success: false,
                    message: data.data?.message || 'Failed to get authorization URL'
                });
            }
        } catch (error: any) {
            setTestResult({
                success: false,
                message: 'Error connecting to Google: ' + error.message
            });
        } finally {
            setConnecting(false);
        }
    };

    const renderHintsTab = () => {
        if (integration.id === 'google_sheets') {
            return (
                <div className="hints-content">
                    <h3>📋 Setup Instructions</h3>

                    <div className="hint-section">
                        <h4>Step 1: Create OAuth Credentials</h4>
                        <ol>
                            <li>Go to <a href="https://console.cloud.google.com/" target="_blank" rel="noopener noreferrer">Google Cloud Console</a></li>
                            <li>Select your project or create a new one</li>
                            <li>Navigate to <strong>APIs & Services</strong> → <strong>Credentials</strong></li>
                            <li>Click <strong>Create Credentials</strong> → <strong>OAuth client ID</strong></li>
                            <li>Choose <strong>Web application</strong></li>
                            <li>Add this as <strong>Authorized redirect URI</strong>:
                                <div className="code-block">
                                    {window.location.origin}/wp-admin/admin.php
                                </div>
                                <small style={{ color: '#64748b', fontSize: '12px', display: 'block', marginTop: '4px' }}>
                                    Note: Use ONLY the base URL without any query parameters
                                </small>
                            </li>
                            <li>Click <strong>Create</strong> and copy your <strong>Client ID</strong> and <strong>Client Secret</strong></li>
                        </ol>
                    </div>

                    <div className="hint-section">
                        <h4>Step 2: Enable Google Sheets API</h4>
                        <ol>
                            <li>In Google Cloud Console, go to <strong>APIs & Services</strong> → <strong>Library</strong></li>
                            <li>Search for "Google Sheets API"</li>
                            <li>Click <strong>Enable</strong></li>
                        </ol>
                    </div>

                    <div className="hint-section">
                        <h4>Step 3: Configure OAuth Consent Screen</h4>
                        <ol>
                            <li>Go to <strong>APIs & Services</strong> → <strong>OAuth consent screen</strong></li>
                            <li>Choose <strong>External</strong> (for public) or <strong>Internal</strong> (for organization)</li>
                            <li>Fill in app name, support email, and developer contact</li>
                            <li>Add scope: <code>https://www.googleapis.com/auth/spreadsheets</code></li>
                            <li>Save and continue</li>
                        </ol>
                    </div>

                    <div className="hint-section warning-hint">
                        <h4>⚠️ Important: Add Test Users</h4>
                        <p>Since your app is in <strong>Testing</strong> mode, you must add test users:</p>
                        <ol>
                            <li>In <strong>OAuth consent screen</strong>, scroll to <strong>Test users</strong> section</li>
                            <li>Click <strong>+ ADD USERS</strong></li>
                            <li>Enter your Google email address (the one you'll use to authorize)</li>
                            <li>Click <strong>SAVE</strong></li>
                        </ol>
                        <p style={{ marginTop: '8px', fontSize: '13px' }}>
                            Without adding yourself as a test user, you'll get an "access_denied" error when trying to connect.
                        </p>
                    </div>

                    <div className="hint-section">
                        <h4>Step 4: Connect SimpleForm</h4>
                        <ol>
                            <li>Enter your <strong>Client ID</strong> and <strong>Client Secret</strong> in the Settings tab</li>
                            <li>Click <strong>Save Settings</strong></li>
                            <li>Click <strong>Connect to Google</strong> button</li>
                            <li>Authorize the app when redirected to Google</li>
                            <li>You'll be redirected back automatically</li>
                            <li>Enter your <strong>Spreadsheet URL</strong> and <strong>Sheet Name</strong></li>
                            <li>Click <strong>Test Connection</strong> to verify</li>
                        </ol>
                    </div>

                    <div className="hint-section success-hint">
                        <h4>✅ You're All Set!</h4>
                        <p>Once connected, all form submissions will automatically be sent to your Google Sheet.</p>
                    </div>

                    <div className="hint-section warning-hint">
                        <h4>⚠️ Troubleshooting</h4>
                        <ul>
                            <li><strong>Invalid redirect URI:</strong> Make sure you added the exact redirect URI to Google Cloud Console</li>
                            <li><strong>Access denied:</strong> Check that Google Sheets API is enabled</li>
                            <li><strong>Token expired:</strong> Tokens auto-refresh, but you can reconnect if needed</li>
                        </ul>
                    </div>
                </div>
            );
        }

        if (integration.id === 'fluentcrm') {
            return (
                <div className="hints-content">
                    <h3>📋 Setup Instructions</h3>

                    <div className="hint-section">
                        <h4>Step 1: Install FluentCRM</h4>
                        <ol>
                            <li>Go to <strong>Plugins</strong> → <strong>Add New</strong> in your WordPress admin</li>
                            <li>Search for "FluentCRM"</li>
                            <li>Click <strong>Install Now</strong> and then <strong>Activate</strong></li>
                            <li>Or download from <a href="https://wordpress.org/plugins/fluent-crm/" target="_blank" rel="noopener noreferrer">WordPress.org</a></li>
                        </ol>
                    </div>

                    <div className="hint-section">
                        <h4>Step 2: Create Lists and Tags</h4>
                        <ol>
                            <li>Go to <strong>FluentCRM</strong> → <strong>Contacts</strong> → <strong>Lists</strong></li>
                            <li>Create lists to organize your contacts (e.g., "Newsletter Subscribers", "Leads")</li>
                            <li>Go to <strong>FluentCRM</strong> → <strong>Contacts</strong> → <strong>Tags</strong></li>
                            <li>Create tags to categorize contacts (e.g., "Website Form", "Contact Page")</li>
                        </ol>
                    </div>

                    <div className="hint-section">
                        <h4>Step 3: Configure Global Settings</h4>
                        <ol>
                            <li>In the <strong>Settings</strong> tab, select your default lists and tags</li>
                            <li>Choose whether to enable double opt-in (recommended for GDPR compliance)</li>
                            <li>Decide if existing contacts should be updated</li>
                            <li>Click <strong>Save Settings</strong></li>
                            <li>Toggle the integration <strong>ON</strong> to enable it</li>
                        </ol>
                    </div>

                    <div className="hint-section">
                        <h4>Step 4: Configure Per-Form Settings (Optional)</h4>
                        <p>Each form can have its own FluentCRM settings:</p>
                        <ol>
                            <li>Open any form in the <strong>Form Builder</strong></li>
                            <li>Go to <strong>Form Settings</strong> tab</li>
                            <li>Scroll to <strong>FluentCRM Integration</strong> section</li>
                            <li>Toggle to enable/disable for this specific form</li>
                            <li>Select form-specific lists and tags (overrides global settings)</li>
                            <li>Save your form</li>
                        </ol>
                    </div>

                    <div className="hint-section success-hint">
                        <h4>✅ How It Works</h4>
                        <ul>
                            <li>When a form is submitted, the contact is automatically added to FluentCRM</li>
                            <li>Email, name, phone, and other fields are mapped automatically</li>
                            <li>Contacts are added to the selected lists and tagged appropriately</li>
                            <li>You can then use FluentCRM's automation features for follow-ups</li>
                        </ul>
                    </div>

                    <div className="hint-section warning-hint">
                        <h4>⚠️ Important Notes</h4>
                        <ul>
                            <li><strong>Email Required:</strong> Forms must have an email field for FluentCRM integration to work</li>
                            <li><strong>Global vs Form Settings:</strong> Form-specific settings override global settings</li>
                            <li><strong>Double Opt-in:</strong> If enabled, contacts will receive a confirmation email before being added</li>
                            <li><strong>GDPR Compliance:</strong> Make sure you have proper consent checkboxes in your forms</li>
                        </ul>
                    </div>
                </div>
            );
        }

        // Default hints for other integrations
        return (
            <div className="hints-content">
                <h3>Setup Instructions</h3>
                <p>Follow the instructions in the Settings tab to configure this integration.</p>
            </div>
        );
    };

    const renderField = (field: ConfigField) => {
        const value = config[field.name] || '';

        switch (field.type) {
            case 'text':
            case 'password':
            case 'email':
            case 'url':
                return (
                    <input
                        type={field.type}
                        value={value}
                        onChange={(e) => handleChange(field.name, e.target.value)}
                        placeholder={field.placeholder}
                        required={field.required}
                    />
                );

            case 'textarea':
                return (
                    <textarea
                        value={value}
                        onChange={(e) => handleChange(field.name, e.target.value)}
                        placeholder={field.placeholder}
                        required={field.required}
                        rows={4}
                    />
                );

            case 'select':
                return (
                    <select
                        value={value}
                        onChange={(e) => handleChange(field.name, e.target.value)}
                        required={field.required}
                    >
                        <option value="">Select...</option>
                        {field.options?.map(option => (
                            <option key={option.value} value={option.value}>
                                {option.label}
                            </option>
                        ))}
                    </select>
                );

            case 'checkbox':
                return (
                    <label className="checkbox-label">
                        <input
                            type="checkbox"
                            checked={value === true}
                            onChange={(e) => handleChange(field.name, e.target.checked)}
                        />
                        <span>{field.label}</span>
                    </label>
                );

            case 'multiselect':
                const selectedValues = Array.isArray(value) ? value : [];
                return (
                    <div className="multiselect-container">
                        <select
                            multiple
                            value={selectedValues}
                            onChange={(e) => {
                                const options = Array.from(e.target.selectedOptions);
                                const values = options.map(option => option.value);
                                handleChange(field.name, values);
                            }}
                            className="multiselect-field"
                            size={Math.min(field.options?.length || 5, 8)}
                        >
                            {field.options?.map(option => (
                                <option key={option.value} value={option.value}>
                                    {option.label}
                                </option>
                            ))}
                        </select>
                        <small className="multiselect-hint">
                            Hold Ctrl (Cmd on Mac) to select multiple items
                        </small>
                    </div>
                );

            default:
                return (
                    <input
                        type="text"
                        value={value}
                        onChange={(e) => handleChange(field.name, e.target.value)}
                        placeholder={field.placeholder}
                    />
                );
        }
    };

    if (!isOpen) return null;

    return (
        <div className="integration-modal-overlay" onClick={onClose}>
            <div className="integration-modal" onClick={(e) => e.stopPropagation()}>
                <div className="modal-header">
                    <h2>{integration.name} Settings</h2>
                    <button className="close-button" onClick={onClose}>
                        <CloseIcon />
                    </button>
                </div>

                {/* Tabs */}
                <div className="modal-tabs">
                    <button
                        className={`tab-button ${activeTab === 'settings' ? 'active' : ''}`}
                        onClick={() => setActiveTab('settings')}
                    >
                        Settings
                    </button>
                    <button
                        className={`tab-button ${activeTab === 'hints' ? 'active' : ''}`}
                        onClick={() => setActiveTab('hints')}
                    >
                        Hints
                    </button>
                </div>

                <div className="modal-body">
                    {activeTab === 'settings' ? (
                        <>
                            <p className="modal-description">{integration.description}</p>

                            <div className="config-fields">
                                {integration.fields.map(field => (
                                    <div key={field.name} className="field-group">
                                        {field.type !== 'checkbox' && (
                                            <label>
                                                {field.label}
                                                {field.required && <span className="required">*</span>}
                                            </label>
                                        )}
                                        {renderField(field)}
                                        {field.description && (
                                            <small className="field-description">{field.description}</small>
                                        )}
                                    </div>
                                ))}
                            </div>

                            {testResult && (
                                <div className={`test-result ${testResult.success ? 'success' : 'error'}`}>
                                    {testResult.success ? <CheckCircleIcon /> : <CloseIcon />}
                                    <span>{testResult.message}</span>
                                </div>
                            )}
                        </>
                    ) : (
                        renderHintsTab()
                    )}
                </div>

                <div className="modal-footer">
                    <div className="left-buttons">
                        {integration.id === 'google_sheets' && activeTab === 'settings' && (
                            <button
                                className="connect-google-button"
                                onClick={handleConnectToGoogle}
                                disabled={connecting || testing || saving}
                            >
                                <LinkIcon />
                                {connecting ? 'Connecting...' : 'Connect to Google'}
                            </button>
                        )}
                    </div>

                    <div className="action-buttons">
                        <button
                            className="test-button"
                            onClick={handleTest}
                            disabled={testing || saving || connecting}
                        >
                            {testing ? 'Testing...' : 'Test Connection'}
                        </button>
                        <button
                            className="save-button"
                            onClick={handleSave}
                            disabled={saving}
                        >
                            <SaveIcon />
                            {saving ? 'Saving...' : 'Save Settings'}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default IntegrationModal;
