import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useAdmin } from '../../context/AdminContext';

// ─── HelpPanel ────────────────────────────────────────────────
// Admin CRUD for contextual help content.
// Manages HelpContent table via /api/admin/help.
//
// Key naming convention: {app}.{section}.{element}
//   client.wizard.budget      client.wizard.objective
//   client.wizard.audience    client.wizard.channels
//   admin.campaigns.pacing    admin.clients.approval
// ─────────────────────────────────────────────────────────────
export default function HelpPanel() {
    const { apiCall } = useAdmin();

    const [items, setItems]         = useState([]);
    const [loading, setLoading]     = useState(true);
    const [error, setError]         = useState(null);
    const [toast, setToast]         = useState(null);   // { msg, type }
    const [showInactive, setShowInactive] = useState(false);

    // Edit state
    const [editKey, setEditKey]     = useState(null);   // helpKey being edited, or 'new'
    const [form, setForm]           = useState({ helpKey: '', title: '', body: '', isActive: true });
    const [saving, setSaving]       = useState(false);
    const [deleting, setDeleting]   = useState(null);   // helpKey being deleted
    const [confirmDelete, setConfirmDelete] = useState(null);

    const bodyRef = useRef(null);

    // ── Toast ──
    const showToast = useCallback((msg, type = 'success') => {
        setToast({ msg, type });
        setTimeout(() => setToast(null), 3000);
    }, []);

    // ── Fetch list ──
    const loadItems = useCallback(async () => {
        setLoading(true);
        setError(null);
        try {
            const res = await apiCall(`/api/admin/help?includeInactive=${showInactive}`);
            if (res.ok) setItems(res.items || []);
            else setError(res.error || 'Failed to load help content');
        } catch {
            setError('Network error loading help content');
        } finally {
            setLoading(false);
        }
    }, [apiCall, showInactive]);

    useEffect(() => { loadItems(); }, [loadItems]);

    // ── Start editing ──
    const startEdit = (item) => {
        setEditKey(item.helpKey);
        setForm({
            helpKey:  item.helpKey,
            title:    item.title,
            body:     item.body,
            isActive: item.isActive,
        });
    };

    const startNew = () => {
        setEditKey('new');
        setForm({ helpKey: '', title: '', body: '', isActive: true });
    };

    const cancelEdit = () => {
        setEditKey(null);
        setForm({ helpKey: '', title: '', body: '', isActive: true });
    };

    // ── Save ──
    const handleSave = async () => {
        if (!form.helpKey.trim()) return showToast('Help key is required', 'error');
        if (!form.title.trim())   return showToast('Title is required', 'error');
        if (!form.body.trim())    return showToast('Body content is required', 'error');

        setSaving(true);
        try {
            const res = await apiCall('/api/admin/help', 'POST', {
                helpKey:  form.helpKey.trim().toLowerCase(),
                title:    form.title.trim(),
                body:     form.body.trim(),
                isActive: form.isActive,
            });

            if (res.ok) {
                showToast(`Saved "${form.helpKey}"`);
                cancelEdit();
                loadItems();
            } else {
                showToast(res.error || 'Save failed', 'error');
            }
        } catch {
            showToast('Network error saving help content', 'error');
        } finally {
            setSaving(false);
        }
    };

    // ── Delete ──
    const handleDelete = async (helpKey) => {
        setDeleting(helpKey);
        try {
            const res = await apiCall(`/api/admin/help/${encodeURIComponent(helpKey)}`, 'DELETE');
            if (res.ok) {
                showToast(`Deleted "${helpKey}"`);
                setConfirmDelete(null);
                loadItems();
            } else {
                showToast(res.error || 'Delete failed', 'error');
            }
        } catch {
            showToast('Network error deleting entry', 'error');
        } finally {
            setDeleting(null);
        }
    };

    // ── Key suggestions ──
    const KEY_SUGGESTIONS = [
        'client.wizard.objective', 'client.wizard.audience',
        'client.wizard.budget',    'client.wizard.channels',
        'client.wizard.creative',  'client.wizard.review',
        'admin.campaigns.status',  'admin.campaigns.pacing',
        'admin.clients.approval',  'admin.clients.status',
    ];

    const unusedSuggestions = KEY_SUGGESTIONS.filter(
        k => !items.find(i => i.helpKey === k)
    );

    // ── Render ──
    return (
        <div className="help-panel">

            {/* Toast */}
            {toast && (
                <div className={`help-panel-toast ${toast.type === 'error' ? 'help-panel-toast-error' : ''}`}>
                    {toast.msg}
                </div>
            )}

            {/* Header */}
            <div className="panel-toolbar">
                <div className="panel-toolbar-left">
                    <h2 className="panel-title">Help Content</h2>
                    <span className="panel-count">{items.length} entries</span>
                </div>
                <div className="panel-toolbar-right">
                    <label className="toggle-label">
                        <input
                            type="checkbox"
                            checked={showInactive}
                            onChange={e => setShowInactive(e.target.checked)}
                        />
                        Show inactive
                    </label>
                    <button className="btn-primary" onClick={startNew}>
                        + New Entry
                    </button>
                </div>
            </div>

            {/* New / edit form */}
            {editKey && (
                <div className="help-edit-card">
                    <div className="help-edit-header">
                        <h3>{editKey === 'new' ? 'New Help Entry' : `Editing: ${editKey}`}</h3>
                        <button className="btn-ghost" onClick={cancelEdit}>Cancel</button>
                    </div>

                    {/* Help key */}
                    <div className="help-form-row">
                        <label className="help-form-label">
                            Help Key
                            <span className="help-form-hint">Lowercase, dots/hyphens only</span>
                        </label>
                        {editKey === 'new' ? (
                            <div>
                                <input
                                    className="form-input"
                                    placeholder="e.g. client.wizard.budget"
                                    value={form.helpKey}
                                    onChange={e => setForm(f => ({ ...f, helpKey: e.target.value.toLowerCase() }))}
                                    style={{ width: '100%', marginBottom: 6 }}
                                />
                                {unusedSuggestions.length > 0 && (
                                    <div className="help-key-suggestions">
                                        <span className="help-form-hint">Suggested:</span>
                                        {unusedSuggestions.slice(0, 5).map(k => (
                                            <button
                                                key={k}
                                                className="help-key-chip"
                                                onClick={() => setForm(f => ({ ...f, helpKey: k }))}
                                            >{k}</button>
                                        ))}
                                    </div>
                                )}
                            </div>
                        ) : (
                            <div className="help-key-display">{form.helpKey}</div>
                        )}
                    </div>

                    {/* Title */}
                    <div className="help-form-row">
                        <label className="help-form-label">Title</label>
                        <input
                            className="form-input"
                            placeholder="Modal heading shown to users"
                            value={form.title}
                            onChange={e => setForm(f => ({ ...f, title: e.target.value }))}
                            style={{ width: '100%' }}
                        />
                    </div>

                    {/* Body */}
                    <div className="help-form-row">
                        <label className="help-form-label">
                            Body (HTML supported)
                            <span className="help-form-hint">
                                &lt;p&gt; &lt;ul&gt; &lt;li&gt; &lt;strong&gt; &lt;h4&gt; tags render in popup
                            </span>
                        </label>
                        <textarea
                            ref={bodyRef}
                            className="form-input help-body-textarea"
                            placeholder="<p>Your help text here…</p>"
                            value={form.body}
                            onChange={e => setForm(f => ({ ...f, body: e.target.value }))}
                            rows={8}
                            style={{ width: '100%', fontFamily: 'var(--font-mono, monospace)', fontSize: 13 }}
                        />
                    </div>

                    {/* Active toggle */}
                    <div className="help-form-row help-form-row-inline">
                        <label className="toggle-label">
                            <input
                                type="checkbox"
                                checked={form.isActive}
                                onChange={e => setForm(f => ({ ...f, isActive: e.target.checked }))}
                            />
                            Active (visible to users)
                        </label>
                        <button
                            className="btn-primary"
                            onClick={handleSave}
                            disabled={saving}
                        >
                            {saving ? 'Saving…' : 'Save Entry'}
                        </button>
                    </div>
                </div>
            )}

            {/* Loading / error */}
            {loading && <div className="loading-state">Loading help content…</div>}
            {error && !loading && (
                <div className="error-message">{error}</div>
            )}

            {/* Entries table */}
            {!loading && !error && items.length === 0 && (
                <div className="empty-state">
                    <p>No help entries yet.</p>
                    <p style={{ fontSize: 13, marginTop: 6, color: 'var(--text-secondary, #666)' }}>
                        Click <strong>+ New Entry</strong> to create your first help entry,
                        or run the seed data in HelpContent.sql to get started quickly.
                    </p>
                </div>
            )}

            {!loading && items.length > 0 && (
                <div className="help-table-wrap">
                    <table className="data-table">
                        <thead>
                            <tr>
                                <th>Help Key</th>
                                <th>Title</th>
                                <th style={{ width: 70 }}>Active</th>
                                <th style={{ width: 80 }}>Updated</th>
                                <th style={{ width: 100 }}></th>
                            </tr>
                        </thead>
                        <tbody>
                            {items.map(item => (
                                <tr key={item.helpKey}
                                    className={!item.isActive ? 'help-row-inactive' : ''}>
                                    <td>
                                        <code className="help-key-code">{item.helpKey}</code>
                                    </td>
                                    <td>{item.title}</td>
                                    <td>
                                        <span className={`status-badge ${item.isActive ? 'status-active' : 'status-inactive'}`}>
                                            {item.isActive ? 'Active' : 'Off'}
                                        </span>
                                    </td>
                                    <td className="text-dim">
                                        {item.updatedAt
                                            ? new Date(item.updatedAt).toLocaleDateString()
                                            : '—'}
                                    </td>
                                    <td>
                                        <div className="row-actions">
                                            <button
                                                className="btn-ghost btn-sm"
                                                onClick={() => startEdit(item)}
                                                disabled={editKey === item.helpKey}
                                            >Edit</button>
                                            {confirmDelete === item.helpKey ? (
                                                <>
                                                    <button
                                                        className="btn-danger btn-sm"
                                                        onClick={() => handleDelete(item.helpKey)}
                                                        disabled={deleting === item.helpKey}
                                                    >
                                                        {deleting === item.helpKey ? '…' : 'Confirm'}
                                                    </button>
                                                    <button
                                                        className="btn-ghost btn-sm"
                                                        onClick={() => setConfirmDelete(null)}
                                                    >✕</button>
                                                </>
                                            ) : (
                                                <button
                                                    className="btn-ghost btn-sm btn-ghost-danger"
                                                    onClick={() => setConfirmDelete(item.helpKey)}
                                                >Del</button>
                                            )}
                                        </div>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            )}
        </div>
    );
}
