// Product Categories — controlled vocabulary for inventory classification.
// Same pattern as Tags/Milestones (admin defines, everyone picks): the
// inventory form offers ONLY these, so "Hosting" and "hosting" can never
// drift into two categories. Deleting one never touches existing products —
// they keep the label; it just stops being offered on new records.

const ProductCategoriesSection = ({ currentUser }) => {
    const [cats, setCats]       = React.useState([]);
    const [newName, setNewName] = React.useState('');
    const [saving, setSaving]   = React.useState(false);
    const [editing, setEditing] = React.useState(null); // { id, name } mid-edit

    const handleSaveEdit = async (e) => {
        e.preventDefault();
        if (!editing.name.trim()) return;
        try {
            // Renames the vocabulary entry only — existing products keep their
            // label (snapshot doctrine, same as delete).
            await api.updateProductCategory(editing.id, { name: editing.name.trim() });
            setEditing(null); refresh();
        } catch (err) { alert(err.message); }
    };

    // A failed refresh after a mutation must not show a silently stale list
    // (swallowed-error rule) — surface it with a retry.
    const [loadErr, setLoadErr] = React.useState(false);
    const refresh = () => api.getProductCategories().then(rows => { setCats(rows); setLoadErr(false); }).catch(() => setLoadErr(true));
    React.useEffect(() => { refresh(); }, []);

    const handleCreate = async (e) => {
        e.preventDefault();
        if (!newName.trim()) return;
        setSaving(true);
        try {
            await api.createProductCategory({ name: newName.trim() });
            setNewName(''); refresh();
        } catch (err) { alert(err.message); }
        finally { setSaving(false); }
    };

    const handleDelete = async (c) => {
        if (!window.confirm(`Delete category "${c.name}"? Existing products keep the label — it just stops being offered on new records.`)) return;
        try { await api.deleteProductCategory(c.id); refresh(); }
        catch (err) { alert(err.message); }
    };

    return (
        <div className="settings-form">
            {loadErr && (
                <LoadErrorBanner what="categories" hasData={cats.length > 0} onRetry={refresh} />
            )}
            <p style={{ fontSize: '0.875rem', color: 'var(--text-3)', marginBottom: '1.25rem' }}>
                The categories your inventory is organized under. The product form offers
                exactly this list — define them here once and every record stays consistent.
            </p>
            <form onSubmit={handleCreate} style={{ display: 'flex', gap: '0.75rem', alignItems: 'flex-end', marginBottom: '1.5rem', flexWrap: 'wrap' }}>
                <div className="form-group" style={{ flex: 1, minWidth: 180 }}>
                    <label className="form-label">Category Name</label>
                    <input className="form-input" value={newName} onChange={e => setNewName(e.target.value)} placeholder="e.g. Web Hosting, Hardware, Services…" required />
                </div>
                <button type="submit" className="btn btn-primary btn-small" disabled={saving} style={{ marginBottom: '0.1rem' }}>
                    {saving ? <><i className="fas fa-spinner fa-spin"></i> Creating…</> : <><i className="fas fa-plus"></i> Create Category</>}
                </button>
            </form>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.625rem' }}>
                {cats.length === 0
                    ? <p style={{ color: 'var(--text-3)', fontSize: '0.875rem' }}>No categories yet.</p>
                    : cats.map(c => editing?.id === c.id ? (
                        <form key={c.id} onSubmit={handleSaveEdit} style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', border: '1px solid var(--border)', borderRadius: '0.5rem', padding: '0.4rem 0.6rem' }}>
                            <input className="form-input" style={{ width: 180, padding: '0.3rem 0.5rem' }} value={editing.name} autoFocus
                                onChange={e => setEditing(p => ({ ...p, name: e.target.value }))} />
                            <button type="submit" className="btn btn-primary btn-small"><i className="fas fa-check"></i></button>
                            <button type="button" className="btn btn-secondary btn-small" onClick={() => setEditing(null)}><i className="fas fa-times"></i></button>
                        </form>
                    ) : (
                        <div key={c.id} style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', background: 'var(--surface-2, #1f2937)', border: '1px solid var(--border, #374151)', borderRadius: '999px', padding: '0.3rem 0.75rem 0.3rem 0.75rem' }}>
                            <i className="fas fa-box" style={{ fontSize: '0.7rem', color: 'var(--text-3)' }}></i>
                            <span style={{ fontWeight: 600, fontSize: '0.8125rem' }}>{c.name}</span>
                            <span style={{ fontSize: '0.75rem', color: 'var(--text-3)' }}>({c.usage_count})</span>
                            {currentUser.role === 'admin' && (<>
                                <button className="btn-icon-sm" onClick={() => setEditing({ id: c.id, name: c.name })} title="Rename category" style={{ padding: '0.1rem 0.3rem', fontSize: '0.7rem' }}><i className="fas fa-pencil-alt"></i></button>
                                <button className="btn-icon-sm danger" onClick={() => handleDelete(c)} title="Delete category" style={{ padding: '0.1rem 0.3rem', fontSize: '0.7rem' }}><i className="fas fa-times"></i></button>
                            </>)}
                        </div>
                    ))
                }
            </div>
        </div>
    );
};
