import React, { useState, useEffect } from 'react';
import { getNonce, isPro } from '../Helpers';
import IntegrationCard from './IntegrationCard';
import IntegrationModal from './IntegrationModal';
import IntegrationHelpModal from './IntegrationHelpModal';
import NoticeModal from './NoticeModal/NoticeModal';
import '../styles/_integrations.scss';

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

interface ConfigField {
    name: string;
    label: string;
    type: string;
    required?: boolean;
    sensitive?: boolean;
    placeholder?: string;
    description?: string;
    options?: any[];
}

const defaultIntegrationsData: Integration[] = [
    {
        "id": "mailchimp",
        "name": "Mailchimp",
        "description": "Send form submissions to your Mailchimp mailing lists automatically.",
        "icon": "MailOutline",
        "enabled": false,
        "configured": false,
        "config": {},
        "fields": [
            {
                "name": "api_key",
                "label": "API Key",
                "type": "password",
                "required": true,
                "sensitive": true,
                "placeholder": "Enter your Mailchimp API key",
                "description": "Find your API key in Mailchimp Account > Extras > API keys"
            },
            {
                "name": "list_id",
                "label": "List ID / Audience ID",
                "type": "text",
                "required": true,
                "placeholder": "Enter your list/audience ID",
                "description": "Find your list ID in Mailchimp Audience > Settings > Audience name and defaults"
            },
            {
                "name": "tags",
                "label": "Tags (Optional)",
                "type": "text",
                "required": false,
                "placeholder": "lead, website, contact-form",
                "description": "Comma-separated tags to add to subscribers"
            },
            {
                "name": "double_optin",
                "label": "Enable Double Opt-in",
                "type": "checkbox",
                "required": false,
                "description": "Send confirmation email before adding to list"
            },
            {
                "name": "update_existing",
                "label": "Update Existing Subscribers",
                "type": "checkbox",
                "required": false,
                "description": "Update subscriber info if email already exists"
            }
        ]
    },
    {
        "id": "google_sheets",
        "name": "Google Sheets",
        "description": "Automatically send form submissions to Google Sheets with organized tabs per form.",
        "icon": "TableChart",
        "enabled": false,
        "configured": false,
        "config": {},
        "fields": [
            {
                "name": "client_id",
                "label": "Client ID",
                "type": "text",
                "required": true,
                "placeholder": "Enter your Google OAuth Client ID",
                "description": "Get from Google Cloud Console > APIs & Services > Credentials"
            },
            {
                "name": "client_secret",
                "label": "Client Secret",
                "type": "password",
                "required": true,
                "sensitive": true,
                "placeholder": "Enter your Google OAuth Client Secret",
                "description": "Get from Google Cloud Console > APIs & Services > Credentials"
            },
            {
                "name": "spreadsheet_url",
                "label": "Spreadsheet URL",
                "type": "url",
                "required": true,
                "placeholder": "https://docs.google.com/spreadsheets/d/...",
                "description": "The URL of your Google Spreadsheet"
            }
        ]
    },
    {
        "id": "trello",
        "name": "Trello",
        "description": "Create Trello cards automatically from form submissions.",
        "icon": "Dashboard",
        "enabled": false,
        "configured": false,
        "config": {},
        "fields": [
            {
                "name": "api_key",
                "label": "API Key",
                "type": "text",
                "required": true,
                "sensitive": true,
                "placeholder": "Enter your Trello API key",
                "description": "Get from https://trello.com/app-key"
            },
            {
                "name": "api_token",
                "label": "API Token",
                "type": "password",
                "required": true,
                "sensitive": true,
                "placeholder": "Enter your Trello API token",
                "description": "Generate token from the API key page"
            },
            {
                "name": "board_id",
                "label": "Board ID",
                "type": "text",
                "required": true,
                "placeholder": "Enter your Trello board ID",
                "description": "Find in board URL: trello.com/b/BOARD_ID/board-name"
            },
            {
                "name": "list_id",
                "label": "List ID",
                "type": "text",
                "required": true,
                "placeholder": "Enter your Trello list ID",
                "description": "The list where cards will be created"
            },
            {
                "name": "card_title_template",
                "label": "Card Title Template",
                "type": "text",
                "required": false,
                "placeholder": "New Lead: {name}",
                "description": "Use {field_name} to insert form field values"
            },
            {
                "name": "label_ids",
                "label": "Label IDs (Optional)",
                "type": "text",
                "required": false,
                "placeholder": "label1,label2,label3",
                "description": "Comma-separated label IDs to add to cards"
            }
        ]
    },
    {
        "id": "fluentcrm",
        "name": "FluentCRM",
        "description": "Automatically sync form submissions to FluentCRM contacts with tags and lists for powerful email marketing automation.",
        "icon": "ContactMail",
        "enabled": false,
        "configured": false,
        "config": {},
        "fields": [
            {
                "name": "default_lists",
                "label": "Default Lists",
                "type": "multiselect",
                "required": false,
                "options": [],
                "placeholder": "Select default lists",
                "description": "Default lists to add contacts to (can be overridden per form)"
            },
            {
                "name": "default_tags",
                "label": "Default Tags",
                "type": "multiselect",
                "required": false,
                "options": [],
                "placeholder": "Select default tags",
                "description": "Default tags to add to contacts (can be overridden per form)"
            },
            {
                "name": "double_optin",
                "label": "Enable Double Opt-in",
                "type": "checkbox",
                "required": false,
                "description": "Require email confirmation before adding to lists"
            },
            {
                "name": "update_existing",
                "label": "Update Existing Contacts",
                "type": "checkbox",
                "required": false,
                "description": "Update contact information if email already exists"
            },
            {
                "name": "skip_if_exists",
                "label": "Skip if Contact Exists",
                "type": "checkbox",
                "required": false,
                "description": "Do not update or add tags/lists if contact already exists"
            }
        ]
    }
];

