/**
 * Shois Chat Button — Settings Page
 *
 * Global settings: widget toggle, integrations, performance, import/export.
 *
 * @package ShoisChatButton
 */
import { useState, useEffect, useCallback } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import DisplayRulesPage from './DisplayRulesPage';

/**
 * Toggle field.
 */
function Toggle({ label, checked, onChange, help, pro }) {
    return (
        <div className="shcb-field-group shcb-field-toggle">
            <label className="shcb-toggle-label">
                <div className="shcb-toggle-text">
                    <span className="shcb-field-label">
                        {label}
                        {pro && <span className="shcb-pro-badge">PRO</span>}
                    </span>
                    {help && <p className="shcb-field-help">{help}</p>}
                </div>
                <div className="shcb-toggle-control-wrap">
                    <input
                        type="checkbox"
                        checked={checked}
                        onChange={(e) => onChange(e.target.checked)}
                        disabled={pro}
                    />
                    <span className="shcb-toggle-slider"></span>
                </div>
            </label>
        </div>
    );
}

/**
 * SettingsPage — Main app settings.
 *
 * @param {Object} props
 * @param {boolean} props.widgetActive Whether widget is active globally.
 * @param {Function} props.onWidgetToggle Global toggle handler.
 *
 * @return {JSX.Element} Settings page.
 */
export default function SettingsPage({ widgetActive, onWidgetToggle }) {
    const [settings, setSettings] = useState({});
    const [saving, setSaving] = useState(false);
    const [saved, setSaved] = useState(false);

    useEffect(() => {
        setSettings(prev => ({ ...prev, active: widgetActive }));
    }, [widgetActive]);

    useEffect(() => {
        apiFetch({ path: '/shois-chat/v1/settings' })
            .then((data) => setSettings(data || {}))
            .catch(() => { });
    }, []);

    const update = useCallback((key, value) => {
        setSettings((prev) => ({ ...prev, [key]: value }));
        setSaved(false);
    }, []);

    const updateNested = useCallback((parent, key, value) => {
        setSettings((prev) => ({
            ...prev,
            [parent]: { ...(prev[parent] || {}), [key]: value },
        }));
        setSaved(false);
    }, []);

    const handleSave = () => {
        setSaving(true);
        apiFetch({
            path: '/shois-chat/v1/settings',
            method: 'POST',
            data: settings,
        })
            .then(() => {
                setSaved(true);
                setTimeout(() => setSaved(false), 2000);
            })
            .catch(() => { })
            .finally(() => setSaving(false));
    };

    const handleExport = () => {
        apiFetch({ path: '/shois-chat/v1/export' })
            .then((data) => {
                const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = 'shois-chat-button-export.json';
                a.click();
                URL.revokeObjectURL(url);
            })
            .catch(() => { });
    };

    const handleImport = (e) => {
        const file = e.target.files[0];
        if (!file) return;
        const reader = new FileReader();
        reader.onload = (ev) => {
            try {
                const data = JSON.parse(ev.target.result);
                apiFetch({
                    path: '/shois-chat/v1/import',
                    method: 'POST',
                    data,
                })
                    .then(() => window.location.reload())
                    .catch(() => { });
            } catch (err) {
                /* Invalid JSON */
            }
        };
        reader.readAsText(file);
    };

    const integrations = settings?.integrations || {};
    const performance = settings?.performance || {};

    return (
        <div className="shcb-settings-page">
            <div className="shcb-settings-tab-content">
                <div>
                    { /* Global Toggle */}
                    <div className="shcb-modern-card">
                        <div className="shcb-modern-card-header">
                            <span>⚡</span>
                            <h3>{__('General', 'shois-chat-button')}</h3>
                        </div>

                        <Toggle
                            label={__('Enable Chat Widget', 'shois-chat-button')}
                            checked={widgetActive}
                            onChange={() => onWidgetToggle()}
                            help={__('Master switch. Disabling this hides the widget on all pages.', 'shois-chat-button')}
                        />
                    </div>

                    <div style={{ marginTop: '24px' }}>
                        <DisplayRulesPage />
                    </div>

                    { /* Integrations */}
                    <div className="shcb-modern-card" style={{ marginTop: '24px' }}>
                        <div className="shcb-modern-card-header">
                            <span>🔗</span>
                            <h3>{__('Integrations', 'shois-chat-button')}</h3>
                        </div>

                        <Toggle
                            label={__('Google Analytics 4 (GA4)', 'shois-chat-button')}
                            checked={integrations.ga4}
                            onChange={(v) => updateNested('integrations', 'ga4', v)}
                            help={__('Automatically sends "chat_widget_click" events to your existing GA4 installation (e.g. Site Kit). No Measurement ID required.', 'shois-chat-button')}
                        />

                        <Toggle
                            label={__('Facebook Pixel', 'shois-chat-button')}
                            checked={integrations.fb_pixel}
                            onChange={(v) => updateNested('integrations', 'fb_pixel', v)}
                            help={__('Fires a standard "Contact" event automatically if the Facebook Pixel is already installed on your site.', 'shois-chat-button')}
                        />

                        <Toggle
                            label={__('Google Tag Manager', 'shois-chat-button')}
                            checked={integrations.gtm}
                            onChange={(v) => updateNested('integrations', 'gtm', v)}
                            help={__('Pushes a custom "shcb_platform_click" event to your existing GTM dataLayer.', 'shois-chat-button')}
                        />
                    </div>

                    { /* Performance */}
                    <div className="shcb-modern-card">
                        <div className="shcb-modern-card-header">
                            <span>🚀</span>
                            <h3>{__('Performance', 'shois-chat-button')}</h3>
                        </div>

                        <Toggle
                            label={__('Hide for Admins', 'shois-chat-button')}
                            checked={performance.hide_for_admins}
                            onChange={(v) => updateNested('performance', 'hide_for_admins', v)}
                            help={__('Hide the widget for logged-in administrators.', 'shois-chat-button')}
                        />
                    </div>

                    { /* Import / Export */}
                    <div className="shcb-modern-card">
                        <div className="shcb-modern-card-header">
                            <span>📦</span>
                            <h3>{__('Import / Export', 'shois-chat-button')}</h3>
                        </div>

                        <div className="shcb-import-export-actions">
                            <button className="shcb-btn shcb-btn-secondary" onClick={handleExport} type="button">
                                ⬇ {__('Export Settings', 'shois-chat-button')}
                            </button>

                            <label className="shcb-btn shcb-btn-secondary shcb-import-btn">
                                ⬆ {__('Import Settings', 'shois-chat-button')}
                                <input type="file" accept=".json" onChange={handleImport} style={{ display: 'none' }} />
                            </label>
                        </div>
                    </div>

                    { /* Save Bar */}
                    <div className="shcb-settings-save-bar">
                        {saved && <span className="shcb-saved-indicator">✓ {__('Settings saved', 'shois-chat-button')}</span>}
                        <button
                            className="shcb-btn shcb-btn-primary"
                            onClick={handleSave}
                            disabled={saving}
                            type="button"
                        >
                            {saving ? __('Saving...', 'shois-chat-button') : __('Save Settings', 'shois-chat-button')}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
}
