/**
 * Shois Chat Button — Display Rules Page
 *
 * Show/hide mode toggle, rule list with type selectors,
 * add/remove rules, and save via REST API.
 *
 * @package ShoisChatButton
 */
import { useState, useEffect, useMemo } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import CustomSelect from '../components/CustomSelect';

/**
 * All available rule types grouped.
 */
const RULE_GROUPS = {
    general: {
        label: __('General', 'shois-chat-button'),
        rules: [
            { type: 'entire_site', label: __('Entire Site', 'shois-chat-button'), hasValue: false },
            { type: 'front_page', label: __('Front Page', 'shois-chat-button'), hasValue: false },
            { type: 'blog_page', label: __('Blog Page', 'shois-chat-button'), hasValue: false },
            { type: 'all_posts', label: __('All Posts', 'shois-chat-button'), hasValue: false },
            { type: 'all_pages', label: __('All Pages', 'shois-chat-button'), hasValue: false },
            { type: 'archive', label: __('Archive Pages', 'shois-chat-button'), hasValue: false },
            { type: 'search', label: __('Search Results', 'shois-chat-button'), hasValue: false },
            { type: '404', label: __('404 Page', 'shois-chat-button'), hasValue: false },
        ],
    },
    specific: {
        label: __('Specific', 'shois-chat-button'),
        rules: [
            { type: 'specific_page', label: __('Specific Page (ID)', 'shois-chat-button'), hasValue: true },
            { type: 'specific_post', label: __('Specific Post (ID)', 'shois-chat-button'), hasValue: true },
            { type: 'post_type', label: __('Post Type', 'shois-chat-button'), hasValue: true },
            { type: 'category', label: __('Category (slug)', 'shois-chat-button'), hasValue: true },
            { type: 'tag', label: __('Tag (slug)', 'shois-chat-button'), hasValue: true },
        ],
    },
    url: {
        label: __('URL', 'shois-chat-button'),
        rules: [
            { type: 'url_contains', label: __('URL Contains', 'shois-chat-button'), hasValue: true },
            { type: 'url_exact', label: __('URL Exact Match', 'shois-chat-button'), hasValue: true },
            { type: 'url_starts_with', label: __('URL Starts With', 'shois-chat-button'), hasValue: true },
        ],
    },
    woocommerce: {
        label: __('WooCommerce', 'shois-chat-button'),
        rules: [
            { type: 'woo_shop', label: __('Shop Page', 'shois-chat-button'), hasValue: false },
            { type: 'woo_product', label: __('Product Pages', 'shois-chat-button'), hasValue: false },
            { type: 'woo_cart', label: __('Cart Page', 'shois-chat-button'), hasValue: false },
            { type: 'woo_checkout', label: __('Checkout Page', 'shois-chat-button'), hasValue: false },
            { type: 'woo_category', label: __('Product Category', 'shois-chat-button'), hasValue: true },
        ],
    },
    user: {
        label: __('User', 'shois-chat-button'),
        rules: [
            { type: 'user_logged_in', label: __('Logged In Users', 'shois-chat-button'), hasValue: false },
            { type: 'user_logged_out', label: __('Logged Out Users', 'shois-chat-button'), hasValue: false },
            { type: 'user_role', label: __('User Role', 'shois-chat-button'), hasValue: true },
        ],
    },
    device: {
        label: __('Device', 'shois-chat-button'),
        rules: [
            { type: 'device_mobile', label: __('Mobile Only', 'shois-chat-button'), hasValue: false },
            { type: 'device_desktop', label: __('Desktop Only', 'shois-chat-button'), hasValue: false },
        ],
    },
};

/** Flat lookup of all rule definitions. */
const ALL_RULES_FLAT = {};
Object.values(RULE_GROUPS).forEach((group) => {
    group.rules.forEach((r) => {
        ALL_RULES_FLAT[r.type] = r;
    });
});

/**
 * Single rule row.
 */
function RuleRow({ rule, onUpdate, onRemove, typeOptions }) {
    const def = ALL_RULES_FLAT[rule.type] || {};

    return (
        <div className="shcb-rule-row">
            <label className="shcb-master-toggle shcb-toggle-sm">
                <input
                    type="checkbox"
                    checked={rule.enabled !== false}
                    onChange={(e) => onUpdate({ enabled: e.target.checked })}
                />
                <span className="shcb-toggle-slider"></span>
            </label>

            <CustomSelect
                style={{ width: '130px' }}
                value={rule.match || 'include'}
                onChange={(val) => onUpdate({ match: val })}
                options={[
                    { value: 'include', label: __('Show on', 'shois-chat-button') },
                    { value: 'exclude', label: __('Hide on', 'shois-chat-button') }
                ]}
            />

            <CustomSelect
                style={{ flex: '1' }}
                value={rule.type}
                onChange={(val) => onUpdate({ type: val, value: '' })}
                options={typeOptions}
            />

            {def.hasValue && (
                <input
                    className="shcb-input shcb-rule-value-input"
                    value={rule.value || ''}
                    onChange={(e) => onUpdate({ value: e.target.value })}
                    placeholder={__('Value...', 'shois-chat-button')}
                />
            )}

            <button className="shcb-btn shcb-btn-danger shcb-btn-sm" onClick={onRemove} type="button">✕</button>
        </div>
    );
}

