import React, { useState, useEffect } from 'react';
import { useAdmin } from '../../context/AdminContext';
import { MANAGEMENT_URL } from '../../auth/authConfig';

export default function HelpPanel() {
    const { sessionToken } = useAdmin();
    const { apiCall } = useAdmin();
    const [items, setItems]     = useState([]);
    const [loading, setLoading] = useState(true);
    const [open, setOpen]       = useState(null);
    const [search, setSearch]   = useState('');

    useEffect(() => {
        (async () => {
            setLoading(true);
            // Help content lives on Management API
            const res = await apiCall(`${MANAGEMENT_URL}/api/help/list`, 'POST', { includeInactive: false });
            const list = Array.isArray(res?.items) ? res.items :
                         Array.isArray(res?.data)  ? res.data  : [];
            setItems(list);
            setLoading(false);
        })();
    }, [apiCall]);

    const filtered = items.filter(item => !search || 
        (item.title || item.Title || '').toLowerCase().includes(search.toLowerCase()) ||
        (item.content || item.Content || '').toLowerCase().includes(search.toLowerCase()));

    if (loading) return <div className="loading-message">Loading help content…</div>;

    return (
        <div style={{ maxWidth: 760 }}>
            <h2 style={{ fontSize: 20, fontWeight: 700, marginBottom: 16 }}>Help & FAQs</h2>
            <input
                className="form-input"
                style={{ marginBottom: 20, maxWidth: 400 }}
                placeholder="Search help articles…"
                value={search}
                onChange={e => setSearch(e.target.value)}
            />
            {filtered.length === 0 ? (
                <div className="empty-state">No help articles found.</div>
            ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                    {filtered.map((item, idx) => {
                        const id    = item.helpId || item.HelpId || idx;
                        const title = item.title || item.Title || 'Article';
                        const body  = item.content || item.Content || '';
                        const isOpen = open === id;
                        return (
                            <div key={id} style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 8, overflow: 'hidden' }}>
                                <button
                                    onClick={() => setOpen(isOpen ? null : id)}
                                    style={{ width: '100%', padding: '14px 18px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: 'none', border: 'none', cursor: 'pointer', textAlign: 'left' }}
                                >
                                    <span style={{ fontWeight: 600, fontSize: 14, color: '#0f172a' }}>{title}</span>
                                    <span style={{ color: '#94a3b8', fontSize: 18, lineHeight: 1 }}>{isOpen ? '−' : '+'}</span>
                                </button>
                                {isOpen && (
                                    <div style={{ padding: '0 18px 16px', fontSize: 14, color: '#475569', lineHeight: 1.6 }}>
                                        {body}
                                    </div>
                                )}
                            </div>
                        );
                    })}
                </div>
            )}
        </div>
    );
}
