// Tags — controlled vocabulary for segmenting accounts. Tag state stays
// lifted in MainApp (the accounts landing's filter chips read the same
// list), so changes flow up via onTagsChange.

const TagsSection = ({ currentUser, allTags = [], onTagsChange }) => {
    const [newTagName, setNewTagName]   = React.useState('');
    const [newTagColor, setNewTagColor] = React.useState('#3b82f6');
    const [tagSaving, setTagSaving]     = React.useState(false);
    const [editing, setEditing]         = React.useState(null); // { id, name, color } mid-edit

    const handleSaveEdit = async (e) => {
        e.preventDefault();
        if (!editing.name.trim()) return;
        try {
            // Rename is safe end-to-end: the server rewrites the tags_on_paid
            // name snapshots (products + payment links) in the same tx.
            await api.updateTag(editing.id, { name: editing.name.trim(), color: editing.color });
            setEditing(null); onTagsChange && onTagsChange();
        } catch (err) { alert(err.message); }
    };

    const handleCreateTag = async (e) => {
        e.preventDefault();
        if (!newTagName.trim()) return;
        setTagSaving(true);
        try {
            await api.createTag({ name: newTagName.trim(), color: newTagColor });
            setNewTagName(''); onTagsChange && onTagsChange();
        } catch(err) { alert(err.message); }
        finally { setTagSaving(false); }
    };

    const handleDeleteTag = async (tag) => {
        // Name the blast radius — a whole vocabulary once got wiped from here
        // because the confirm didn't say what the delete would touch.
        const n = parseInt(tag.usage_count, 10) || 0;
        const reach = n ? `It's applied to ${n} account${n === 1 ? '' : 's'} and will be removed from all of them.` : 'It isn\'t applied to any accounts.';
        if (!window.confirm(`Delete tag "${tag.name}"? ${reach}`)) return;
        try { await api.deleteTag(tag.id); onTagsChange && onTagsChange(); }
        catch(err) { alert(err.message); }
    };

    return (
        <div className="settings-form">
            <p style={{ fontSize: '0.875rem', color: 'var(--text-3)', marginBottom: '1.25rem' }}>Tags can be applied to accounts for filtering and categorization.</p>
            <form onSubmit={handleCreateTag} 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">Tag Name</label>
                    <input className="form-input" value={newTagName} onChange={e => setNewTagName(e.target.value)} placeholder="e.g. VIP, Wholesale, Prospect…" required />
                </div>
                <div className="form-group">
                    <label className="form-label">Color</label>
                    <ColorSwatchPicker value={newTagColor} onChange={setNewTagColor} />
                </div>
                <button type="submit" className="btn btn-primary btn-small" disabled={tagSaving} style={{ marginBottom: '0.1rem' }}>
                    {tagSaving ? <><i className="fas fa-spinner fa-spin"></i> Creating…</> : <><i className="fas fa-plus"></i> Create Tag</>}
                </button>
            </form>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.625rem' }}>
                {allTags.length === 0
                    ? <p style={{ color: 'var(--text-3)', fontSize: '0.875rem' }}>No tags yet.</p>
                    : allTags.map(t => editing?.id === t.id ? (
                        <form key={t.id} onSubmit={handleSaveEdit} style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', flexWrap: 'wrap', border: '1px solid var(--border)', borderRadius: '0.5rem', padding: '0.4rem 0.6rem' }}>
                            <input className="form-input" style={{ width: 160, padding: '0.3rem 0.5rem' }} value={editing.name} autoFocus
                                onChange={e => setEditing(p => ({ ...p, name: e.target.value }))} />
                            <ColorSwatchPicker value={editing.color} onChange={c => setEditing(p => ({ ...p, color: c }))} />
                            <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={t.id} style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', background: t.color + '18', border: `1px solid ${t.color}44`, borderRadius: '999px', padding: '0.3rem 0.75rem 0.3rem 0.5rem' }}>
                            <span style={{ width: 10, height: 10, borderRadius: '50%', background: t.color, flexShrink: 0 }}></span>
                            <span style={{ fontWeight: 600, fontSize: '0.8125rem', color: t.color }}>{t.name}</span>
                            <span style={{ fontSize: '0.75rem', color: 'var(--text-3)' }}>({t.usage_count})</span>
                            {currentUser.role === 'admin' && (<>
                                <button className="btn-icon-sm" onClick={() => setEditing({ id: t.id, name: t.name, color: t.color })} title="Edit tag" style={{ padding: '0.1rem 0.3rem', fontSize: '0.7rem' }}><i className="fas fa-pencil-alt"></i></button>
                                <button className="btn-icon-sm danger" onClick={() => handleDeleteTag(t)} title="Delete tag" style={{ padding: '0.1rem 0.3rem', fontSize: '0.7rem' }}><i className="fas fa-times"></i></button>
                            </>)}
                        </div>
                    ))
                }
            </div>
        </div>
    );
};
