import React, { useState, useEffect } from 'react';
import { useApi, apiFetch } from '../hooks/useApi';

const TAB_GENERAL = 'general';
const TAB_PAYMENTS = 'payments';

export default function Settings() {
    const { data: settings, loading, refetch } = useApi('settings');
    const [activeTab, setActiveTab] = useState(TAB_GENERAL);
    const [keys, setKeys] = useState({
        stripe_test_public: '',
        stripe_test_secret: '',
        stripe_live_public: '',
        stripe_live_secret: '',
        stripe_mode: 'test',
        engine_mode: 'standalone',
        paypal_client_id: '',
        paypal_secret: '',
        paypal_mode: 'test',
        openai_key: '',
        standalone_store_page_id: 0,
        standalone_checkout_page_id: 0,
        standalone_account_page_id: 0,
        standalone_login_page_id: 0,
        standalone_register_page_id: 0,
        standalone_privacy_policy_page_id: 0,
        checkout_btn_subscribe: 'Subscribe Now',
        checkout_btn_processing: 'Processing...',
        require_subscription_email_verification: false,
    });
    const [saving, setSaving] = useState(false);
    const [generatingPages, setGeneratingPages] = useState(false);
    const [isEditing, setIsEditing] = useState(false);
    const [webhookSetting, setWebhookSetting] = useState(false);
    const [toastMessage, setToastMessage] = useState('');

    useEffect(() => {
        if (settings) {
            setKeys({
                stripe_test_public: settings.stripe_test_public ?? '',
                stripe_test_secret: settings.stripe_test_secret ?? '',
                stripe_live_public: settings.stripe_live_public ?? '',
                stripe_live_secret: settings.stripe_live_secret ?? '',
                stripe_mode: settings.stripe_mode || 'test',
                engine_mode: settings.engine_mode || 'standalone',
                paypal_client_id: settings.paypal_client_id || '',
                paypal_secret: settings.paypal_secret || '',
                paypal_mode: settings.paypal_mode || 'test',
                openai_key: settings.openai_key || '',
                standalone_store_page_id: Number(settings.standalone_store_page_id) || 0,
                standalone_checkout_page_id: Number(settings.standalone_checkout_page_id) || 0,
                standalone_account_page_id: Number(settings.standalone_account_page_id) || 0,
                standalone_login_page_id: Number(settings.standalone_login_page_id) || 0,
                standalone_register_page_id: Number(settings.standalone_register_page_id) || 0,
                standalone_privacy_policy_page_id: Number(settings.standalone_privacy_policy_page_id) || 0,
                checkout_btn_subscribe: settings.checkout_btn_subscribe || 'Subscribe Now',
                checkout_btn_processing: settings.checkout_btn_processing || 'Processing...',
                require_subscription_email_verification: !!settings.require_subscription_email_verification,
            });
        }
    }, [settings]);

    const pageChoices = settings?.checkout_page_choices ?? [];

    const standalonePagesIncomplete =
        keys.engine_mode === 'standalone' &&
        (!keys.standalone_store_page_id ||
            !keys.standalone_checkout_page_id ||
            !keys.standalone_account_page_id ||
            !keys.standalone_login_page_id ||
            !keys.standalone_register_page_id);

    const hasAnyStripeKey =
        !!(keys.stripe_test_public || keys.stripe_live_public);
    const activeStripePublic =
        keys.stripe_mode === 'live' ? keys.stripe_live_public : keys.stripe_test_public;
    const activeStripeSecret =
        keys.stripe_mode === 'live' ? keys.stripe_live_secret : keys.stripe_test_secret;

    const setActiveStripePublic = (value) => {
        setKeys((prev) =>
            prev.stripe_mode === 'live'
                ? { ...prev, stripe_live_public: value }
                : { ...prev, stripe_test_public: value }
        );
    };

    const setActiveStripeSecret = (value) => {
        setKeys((prev) =>
            prev.stripe_mode === 'live'
                ? { ...prev, stripe_live_secret: value }
                : { ...prev, stripe_test_secret: value }
        );
    };

    const handleSaveMode = async (mode) => {
        setSaving(true);
        try {
            await apiFetch('settings', {
                method: 'POST',
                body: JSON.stringify({ ...keys, stripe_mode: mode }),
            });
            setKeys({ ...keys, stripe_mode: mode });
            setToastMessage(`Switched to ${mode} mode!`);
            setTimeout(() => setToastMessage(''), 3000);
            refetch();
        } catch {
            alert('Failed to switch mode');
        } finally {
            setSaving(false);
        }
    };

    const handleWebhookSetup = async () => {
        setWebhookSetting(true);
        try {
            const res = await apiFetch('settings/webhook', { method: 'POST' });
            alert(res.message || 'Webhook setup finished');
            refetch();
        } catch {
            alert('Failed to setup webhook automatically. Check Keys.');
        } finally {
            setWebhookSetting(false);
        }
    };

    const handleGenerateStandalonePages = async () => {
        setGeneratingPages(true);
        try {
            await apiFetch('settings/generate-standalone-pages', { method: 'POST', body: '{}' });
            setToastMessage(
                'Default pages were created or found by slug; empty page slots in settings were filled. First run also enables “Anyone can register” in WordPress General settings.'
            );
            setTimeout(() => setToastMessage(''), 4000);
            refetch();
        } catch (err) {
            const msg =
                err?.message ||
                (typeof err === 'string' ? err : 'Could not generate pages. Save standalone mode first.');
            alert(msg);
        } finally {
            setGeneratingPages(false);
        }
    };

    const handleSave = async (e) => {
        e.preventDefault();
        setSaving(true);
        try {
            await apiFetch('settings', {
                method: 'POST',
                body: JSON.stringify(keys),
            });
            setIsEditing(false);
            setToastMessage('Settings saved successfully!');
            setTimeout(() => setToastMessage(''), 3000);
            refetch();
        } catch {
            alert('Failed to save settings');
        } finally {
            setSaving(false);
        }
    };

    const tabBtn = (id, label) => (
        <button
            key={id}
            type="button"
            onClick={() => setActiveTab(id)}
            className={`px-4 py-2.5 text-sm font-semibold border-b-2 -mb-px transition-colors cursor-pointer ${
                activeTab === id
                    ? 'border-[#2271b1] text-[#2271b1]'
                    : 'border-transparent text-[#646970] hover:text-[#1d2327]'
            }`}
        >
            {label}
        </button>
    );

    return (
        <div className="p-6 pb-20">
            <div className="flex justify-between items-center mb-4">
                <h1 className="text-3xl font-bold text-[#1d2327]">Settings</h1>
                <button
                    type="button"
                    onClick={handleSave}
                    disabled={saving}
                    className="bg-[#2271b1] hover:bg-[#135e96] text-white px-6 py-2 rounded-md font-medium text-sm transition-all cursor-pointer disabled:opacity-50"
                >
                    {saving ? 'Saving...' : 'Save Settings'}
                </button>
            </div>

            <div className="flex gap-6 border-b border-[#c3c4c7] mb-6">{tabBtn(TAB_GENERAL, 'General')}{tabBtn(TAB_PAYMENTS, 'Payments')}</div>

            {loading ? (
                <p className="text-[#646970]">Loading settings...</p>
            ) : (
                <div className="space-y-6">
                    {activeTab === TAB_GENERAL && (
                        <>
                            <div className="p-5 border border-[#c3c4c7] rounded-md bg-white shadow-sm">
                                <div className="mb-4">
                                    <h3 className="font-bold text-[#1d2327] flex items-center gap-2">
                                        <span className="w-3 h-3 rounded-full bg-[#2271b1]" />
                                        Subscription engine
                                    </h3>
                                    <p className="text-sm text-[#646970] mt-1">
                                        Choose how subscriptions integrate with your site checkout.
                                    </p>
                                </div>
                                <div className="mt-4 flex flex-col lg:flex-row gap-4">
                                    <label
                                        className={`flex-1 p-4 border rounded-md cursor-pointer transition-all ${
                                            keys.engine_mode === 'standalone'
                                                ? 'border-[#2271b1] bg-[#f0f6fc] shadow-sm'
                                                : 'border-[#dcdcde] hover:bg-[#f6f7f7]'
                                        }`}
                                    >
                                        <div className="flex items-center gap-2 font-bold mb-1 text-[#1d2327]">
                                            <input
                                                type="radio"
                                                checked={keys.engine_mode === 'standalone'}
                                                onChange={() => setKeys({ ...keys, engine_mode: 'standalone' })}
                                            />
                                            Standalone mode (default)
                                        </div>
                                        <p className="text-xs text-[#646970] ml-6">
                                            Uses the native Invizo checkout shortcode. Best for simple memberships and
                                            sites without WooCommerce checkout.
                                        </p>
                                    </label>
                                    <label
                                        className={`flex-1 p-4 border rounded-md cursor-pointer transition-all ${
                                            keys.engine_mode === 'woocommerce'
                                                ? 'border-[#2271b1] bg-[#f0f6fc] shadow-sm'
                                                : 'border-[#dcdcde] hover:bg-[#f6f7f7]'
                                        }`}
                                    >
                                        <div className="flex items-center gap-2 font-bold mb-1 text-[#1d2327]">
                                            <input
                                                type="radio"
                                                checked={keys.engine_mode === 'woocommerce'}
                                                onChange={() => setKeys({ ...keys, engine_mode: 'woocommerce' })}
                                            />
                                            WooCommerce
                                        </div>
                                        <p className="text-xs text-[#646970] ml-6">
                                            Integrates with WooCommerce checkout. Subscription products bill through your
                                            WooCommerce flow.
                                        </p>
                                    </label>
                                </div>
                            </div>

                            {keys.engine_mode === 'standalone' && (
                                <>
                                    <div className="p-5 border border-[#c3c4c7] rounded-md bg-white shadow-sm">
                                        <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4 mb-4">
                                            <div>
                                                <h3 className="font-bold text-[#1d2327] mb-1">Standalone customer pages</h3>
                                                <p className="text-sm text-[#646970] max-w-2xl">
                                                    Map each flow to a published page with the matching shortcode. New site?
                                                    Generate default pages (creates missing pages by slug, assigns them
                                                    here, and enables{' '}
                                                    <strong className="font-semibold text-[#1d2327]">
                                                        Settings → General → Membership → Anyone can register
                                                    </strong>
                                                    ).
                                                </p>
                                            </div>
                                            <button
                                                type="button"
                                                onClick={handleGenerateStandalonePages}
                                                disabled={generatingPages}
                                                className="shrink-0 px-4 py-2.5 bg-[#00a32a] hover:bg-[#008a20] text-white rounded-md text-sm font-semibold cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                                            >
                                                {generatingPages ? 'Working…' : 'Generate default pages'}
                                            </button>
                                        </div>
                                        {standalonePagesIncomplete && !generatingPages && (
                                            <p className="text-xs text-[#856404] bg-[#fff8e5] border border-[#f0e6c8] rounded px-3 py-2 mb-4">
                                                One or more pages are unset. Use the button above or choose pages
                                                manually, then save.
                                            </p>
                                        )}

                                        {[
                                            {
                                                key: 'standalone_store_page_id',
                                                urlKey: 'standalone_store_page_url',
                                                title: 'Store page',
                                                shortcode: '[invizo_store]',
                                                hint: 'Grid of all plans; links go to checkout with ?plan=ID.',
                                            },
                                            {
                                                key: 'standalone_checkout_page_id',
                                                urlKey: 'standalone_checkout_page_url',
                                                title: 'Checkout page',
                                                shortcode: '[invizo_checkout]',
                                                hint: 'Stripe checkout for the plan in the URL.',
                                            },
                                            {
                                                key: 'standalone_account_page_id',
                                                urlKey: 'standalone_account_page_url',
                                                title: 'My account / dashboard',
                                                shortcode: '[invizo_account]',
                                                hint: 'Subscriptions, profile, and payment methods (Stripe portal).',
                                            },
                                            {
                                                key: 'standalone_login_page_id',
                                                urlKey: 'standalone_login_page_url',
                                                title: 'Login page',
                                                shortcode: '[invizo_auth view="login"]',
                                                hint: 'Custom login form; links to the register page when set.',
                                            },
                                            {
                                                key: 'standalone_register_page_id',
                                                urlKey: 'standalone_register_page_url',
                                                title: 'Register page',
                                                shortcode: '[invizo_auth view="register"]',
                                                hint: 'Registration only; links back to login.',
                                            },
                                            {
                                                key: 'standalone_privacy_policy_page_id',
                                                urlKey: 'standalone_privacy_policy_page_url',
                                                title: 'Privacy policy page (optional)',
                                                shortcode: 'Any page with your policy text',
                                                hint: 'If set, checkout requires acceptance of this policy before payment.',
                                            },
                                        ].map((row) => {
                                            const savedId = Number(settings?.[row.key] || 0);
                                            const currentId = Number(keys[row.key] || 0);
                                            const viewUrl = settings?.[row.urlKey] || '';
                                            return (
                                                <div
                                                    key={row.key}
                                                    className="mb-5 pb-5 border-b border-[#f0f0f1] last:border-0 last:pb-0 last:mb-0"
                                                >
                                                    <h4 className="font-semibold text-[#1d2327] mb-1">{row.title}</h4>
                                                    <p className="text-sm text-[#646970] mb-2">
                                                        Shortcode:{' '}
                                                        <code className="text-xs bg-[#f0f0f1] px-1 py-0.5 rounded">
                                                            {row.shortcode}
                                                        </code>
                                                        . {row.hint}
                                                    </p>
                                                    <label className="block text-sm font-medium text-[#1d2327] mb-1">
                                                        Page
                                                    </label>
                                                    <select
                                                        value={keys[row.key] || ''}
                                                        onChange={(e) =>
                                                            setKeys({
                                                                ...keys,
                                                                [row.key]: parseInt(e.target.value, 10) || 0,
                                                            })
                                                        }
                                                        className="max-w-xl w-full border border-[#8c8f94] rounded px-3 py-2 text-sm bg-white focus:border-[#2271b1] focus:ring-1 focus:ring-[#2271b1] outline-none"
                                                    >
                                                        <option value="">— Select a page —</option>
                                                        {pageChoices.map((p) => (
                                                            <option key={p.id} value={p.id}>
                                                                {p.title}
                                                            </option>
                                                        ))}
                                                    </select>
                                                    {viewUrl && currentId > 0 && currentId === savedId ? (
                                                        <p className="mt-2 text-sm">
                                                            <a
                                                                href={viewUrl}
                                                                target="_blank"
                                                                rel="noopener noreferrer"
                                                                className="text-[#2271b1] hover:underline"
                                                            >
                                                                View page
                                                            </a>
                                                        </p>
                                                    ) : currentId > 0 && currentId !== savedId ? (
                                                        <p className="mt-2 text-xs text-[#646970]">
                                                            Save settings to apply this page.
                                                        </p>
                                                    ) : null}
                                                </div>
                                            );
                                        })}
                                    </div>

                                    <div className="p-5 border border-[#c3c4c7] rounded-md bg-white shadow-sm">
                                        <h3 className="font-bold text-[#1d2327] mb-1">Checkout button labels</h3>
                                        <p className="text-sm text-[#646970] mb-4">
                                            Customize text on the standalone checkout form (main payment button and
                                            processing state if your theme uses the bundled script).
                                        </p>
                                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 max-w-3xl">
                                            <div>
                                                <label className="block text-sm font-medium text-[#1d2327] mb-1">
                                                    Pay / subscribe button
                                                </label>
                                                <input
                                                    value={keys.checkout_btn_subscribe}
                                                    onChange={(e) =>
                                                        setKeys({ ...keys, checkout_btn_subscribe: e.target.value })
                                                    }
                                                    type="text"
                                                    className="w-full border border-[#8c8f94] rounded px-3 py-2 text-sm focus:border-[#2271b1] focus:ring-1 focus:ring-[#2271b1] outline-none"
                                                    placeholder="Subscribe Now"
                                                />
                                            </div>
                                            <div>
                                                <label className="block text-sm font-medium text-[#1d2327] mb-1">
                                                    Processing state (optional)
                                                </label>
                                                <input
                                                    value={keys.checkout_btn_processing}
                                                    onChange={(e) =>
                                                        setKeys({ ...keys, checkout_btn_processing: e.target.value })
                                                    }
                                                    type="text"
                                                    className="w-full border border-[#8c8f94] rounded px-3 py-2 text-sm focus:border-[#2271b1] focus:ring-1 focus:ring-[#2271b1] outline-none"
                                                    placeholder="Processing..."
                                                />
                                            </div>
                                        </div>
                                        <div className="mt-6 pt-6 border-t border-[#f0f0f1] max-w-3xl">
                                            <label className="flex items-start gap-3 cursor-pointer">
                                                <input
                                                    type="checkbox"
                                                    checked={keys.require_subscription_email_verification}
                                                    onChange={(e) =>
                                                        setKeys({
                                                            ...keys,
                                                            require_subscription_email_verification: e.target.checked,
                                                        })
                                                    }
                                                    className="mt-1 w-4 h-4 rounded border-[#8c8f94] text-[#2271b1] focus:ring-[#2271b1]"
                                                />
                                                <span>
                                                    <span className="block text-sm font-semibold text-[#1d2327]">
                                                        Require email confirmation before subscription shows as active
                                                    </span>
                                                    <span className="block text-sm text-[#646970] mt-1">
                                                        After payment, the local status stays <strong>Pending</strong> until
                                                        the customer clicks the link in the email (
                                                        <code className="text-xs bg-[#f0f0f1] px-1 py-0.5 rounded">wp_mail</code>
                                                        ). Stripe billing still runs; this only gates your member area. Use
                                                        MailHog or similar locally to capture messages. Off by default.
                                                    </span>
                                                </span>
                                            </label>
                                        </div>
                                    </div>
                                </>
                            )}
                        </>
                    )}

                    {activeTab === TAB_PAYMENTS && (
                        <div className="p-5 border border-[#c3c4c7] rounded-md bg-white shadow-sm">
                            <div className="flex justify-between items-start mb-4">
                                <div>
                                    <h3 className="font-bold flex items-center gap-2 text-[#1d2327]">
                                        <span
                                            className={`w-3 h-3 rounded-full ${hasAnyStripeKey ? 'bg-green-600' : 'bg-[#d63638]'}`}
                                        />
                                        Stripe
                                    </h3>
                                    <p className="text-sm text-[#646970] mt-1">
                                        Process cards securely. Keys are stored in your WordPress database.
                                    </p>
                                </div>
                                <div className="flex gap-2">
                                    {!isEditing && (
                                        <button
                                            type="button"
                                            onClick={() => setIsEditing(true)}
                                            className="px-4 py-1.5 border border-[#2271b1] text-[#2271b1] bg-[#f6f7f7] rounded-md text-sm font-semibold hover:bg-[#f0f0f1] cursor-pointer"
                                        >
                                            Edit keys
                                        </button>
                                    )}
                                </div>
                            </div>

                            {hasAnyStripeKey && !isEditing && (
                                <div className="mb-4 flex items-center gap-3 bg-[#f6f7f7] border border-[#dcdcde] p-1 rounded-md max-w-fit">
                                    <button
                                        type="button"
                                        onClick={() => handleSaveMode('test')}
                                        className={`px-3 py-1 text-sm font-medium rounded ${
                                            keys.stripe_mode === 'test'
                                                ? 'bg-white shadow-sm ring-1 ring-[#dcdcde]'
                                                : 'text-[#646970]'
                                        }`}
                                    >
                                        Test mode
                                    </button>
                                    <button
                                        type="button"
                                        onClick={() => handleSaveMode('live')}
                                        className={`px-3 py-1 text-sm font-medium rounded ${
                                            keys.stripe_mode === 'live'
                                                ? 'bg-white shadow-sm ring-1 ring-[#dcdcde]'
                                                : 'text-[#646970]'
                                        }`}
                                    >
                                        Live mode
                                    </button>
                                </div>
                            )}

                            {isEditing && (
                                <div className="space-y-4 mb-4">
                                    <div className="p-3 bg-[#f0f6fc] border border-[#c3d9ed] rounded-md mb-4 flex gap-4">
                                        <label className="flex items-center gap-2 text-sm font-medium cursor-pointer">
                                            <input
                                                type="radio"
                                                checked={keys.stripe_mode === 'test'}
                                                onChange={() => setKeys({ ...keys, stripe_mode: 'test' })}
                                                name="st_mode"
                                            />
                                            Test mode
                                        </label>
                                        <label className="flex items-center gap-2 text-sm font-medium cursor-pointer">
                                            <input
                                                type="radio"
                                                checked={keys.stripe_mode === 'live'}
                                                onChange={() => setKeys({ ...keys, stripe_mode: 'live' })}
                                                name="st_mode"
                                            />
                                            Live mode
                                        </label>
                                    </div>
                                    <p className="text-xs text-[#646970] -mt-2 mb-2">
                                        Keys are stored separately for test and live. Switch the mode above to edit the
                                        matching pair (pk_test/sk_test vs pk_live/sk_live).
                                    </p>
                                    <div>
                                        <label className="block text-sm font-medium mb-1 text-[#1d2327]">
                                            Publishable key ({keys.stripe_mode === 'live' ? 'live' : 'test'})
                                        </label>
                                        <input
                                            value={activeStripePublic}
                                            onChange={(e) => setActiveStripePublic(e.target.value)}
                                            type="text"
                                            className="w-full border border-[#8c8f94] rounded-md px-3 py-2 text-sm font-mono focus:ring-1 focus:ring-[#2271b1] outline-none"
                                            placeholder={keys.stripe_mode === 'live' ? 'pk_live_...' : 'pk_test_...'}
                                        />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-medium mb-1 text-[#1d2327]">
                                            Secret key ({keys.stripe_mode === 'live' ? 'live' : 'test'})
                                        </label>
                                        <input
                                            value={activeStripeSecret}
                                            onChange={(e) => setActiveStripeSecret(e.target.value)}
                                            type="password"
                                            className="w-full border border-[#8c8f94] rounded-md px-3 py-2 text-sm font-mono focus:ring-1 focus:ring-[#2271b1] outline-none"
                                            placeholder={keys.stripe_mode === 'live' ? 'sk_live_...' : 'sk_test_...'}
                                        />
                                    </div>
                                    <button
                                        type="button"
                                        onClick={() => setIsEditing(false)}
                                        className="px-4 py-2 border border-[#dcdcde] text-[#50575e] bg-white rounded-md text-sm font-semibold hover:bg-[#f6f7f7] cursor-pointer"
                                    >
                                        Close key editor
                                    </button>
                                </div>
                            )}
                            {!isEditing && settings && settings.webhook_url && (
                                <div className="mt-4 pt-4 border-t border-[#dcdcde]">
                                    <label className="block text-sm font-medium mb-1 text-[#1d2327]">Webhook URL</label>
                                    <div className="flex gap-2 mb-2">
                                        <input
                                            readOnly
                                            value={settings.webhook_url}
                                            className="w-full bg-[#f6f7f7] border border-[#dcdcde] rounded-md px-3 py-2 text-xs font-mono text-[#50575e]"
                                        />
                                    </div>
                                    <div className="flex items-center justify-between mt-2 flex-wrap gap-2">
                                        {settings.webhook_secret ? (
                                            <span className="text-xs font-medium text-green-700 bg-green-50 px-2 py-1 rounded border border-green-200">
                                                Webhook is configured
                                            </span>
                                        ) : (
                                            <button
                                                type="button"
                                                onClick={handleWebhookSetup}
                                                disabled={webhookSetting || !activeStripeSecret}
                                                className="px-3 py-1.5 bg-[#2271b1] text-white text-xs font-medium rounded hover:bg-[#135e96] disabled:opacity-50 cursor-pointer"
                                            >
                                                {webhookSetting ? 'Setting up…' : 'Auto-setup webhook'}
                                            </button>
                                        )}
                                        {!settings.webhook_secret && (
                                            <span className="text-xs text-[#646970]">Registers Stripe events automatically</span>
                                        )}
                                    </div>
                                </div>
                            )}
                        </div>
                    )}
                </div>
            )}

            {toastMessage && (
                <div className="fixed bottom-6 right-6 bg-green-700 text-white px-4 py-3 rounded-md shadow-xl z-50 flex items-center gap-2">
                    <svg className="w-5 h-5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7" />
                    </svg>
                    <span className="font-medium text-sm">{toastMessage}</span>
                </div>
            )}
        </div>
    );
}