const Integrations: React.FC = () => {
    const [loading, setLoading] = useState(true);
    const [integrations, setIntegrations] = useState<Integration[]>([]);
    const [selectedIntegration, setSelectedIntegration] = useState<Integration | null>(null);
    const [modalOpen, setModalOpen] = useState(false);
    const [helpModalOpen, setHelpModalOpen] = useState(false);
    const [helpIntegration, setHelpIntegration] = useState<Integration | null>(null);
    const [isProUser, setIsProUser] = useState(false);
    const [modalConfig, setModalConfig] = useState({
        isOpen: false,
        type: 'toast' as 'success' | 'error' | 'confirmation' | 'premium' | 'toast',
        title: '',
        message: '',
        position: 'top-right' as 'top-right' | 'center',
        mode: 'success' as 'success' | 'error',
        onConfirm: () => { },
        onClose: () => { },
        confirmText: 'OK',
        declineText: 'Cancel'
    });

    useEffect(() => {
        checkProStatus();
        loadIntegrations();
    }, []);

    const checkProStatus = () => {
        const isProactive = isPro();
        setIsProUser(isProactive);
    };

    const handleHelp = (integration: Integration) => {
        setHelpIntegration(integration);
        setHelpModalOpen(true);
    };

    const closeModal = () => {
        setModalConfig(prev => ({ ...prev, isOpen: false }));
    };

    const showToast = (mode: 'success' | 'error', title: string, message: string) => {
        setModalConfig({
            isOpen: true,
            type: 'toast',
            title,
            message,
            position: 'top-right',
            mode,
            onConfirm: closeModal,
            onClose: closeModal,
            confirmText: 'OK',
            declineText: 'Cancel'
        });
        setTimeout(closeModal, 3000);
    };

    const showProModal = () => {
        setModalConfig({
            isOpen: true,
            type: 'premium',
            title: '🚀 Upgrade to Pro',
            message: 'Integrations are available in the Pro version. Connect your forms to Mailchimp, Google Sheets, Trello, and more!',
            position: 'center',
            mode: 'success',
            onConfirm: () => {
                window.open('https://wpazleen.com/simple-form-pricing/', '_blank');
                closeModal();
            },
            onClose: closeModal,
            confirmText: 'Upgrade Now',
            declineText: 'Maybe Later'
        });
    };

    const loadIntegrations = () => {
        if (!isPro()) {
            setIntegrations(defaultIntegrationsData);
            setLoading(false);
            return;
        }

        (wp as any).ajax.send('simpleform_get_integrations', {
            data: {
                nonce: getNonce(),
            },
            success(response: any) {
                if (response.integrations) {
                    setIntegrations(response.integrations);
                }
                setLoading(false);
            },
            error(error: any) {
                showToast('error', 'Error', 'Failed to load integrations. Please refresh the page.');
                setLoading(false);
            },
        });
    };

    const handleToggle = (integrationId: string) => {
        if (!isProUser) {
            showProModal();
            return;
        }

        const integration = integrations.find(int => int.id === integrationId);
        if (!integration) return;

        const newEnabledState = !integration.enabled;

        (wp as any).ajax.send('simpleform_toggle_integration', {
            data: {
                nonce: getNonce(),
                integration_id: integrationId,
                enabled: newEnabledState,
            },
            success(response: any) {
                // Update local state
                setIntegrations(prev =>
                    prev.map(int =>
                        int.id === integrationId ? { ...int, enabled: newEnabledState } : int
                    )
                );
                showToast('success', 'Success', response.message || 'Integration updated.');
            },
            error(error: any) {
                showToast('error', 'Error', error.message || 'Failed to update integration.');
            },
        });
    };

    const handleSettings = (integration: Integration) => {
        if (!isProUser) {
            showProModal();
            return;
        }

        setSelectedIntegration(integration);
        setModalOpen(true);
    };

    const handleSaveConfig = (integrationId: string, config: any) => {
        (wp as any).ajax.send('simpleform_save_integration', {
            data: {
                nonce: getNonce(),
                integration_id: integrationId,
                config: config,
            },
            success(response: any) {
                showToast('success', 'Success', response.message || 'Settings saved successfully.');
                setModalOpen(false);
                loadIntegrations(); // Reload to get updated data
            },
            error(error: any) {
                showToast('error', 'Error', error.message || 'Failed to save settings.');
            },
        });
    };

    const handleTestConnection = (integrationId: string, config: any) => {
        return new Promise((resolve, reject) => {
            (wp as any).ajax.send('simpleform_test_integration', {
                data: {
                    nonce: getNonce(),
                    integration_id: integrationId,
                    config: config,
                },
                success(response: any) {
                    resolve(response.message || 'Connection successful!');
                },
                error(error: any) {
                    reject(error.message || 'Connection failed.');
                },
            });
        });
    };

    if (loading) {
        return (
            <div className="integrations-loading">
                <div className="spinner"></div>
                <p>Loading integrations...</p>
            </div>
        );
    }

    return (
        <div className="integrations-container">
            <div className="integrations-header">
                <h1>Integrations</h1>
                <p>Connect your forms to third-party services</p>
            </div>

            <div className="integrations-grid">
                {integrations.map(integration => (
                    <IntegrationCard
                        key={integration.id}
                        integration={integration}
                        onToggle={handleToggle}
                        onSettings={handleSettings}
                        onHelp={handleHelp}
                        disabled={!isProUser}
                        isProUser={isProUser}
                        onProClick={showProModal}
                    />
                ))}
            </div>

            {integrations.length === 0 && (
                <div className="no-integrations">
                    <p>No integrations available yet.</p>
                </div>
            )}

            {selectedIntegration && (
                <IntegrationModal
                    integration={selectedIntegration}
                    isOpen={modalOpen}
                    onClose={() => setModalOpen(false)}
                    onSave={handleSaveConfig}
                    onTest={handleTestConnection}
                />
            )}

            {helpIntegration && (
                <IntegrationHelpModal
                    integrationId={helpIntegration.id}
                    integrationName={helpIntegration.name}
                    isOpen={helpModalOpen}
                    onClose={() => setHelpModalOpen(false)}
                />
            )}

            <NoticeModal
                isOpen={modalConfig.isOpen}
                type={modalConfig.type}
                title={modalConfig.title}
                message={modalConfig.message}
                onConfirm={modalConfig.onConfirm}
                onClose={modalConfig.onClose}
                onDecline={modalConfig.onClose}
                confirmText={modalConfig.confirmText}
                declineText={modalConfig.declineText}
                position={modalConfig.position}
                autoClose={modalConfig.type === 'toast'}
                autoCloseTime={3000}
            />
        </div>
    );
};

export default Integrations;
