import React, { useState } from 'react';
import ReactSwitchsupport from "react-switch";
import { getNonce } from '../../Helpers';
import TelegramIcon from '@mui/icons-material/Telegram';
import InfoIcon from '@mui/icons-material/Info';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import LaunchIcon from '@mui/icons-material/Launch';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';

const TelegramTab = ({
    leadsinTelegram,
    setLeadsinTelegram,
    telegramBotToken,
    setTelegramBotToken,
    telegramChatId,
    setTelegramChatId,
    setModalConfig,
    closeModal
}) => {
    const [showGuide, setShowGuide] = useState(false);
    const [testingConnection, setTestingConnection] = useState(false);

    // Test Telegram connection
    const testTelegramConnection = () => {
        if (!telegramBotToken || !telegramChatId) {
            setModalConfig({
                isOpen: true,
                type: 'toast',
                title: 'Missing Information',
                message: 'Please enter both Bot Token and Chat ID before testing.',
                position: 'top-right',
                mode: 'error',
            });
            setTimeout(closeModal, 3000);
            return;
        }

        setTestingConnection(true);

        // Send test message via WordPress AJAX
        wp.ajax.send('simpleform_test_telegram', {
            data: {
                nonce: getNonce(),
                bot_token: telegramBotToken,
                chat_id: telegramChatId,
            },
            success(response) {
                setTestingConnection(false);
                setModalConfig({
                    isOpen: true,
                    type: 'toast',
                    title: 'Success!',
                    message: 'Test message sent successfully! Check your Telegram chat.',
                    position: 'top-right',
                    mode: 'success',
                });
                setTimeout(closeModal, 3000);
            },
            error(error) {
                setTestingConnection(false);
                setModalConfig({
                    isOpen: true,
                    type: 'toast',
                    title: 'Connection Failed',
                    message: error.responseJSON?.data?.message || 'Failed to send test message. Please check your Bot Token and Chat ID.',
                    position: 'top-right',
                    mode: 'error',
                });
                setTimeout(closeModal, 3000);
            },
        });
    };

    // Copy text to clipboard
    const copyToClipboard = (text) => {
        navigator.clipboard.writeText(text).then(() => {
            setModalConfig({
                isOpen: true,
                type: 'toast',
                title: 'Copied!',
                message: 'Text copied to clipboard.',
                position: 'top-right',
                mode: 'success',
            });
            setTimeout(closeModal, 2000);
        });
    };

    return (
        <div className="sf-settings-panel">
            <h3 className="review-case-title">Telegram Integration</h3>
            <p className="settings-description">Send form submissions directly to your Telegram chat or channel</p>

            <div className="floating-widgets">
                {/* Enable/Disable Toggle */}
                <div className="wpnts-switch-review">
                    <label className="form-feature-heading" htmlFor="leadsinTelegram">
                        <TelegramIcon className="telegram-icon" style={{ marginRight: '8px', color: '#0088cc' }} />
                        Get SimpleForm leads in Telegram:
                    </label>
                    <ReactSwitchsupport
                        checked={leadsinTelegram}
                        className="leadsinTelegram"
                        name="leadsinTelegram"
                        id="leadsinTelegram"
                        onChange={(checked) => setLeadsinTelegram(checked)}
                    />
                </div>

                {/* Configuration Fields */}
                {leadsinTelegram && (
                    <>
                        <div className="formInput">
                            <label className="form-feature-sub-heading" htmlFor="telegram-bot-token">
                                Telegram Bot Token
                                <button
                                    type="button"
                                    className="help-btn"
                                    onClick={() => setShowGuide(!showGuide)}
                                    title="Show setup guide"
                                    style={{ marginLeft: '10px', background: 'none', border: 'none', color: '#0088cc', cursor: 'pointer' }}
                                >
                                    <InfoIcon />
                                </button>
                            </label>
                            <div className="wpnts-setting">
                                <input
                                    type="password"
                                    className="telegramBotToken"
                                    id="telegram-bot-token"
                                    name="telegramBotToken"
                                    value={telegramBotToken}
                                    onChange={(e) => setTelegramBotToken(e.target.value)}
                                    placeholder="Enter your Telegram Bot Token"
                                />
                            </div>
                        </div>

                        <div className="formInput">
                            <label className="form-feature-sub-heading" htmlFor="telegram-chat-id">Telegram Chat ID</label>
                            <div className="wpnts-setting">
                                <input
                                    type="text"
                                    className="telegramChatId"
                                    id="telegram-chat-id"
                                    name="telegramChatId"
                                    value={telegramChatId}
                                    onChange={(e) => setTelegramChatId(e.target.value)}
                                    placeholder="Enter your Chat ID (e.g., -1001234567890)"
                                />
                            </div>
                        </div>

                        {/* Test Connection Button */}
                        <div className="formInput">
                            <button
                                type="button"
                                onClick={testTelegramConnection}
                                disabled={testingConnection || !telegramBotToken || !telegramChatId}
                                className={`test-telegram-btn ${testingConnection ? 'testing' : ''}`}
                                style={{
                                    background: testingConnection ? '#6c757d' : 'linear-gradient(135deg, #28a745, #20c997)',
                                    color: 'white',
                                    border: 'none',
                                    padding: '12px 20px',
                                    borderRadius: '8px',
                                    fontWeight: '600',
                                    cursor: testingConnection ? 'wait' : 'pointer',
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '10px',
                                    fontSize: '0.95rem',
                                    transition: 'all 0.2s ease'
                                }}
                            >
                                {testingConnection ? (
                                    <>
                                        <div className="spinner" style={{
                                            width: '16px',
                                            height: '16px',
                                            border: '2px solid transparent',
                                            borderTop: '2px solid white',
                                            borderRadius: '50%',
                                            animation: 'spin 1s linear infinite'
                                        }}></div>
                                        Testing Connection...
                                    </>
                                ) : (
                                    <>
                                        <CheckCircleIcon />
                                        Test Connection
                                    </>
                                )}
                            </button>
                        </div>

                        <div className="seperationLine">
                            <hr />
                            <br />
                        </div>
                    </>
                )}
                </div>

                {/* Setup Guide */}
                {showGuide && (
                    <div className="setup-guide">
                        <div className="guide-header">
                            <h4>📚 Telegram Bot Setup Guide</h4>
                            <button
                                type="button"
                                onClick={() => setShowGuide(false)}
                                className="close-guide-btn"
                            >
                                ×
                            </button>
                        </div>

                        <div className="guide-content">
                            <div className="guide-step">
                                <div className="step-number">1</div>
                                <div className="step-content">
                                    <h5>Create a Telegram Bot</h5>
                                    <p>Open Telegram and search for <strong>@BotFather</strong></p>
                                    <div className="code-block">
                                        <code>/newbot</code>
                                        <button onClick={() => copyToClipboard('/newbot')} className="copy-btn">
                                            <ContentCopyIcon />
                                        </button>
                                    </div>
                                    <p>Follow the instructions to create your bot and get the <strong>Bot Token</strong></p>
                                    <a
                                        href="https://t.me/botfather"
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="external-link"
                                    >
                                        Open BotFather <LaunchIcon />
                                    </a>
                                </div>
                            </div>

                            <div className="guide-step">
                                <div className="step-number">2</div>
                                <div className="step-content">
                                    <h5>Get Your Chat ID</h5>
                                    <p><strong>For Personal Chat:</strong></p>
                                    <ol>
                                        <li>Search for <strong>@userinfobot</strong> on Telegram</li>
                                        <li>Start the bot and it will show your Chat ID</li>
                                    </ol>
                                    <a
                                        href="https://t.me/userinfobot"
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="external-link"
                                    >
                                        Open UserInfoBot <LaunchIcon />
                                    </a>

                                    <p><strong>For Group/Channel:</strong></p>
                                    <ol>
                                        <li>Add your bot to the group/channel</li>
                                        <li>Make your bot an admin (for channels)</li>
                                        <li>Send a message in the group</li>
                                        <li>Visit this URL (replace YOUR_BOT_TOKEN):</li>
                                    </ol>
                                    <div className="code-block">
                                        <code>https://api.telegram.org/botYOUR_BOT_TOKEN/getUpdates</code>
                                        <button
                                            onClick={() => copyToClipboard('https://api.telegram.org/botYOUR_BOT_TOKEN/getUpdates')}
                                            className="copy-btn"
                                        >
                                            <ContentCopyIcon />
                                        </button>
                                    </div>
                                    <p>Look for the {"{\"chat\":{\"id\": value}"} in the response</p>
                                </div>
                            </div>

                            <div className="guide-step">
                                <div className="step-number">3</div>
                                <div className="step-content">
                                    <h5>Configure & Test</h5>
                                    <p>Enter your Bot Token and Chat ID above, then click "Test Connection" to verify everything works!</p>
                                </div>
                            </div>
                        </div>

                        <div className="guide-footer">
                            <div className="info-box">
                                <InfoIcon />
                                <div>
                                    <strong>Security Note:</strong> Keep your Bot Token secure and never share it publicly.
                                    Your Chat ID can be negative for groups/channels (e.g., -1001234567890).
                                </div>
                            </div>
                        </div>
                    </div>
                )}

                {/* Feature Preview */}
                {leadsinTelegram && telegramBotToken && telegramChatId && (
                    <div className="feature-preview">
                        <h4>📱 What you'll receive:</h4>
                        <div className="preview-message">
                            <div className="telegram-message">
                                <div className="message-header">
                                    <TelegramIcon className="telegram-logo" />
                                    <span>Your Bot</span>
                                </div>
                                <div className="message-content">
                                    <strong>🔔 New Form Submission</strong><br />
                                    📋 Form ID: <code>123</code><br />
                                    📅 Date: <code>2024-01-15 10:30:00</code><br /><br />

                                    <strong>📝 Form Data:</strong><br />
                                    • <strong>Name:</strong> John Doe<br />
                                    • <strong>Email:</strong> john@example.com<br />
                                    • <strong>Message:</strong> Hello, I'm interested in your services<br /><br />

                                    <strong>📊 Additional Info:</strong><br />
                                    • <strong>IP:</strong> 192.168.1.1<br />
                                    • <strong>Country:</strong> United States<br /><br />

                                    🚀 Powered by FormFlow
                                </div>
                            </div>
                        </div>
                    </div>
                )}
            </div>
            );
        };

export default TelegramTab;