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;
}

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 = () => {
        (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;