/**
 * DisplayRulesPage — where to show/hide the widget.
 *
 * @return {JSX.Element} Display rules page.
 */
export default function DisplayRulesPage() {
    const [rules, setRules] = useState([]);
    const [saving, setSaving] = useState(false);
    const [saved, setSaved] = useState(false);

    // Prepare rule options once
    const typeOptions = useMemo(() => {
        const opts = [];
        Object.entries(RULE_GROUPS).forEach(([gk, g]) => {
            g.rules.forEach(r => {
                opts.push({ value: r.type, label: r.label, group: g.label });
            });
        });
        return opts;
    }, []);

    useEffect(() => {
        apiFetch({ path: '/shois-chat/v1/rules' })
            .then((data) => {
                if (data) {
                    // Initialize with proper match properties for legacy rules
                    const loadedRules = Array.isArray(data.rules) ? data.rules : [];
                    const legacyMode = data.mode || 'show';

                    const normalized = loadedRules.map(r => ({
                        ...r,
                        match: r.match ? r.match : (legacyMode === 'hide' ? 'exclude' : 'include'),
                    }));

                    if (normalized.length === 0) {
                        setRules([{ match: 'include', type: 'entire_site', value: '', enabled: true }]);
                    } else {
                        setRules(normalized);
                    }
                } else {
                    setRules([{ match: 'include', type: 'entire_site', value: '', enabled: true }]);
                }
            })
            .catch(() => { });
    }, []);

    const isProUser = window.shcbAdmin?.isPro || false;

    const addRule = () => {
        if (!isProUser && rules.length >= 1) {
            return; // blocked — UI shows upsell
        }
        setRules([...rules, { match: 'include', type: 'entire_site', value: '', enabled: true }]);
        setSaved(false);
    };

    const updateRule = (index, updates) => {
        const updated = [...rules];
        updated[index] = { ...updated[index], ...updates };
        setRules(updated);
        setSaved(false);
    };

    const removeRule = (index) => {
        const updated = rules.filter((_, i) => i !== index);
        setRules(updated);
        setSaved(false);
    };

    const handleSave = () => {
        setSaving(true);
        apiFetch({
            path: '/shois-chat/v1/rules',
            method: 'POST',
            data: { mode: 'advanced', rules },
        })
            .then(() => {
                setSaved(true);
                setTimeout(() => setSaved(false), 2000);
            })
            .catch(() => { })
            .finally(() => setSaving(false));
    };

    return (
        <div className="shcb-display-rules-page">
            <div className="shcb-modern-card">
                <div className="shcb-modern-card-header">
                    <span>🎯</span>
                    <h3>{__('Display Rules', 'shois-chat-button')}</h3>
                </div>
                <p className="shcb-tab-description">
                    {__('Control where the chat widget appears on your website. Add rules to show or hide the widget on specific pages.', 'shois-chat-button')}
                </p>

                <div className="shcb-rules-mode" style={{ display: 'none' }}>
                    {/* Mode toggle removed in favor of per-rule include/exclude */}
                </div>
            </div>

            { /* Rules List */}
            <div className="shcb-rules-list">
                {rules.length === 0 && (
                    <div className="shcb-empty-state">
                        <span className="shcb-empty-icon">📍</span>
                        <p>{__('No rules yet. The widget will show on all pages.', 'shois-chat-button')}</p>
                    </div>
                )}

                {rules.map((rule, idx) => (
                    <RuleRow
                        key={idx}
                        rule={rule}
                        onUpdate={(updates) => updateRule(idx, updates)}
                        onRemove={() => removeRule(idx)}
                        typeOptions={typeOptions}
                    />
                ))}
            </div>

            <div className="shcb-rules-actions">
                {(!isProUser && rules.length >= 1) ? (
                    <div className="shcb-pro-upsell-inline" onClick={() => window.dispatchEvent(new CustomEvent('shcb-pro-alert'))} style={{cursor: 'pointer'}}>
                        <span>🔒</span>
                        <span>{__('Multiple display rules requires', 'shois-chat-button')} <strong>PRO</strong></span>
                    </div>
                ) : (
                    <button className="shcb-btn shcb-btn-secondary" onClick={addRule} type="button">
                        + {__('Add Rule', 'shois-chat-button')}
                    </button>
                )}

                <div className="shcb-rules-save">
                    {saved && <span className="shcb-saved-indicator">✓ {__('Saved', 'shois-chat-button')}</span>}
                    <button
                        className="shcb-btn shcb-btn-primary"
                        onClick={handleSave}
                        disabled={saving}
                        type="button"
                    >
                        {saving ? __('Saving...', 'shois-chat-button') : __('Save Rules', 'shois-chat-button')}
                    </button>
                </div>
            </div>
        </div>
    );
}
