// PresetApplyPanel — apply a task preset to the record you're on (trigger
// class 4, 0063) from a small expanding panel: no trip to Settings. Shows
// each preset as a chip with its task count + which events auto-fire it;
// click = open its tasks on this account now (server dedupes titles that
// are already open). Admins get an inline "New preset" form here too —
// create it where you need it, bind events later if you want automation.
//
// Props: accountId, currentUser, onApplied(result) — refetch tasks after.

const PresetApplyPanel = ({ accountId, currentUser, onApplied }) => {
    const [open, setOpen]       = React.useState(false);
    const [presets, setPresets] = React.useState(null);   // null = not loaded yet
    const [busy, setBusy]       = React.useState(null);   // preset id mid-apply
    const [msg, setMsg]         = React.useState('');
    const [err, setErr]         = React.useState('');
    const [creating, setCreating] = React.useState(null); // { name, tasks }
    const isAdmin = currentUser?.role === 'admin';

    const load = () => api.getTaskPresets().then(setPresets).catch(() => setPresets([]));
    React.useEffect(() => { if (open && presets === null) load(); }, [open]);

    const apply = async (p) => {
        setBusy(p.id); setErr(''); setMsg('');
        try {
            const r = await api.applyPreset(accountId, p.id);
            setMsg(r.spawned ? `Opened ${r.spawned} task${r.spawned === 1 ? '' : 's'} from "${p.name}".` : `"${p.name}" — all of its tasks are already open here.`);
            onApplied && onApplied(r);
        } catch (ex) { setErr(ex.message); }
        finally { setBusy(null); }
    };

    const saveNew = async (e) => {
        e.preventDefault(); setErr('');
        const tasks = creating.tasks.filter(t => (t.title || '').trim());
        if (!creating.name.trim() || !tasks.length) return setErr('A preset needs a name and at least one task.');
        try {
            await api.createTaskPreset({ name: creating.name.trim(), tasks });
            setCreating(null); await load();
            setMsg(`Preset "${creating.name.trim()}" created. Bind it to events in Settings → Task Presets when you want it automatic.`);
        } catch (ex) { setErr(ex.message); }
    };

    if (!open) return (
        <button type="button" className="btn btn-secondary btn-small" onClick={() => setOpen(true)} title="Open a preset's tasks on this account">
            <i className="fas fa-tasks"></i> Apply preset
        </button>
    );

    return (
        <div style={{ border: '1px solid var(--border)', borderRadius: '0.5rem', padding: '0.75rem 1rem', marginTop: '0.5rem' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', marginBottom: '0.5rem' }}>
                <span style={{ fontWeight: 600, fontSize: '0.875rem' }}><i className="fas fa-tasks" style={{ marginRight: '0.35rem', color: 'var(--text-3)' }}></i>Apply a preset</span>
                <span style={{ fontSize: '0.75rem', color: 'var(--text-3)' }}>— opens its tasks on this account, due dates counted from today</span>
                <button type="button" className="btn-icon-sm" style={{ marginLeft: 'auto' }} onClick={() => { setOpen(false); setMsg(''); setErr(''); }} title="Close"><i className="fas fa-times"></i></button>
            </div>
            {err && <div className="api-error" style={{ marginBottom: '0.5rem' }}>{err}</div>}
            {msg && <div style={{ fontSize: '0.8125rem', color: 'var(--success, #22c55e)', marginBottom: '0.5rem' }}><i className="fas fa-check"></i> {msg}</div>}
            {presets === null ? <span style={{ fontSize: '0.8125rem', color: 'var(--text-3)' }}>Loading…</span>
             : presets.length === 0 && !creating ? <span style={{ fontSize: '0.8125rem', color: 'var(--text-3)' }}>No presets yet.</span>
             : (
                <div className="tag-filter-row" style={{ alignItems: 'center' }}>
                    {presets.map(p => (
                        <span key={p.id} className="tag-pill tag-filter-chip" style={{ cursor: busy ? 'wait' : 'pointer', opacity: busy && busy !== p.id ? 0.5 : 1, background: 'var(--surface-2)', border: '1px solid var(--border)', color: 'var(--text-1, inherit)' }}
                              title={`${p.tasks.map(t => t.title).join(' · ')}${p.triggers?.length ? `\nAuto-fires on: ${p.triggers.join(', ')}` : '\nManual only'}`}
                              onClick={() => !busy && apply(p)}>
                            {busy === p.id ? <i className="fas fa-spinner fa-spin"></i> : <i className="fas fa-plus" style={{ fontSize: '0.6rem' }}></i>}
                            {' '}{p.name} <span style={{ opacity: 0.7 }}>({p.tasks.length})</span>
                            {p.triggers?.length > 0 && <i className="fas fa-bolt" style={{ marginLeft: '0.3rem', fontSize: '0.6rem' }} title="Also fires automatically"></i>}
                        </span>
                    ))}
                    {isAdmin && !creating && (
                        <button type="button" className="btn-link" style={{ fontSize: '0.75rem' }} onClick={() => setCreating({ name: '', tasks: [{ title: '', notes: '', due_in_days: 0, auto_close: null }] })}>
                            <i className="fas fa-plus"></i> New preset
                        </button>
                    )}
                </div>
            )}
            {creating && (
                <form onSubmit={saveNew} style={{ marginTop: '0.75rem', borderTop: '1px solid var(--border)', paddingTop: '0.75rem' }}>
                    <div className="form-group" style={{ maxWidth: 320 }}>
                        <label className="form-label">Preset name</label>
                        <input className="form-input" value={creating.name} autoFocus maxLength={100} placeholder="e.g. New web lead"
                               onChange={e => setCreating(p => ({ ...p, name: e.target.value }))} />
                    </div>
                    <TaskListEditor tasks={creating.tasks} onChange={tasks => setCreating(p => ({ ...p, tasks }))} />
                    <div style={{ display: 'flex', gap: '0.5rem', marginTop: '0.5rem' }}>
                        <button type="submit" className="btn btn-primary btn-small"><i className="fas fa-check"></i> Create preset</button>
                        <button type="button" className="btn btn-secondary btn-small" onClick={() => setCreating(null)}>Cancel</button>
                    </div>
                </form>
            )}
        </div>
    );
};
