// Task Presets — named task lists with relative due dates (migration 0062),
// bound to record EVENTS (0063). A preset with no events bound is manual-
// apply only (from any account's overview, or copied onto an inventory
// item); binding an event makes it automatic — the moment a lead lands /
// a quote goes out / an order is paid, its tasks open on that account.
// Editing or deleting a preset never touches tasks already opened or
// items that copied it (snapshot doctrine — same as categories/tags).
//
// Vocabulary note: "preset" (not "playbook" — implies branching logic we
// don't have; not "cadence" — implies date-driven only). A preset is a
// list; a TRIGGER is what binds it to an event.

const TaskPresetsSection = ({ currentUser }) => {
    const [presets, setPresets] = React.useState([]);
    const [events, setEvents]   = React.useState([]);     // bindable vocabulary (server catalog)
    const [loadErr, setLoadErr] = React.useState(false);
    const [editing, setEditing] = React.useState(null);   // null | { id?, name, tasks, triggers, requires_signoff }
    const [saving, setSaving]   = React.useState(false);
    const [err, setErr]         = React.useState('');

    const refresh = () => api.getTaskPresets().then(rows => { setPresets(rows); setLoadErr(false); }).catch(() => setLoadErr(true));
    React.useEffect(() => { refresh(); api.getEventCatalog().then(setEvents).catch(() => setEvents([])); }, []);

    const blank = { name: '', tasks: [{ title: '', notes: '', due_in_days: 0, auto_close: null }], triggers: [], requires_signoff: false };
    const startNew  = () => { setErr(''); setEditing({ ...blank }); };
    const startEdit = (p) => { setErr(''); setEditing({ id: p.id, name: p.name, tasks: p.tasks.map(t => ({ ...t })), triggers: [...(p.triggers || [])], requires_signoff: !!p.requires_signoff }); };
    const toggleTrigger = (type) => setEditing(p => ({ ...p, triggers: p.triggers.includes(type) ? p.triggers.filter(t => t !== type) : [...p.triggers, type] }));

    const handleSave = async (e) => {
        e.preventDefault();
        setErr('');
        const tasks = editing.tasks.filter(t => (t.title || '').trim() || (t.notes || '').trim());
        if (!editing.name.trim()) return setErr('Preset name is required.');
        if (tasks.length === 0) return setErr('Add at least one task.');
        setSaving(true);
        const body = { name: editing.name.trim(), tasks, triggers: editing.triggers, requires_signoff: editing.requires_signoff };
        try {
            if (editing.id) await api.updateTaskPreset(editing.id, body);
            else            await api.createTaskPreset(body);
            setEditing(null); refresh();
        } catch (ex) { setErr(ex.message); }
        finally { setSaving(false); }
    };

    const handleDelete = async (p) => {
        if (!await confirmAction(`Delete preset "${p.name}"? Tasks already opened and items that copied it keep what they have.`)) return;
        try { await api.deleteTaskPreset(p.id); refresh(); }
        catch (ex) { setErr(ex.message); }
    };

    const isAdmin = currentUser.role === 'admin';
    const label = (type) => (events.find(e => e.type === type) || {}).label || type;
    const groups = [...new Set(events.map(e => e.group))];
    const dueText = (t) => { const d = Number(t.due_in_days) || 0; return d === 0 ? 'now' : d === 7 ? '+1w' : d === 14 ? '+2w' : d === 30 ? '+1m' : `+${d}d`; };

    return (
        <div className="settings-form">
            {loadErr && <LoadErrorBanner what="task presets" hasData={presets.length > 0} onRetry={refresh} />}
            <p style={{ fontSize: '0.875rem', color: 'var(--text-3)', marginBottom: '1.25rem' }}>
                A preset is a named list of tasks with due dates counted from the moment it fires.
                Bind it to events and it runs itself — a web lead arrives, a quote goes out, an order is paid —
                or apply it by hand from any account. Tasks that wait on a reply close themselves when the reply
                is logged, and when the event reverses (order cancelled, quote declined) the open tasks it opened close too.
            </p>
            {err && <div className="form-error" style={{ marginBottom: '0.75rem', color: 'var(--danger, #ef4444)', fontSize: '0.8125rem' }}>{err}</div>}

            {editing ? (
                <form onSubmit={handleSave} style={{ border: '1px solid var(--border)', borderRadius: '0.5rem', padding: '1rem', marginBottom: '1.5rem' }}>
                    <div className="form-group" style={{ maxWidth: 320 }}>
                        <label className="form-label">Preset name</label>
                        <input className="form-input" value={editing.name} autoFocus maxLength={100}
                               placeholder="e.g. New web lead, Order handling, Web launch"
                               onChange={e => setEditing(p => ({ ...p, name: e.target.value }))} />
                    </div>
                    <div className="form-group">
                        <label className="form-label">Tasks, in order</label>
                        <TaskListEditor tasks={editing.tasks} onChange={tasks => setEditing(p => ({ ...p, tasks }))} />
                    </div>
                    <div className="form-group">
                        <label className="form-label">Fires automatically on <span style={{ fontWeight: 400, color: 'var(--text-3)' }}>— none selected = apply by hand only</span></label>
                        {groups.map(g => (
                            <div key={g} className="tag-filter-row" style={{ alignItems: 'center', marginBottom: '0.35rem' }}>
                                <span style={{ fontSize: '0.7rem', color: 'var(--text-3)', width: '9.5rem', textTransform: 'uppercase', letterSpacing: '0.05em' }}>{g}</span>
                                {events.filter(e => e.group === g).map(e => {
                                    const on = editing.triggers.includes(e.type);
                                    return (
                                        <span key={e.type} className="tag-pill tag-filter-chip"
                                              style={on ? { background: 'var(--accent, #3b82f6)', color: '#fff' } : { opacity: 0.8 }}
                                              title={e.reverses?.length ? `${e.type} — also closes open tasks from: ${e.reverses.join(', ')}` : e.type}
                                              onClick={() => toggleTrigger(e.type)}>
                                            {on && <i className="fas fa-check" style={{ fontSize: '0.6rem', marginRight: '0.25rem' }}></i>}{e.label}
                                        </span>
                                    );
                                })}
                            </div>
                        ))}
                    </div>
                    <div className="form-group">
                        <label className="form-label">Completion</label>
                        <div className="seg-control">
                            {[[false, 'Tick to complete'], [true, 'Needs sign-off (initials + what was done)']].map(([v, l]) => (
                                <button key={String(v)} type="button" className={`btn btn-small ${editing.requires_signoff === v ? 'btn-primary' : 'btn-secondary'}`}
                                        onClick={() => setEditing(p => ({ ...p, requires_signoff: v }))}>{l}</button>
                            ))}
                        </div>
                    </div>
                    <div style={{ display: 'flex', gap: '0.5rem' }}>
                        <button type="submit" className="btn btn-primary btn-small" disabled={saving}>
                            {saving ? <><i className="fas fa-spinner fa-spin"></i> Saving…</> : <><i className="fas fa-check"></i> {editing.id ? 'Save preset' : 'Create preset'}</>}
                        </button>
                        <button type="button" className="btn btn-secondary btn-small" onClick={() => setEditing(null)}>Cancel</button>
                    </div>
                </form>
            ) : isAdmin && (
                <button type="button" className="btn btn-primary btn-small" style={{ marginBottom: '1.5rem' }} onClick={startNew}>
                    <i className="fas fa-plus"></i> New preset
                </button>
            )}

            {presets.length === 0
                ? <p style={{ color: 'var(--text-3)', fontSize: '0.875rem' }}>No presets yet.</p>
                : presets.map(p => (
                    <div key={p.id} style={{ border: '1px solid var(--border)', borderRadius: '0.5rem', padding: '0.75rem 1rem', marginBottom: '0.75rem' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', flexWrap: 'wrap' }}>
                            <i className="fas fa-tasks" style={{ color: 'var(--text-3)', fontSize: '0.8rem' }}></i>
                            <span style={{ fontWeight: 600 }}>{p.name}</span>
                            <span style={{ fontSize: '0.75rem', color: 'var(--text-3)' }}>({p.tasks.length} task{p.tasks.length === 1 ? '' : 's'}{p.requires_signoff ? ' · sign-off' : ''})</span>
                            {(p.triggers || []).length
                                ? p.triggers.map(t => <span key={t} className="tag-pill" style={{ background: 'var(--accent-soft, rgba(59,130,246,0.15))', color: 'var(--accent, #3b82f6)' }}><i className="fas fa-bolt" style={{ fontSize: '0.6rem' }}></i> {label(t)}</span>)
                                : <span className="tag-pill" style={{ background: 'var(--surface-2)', color: 'var(--text-3)' }}>manual only</span>}
                            {isAdmin && (<span style={{ marginLeft: 'auto', display: 'flex', gap: '0.25rem' }}>
                                <button className="btn-icon-sm" onClick={() => startEdit(p)} title="Edit preset"><i className="fas fa-pencil-alt"></i></button>
                                <button className="btn-icon-sm danger" onClick={() => handleDelete(p)} title="Delete preset"><i className="fas fa-times"></i></button>
                            </span>)}
                        </div>
                        <ol style={{ margin: '0.5rem 0 0 1.25rem', fontSize: '0.8125rem', color: 'var(--text-2)' }}>
                            {p.tasks.map((t, i) => (
                                <li key={i}>{t.title}
                                    <span style={{ color: 'var(--text-3)' }}> · {dueText(t)}{t.auto_close === 'reply' ? ' · closes on reply' : t.auto_close === 'contact' ? ' · closes on contact' : ''}{t.notes ? ` — ${t.notes}` : ''}</span>
                                </li>
                            ))}
                        </ol>
                    </div>
                ))}
        </div>
    );
};
