import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useEffect } from 'react';
import { GripVertical } from 'lucide-react';
import { getCategories, putCategories, testNewbook, getConfig, getWorkforceDepartments, putWorkforceDepartments, putGeneralTasks, putTimeReq, putWarningThresholds, } from '../api';
const WEEKDAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
export function Settings() {
    // ── Category state ─────────────────────────────────────────────────────────
    const [cats, setCats] = useState([]);
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [testing, setTesting] = useState(false);
    const [error, setError] = useState('');
    const [msg, setMsg] = useState('');
    const [dragIdx, setDragIdx] = useState(null);
    // ── Workforce state ────────────────────────────────────────────────────────
    const [wfDepts, setWfDepts] = useState([]);
    const [wfSelected, setWfSelected] = useState([]);
    const [wfLoading, setWfLoading] = useState(true);
    const [wfError, setWfError] = useState('');
    const [wfNotConfigured, setWfNotConfigured] = useState(false);
    const [wfSaving, setWfSaving] = useState(false);
    const [wfMsg, setWfMsg] = useState('');
    // ── Recurring general tasks state ──────────────────────────────────────────
    const [tasks, setTasks] = useState([]);
    const [taskSaving, setTaskSaving] = useState(false);
    const [taskMsg, setTaskMsg] = useState('');
    const [taskError, setTaskError] = useState('');
    // ── Time requirements state ────────────────────────────────────────────────
    const [timeReqs, setTimeReqs] = useState({});
    const [timeMsg, setTimeMsg] = useState('');
    const [timeError, setTimeError] = useState('');
    // ── Warning threshold state ────────────────────────────────────────────────
    const [warnOverRed, setWarnOverRed] = useState(4);
    const [warnOverAmber, setWarnOverAmber] = useState(1);
    const [warnUnderAmber, setWarnUnderAmber] = useState(1);
    const [warnUnderRed, setWarnUnderRed] = useState(2);
    const [warnSaving, setWarnSaving] = useState(false);
    const [warnMsg, setWarnMsg] = useState('');
    const [warnError, setWarnError] = useState('');
    useEffect(() => {
        Promise.all([
            getCategories(),
            getConfig(),
            getWorkforceDepartments().catch((e) => {
                if (e.message.includes('503') || e.message.toLowerCase().includes('not configured')) {
                    setWfNotConfigured(true);
                }
                else {
                    setWfError(e.message);
                }
                return null;
            }),
        ]).then(([catResp, cfg, depts]) => {
            setCats(catResp.categories);
            setTasks(cfg.general_tasks || []);
            setTimeReqs(cfg.time_requirements || {});
            setWfSelected(cfg.workforce_departments || []);
            setWarnOverRed(cfg.warn_over_red_hrs ?? 4);
            setWarnOverAmber(cfg.warn_over_amber_hrs ?? 1);
            setWarnUnderAmber(cfg.warn_under_amber_hrs ?? 1);
            setWarnUnderRed(cfg.warn_under_red_hrs ?? 2);
            if (depts)
                setWfDepts(depts);
            setLoading(false);
            setWfLoading(false);
        }).catch(e => {
            setError(e.message);
            setLoading(false);
            setWfLoading(false);
        });
    }, []);
    // ── Category handlers ──────────────────────────────────────────────────────
    function toggleExcluded(i) {
        setCats(cats.map((c, idx) => idx === i ? { ...c, excluded: !c.excluded } : c));
    }
    function onDragStart(e, i) {
        setDragIdx(i);
        e.dataTransfer.effectAllowed = 'move';
    }
    function onDragOver(e, i) {
        e.preventDefault();
        if (dragIdx === null || dragIdx === i)
            return;
        const next = [...cats];
        const [moved] = next.splice(dragIdx, 1);
        next.splice(i, 0, moved);
        setCats(next);
        setDragIdx(i);
    }
    function onDragEnd() { setDragIdx(null); }
    async function saveCats() {
        setSaving(true);
        setError('');
        setMsg('');
        try {
            await putCategories(cats.map(c => c.id), cats.filter(c => c.excluded).map(c => c.id));
            setMsg('Saved');
            setTimeout(() => setMsg(''), 2500);
        }
        catch (e) {
            setError(e instanceof Error ? e.message : 'Save failed');
        }
        finally {
            setSaving(false);
        }
    }
    async function handleTest() {
        setTesting(true);
        setError('');
        setMsg('');
        try {
            const res = await testNewbook();
            setMsg(res.ok ? `Connection OK: ${res.message || ''}` : `Failed: ${res.error || 'unknown'}`);
        }
        catch (e) {
            setError(e instanceof Error ? e.message : 'Test failed');
        }
        finally {
            setTesting(false);
        }
    }
    // ── Workforce handlers ─────────────────────────────────────────────────────
    function toggleWfDept(id) {
        setWfSelected(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
    }
    async function saveWfDepts() {
        setWfSaving(true);
        setWfError('');
        setWfMsg('');
        try {
            await putWorkforceDepartments(wfSelected);
            setWfMsg('Departments saved');
            setTimeout(() => setWfMsg(''), 2500);
        }
        catch (e) {
            setWfError(e instanceof Error ? e.message : 'Save failed');
        }
        finally {
            setWfSaving(false);
        }
    }
    // ── Recurring tasks handlers ───────────────────────────────────────────────
    function setTaskName(i, name) {
        setTasks(tasks.map((t, idx) => idx === i ? { ...t, name } : t));
    }
    function setTaskHours(i, day, val) {
        const mins = parseInt(val, 10);
        setTasks(tasks.map((t, idx) => {
            if (idx !== i)
                return t;
            return { ...t, hours: { ...t.hours, [day]: isNaN(mins) ? 0 : Math.max(0, mins) } };
        }));
    }
    function removeTask(i) {
        setTasks(tasks.filter((_, idx) => idx !== i));
    }
    async function saveTasks() {
        setTaskSaving(true);
        setTaskError('');
        setTaskMsg('');
        try {
            await putGeneralTasks(tasks);
            setTaskMsg('Saved');
            setTimeout(() => setTaskMsg(''), 2500);
        }
        catch (e) {
            setTaskError(e instanceof Error ? e.message : 'Save failed');
        }
        finally {
            setTaskSaving(false);
        }
    }
    // ── Time requirements handlers ─────────────────────────────────────────────
    async function handleTimeReqChange(catId, action, value) {
        const next = {
            ...timeReqs,
            [catId]: { ...(timeReqs[catId] || { depart: 0, stay: 0, arrive: 0 }), [action]: value },
        };
        setTimeReqs(next);
        try {
            await putTimeReq(catId, action, value);
            setTimeMsg('Saved');
            setTimeout(() => setTimeMsg(''), 1500);
        }
        catch (e) {
            setTimeError(e instanceof Error ? e.message : 'Save failed');
        }
    }
    // ── Warning threshold handlers ─────────────────────────────────────────────
    async function saveWarnThresholds() {
        setWarnSaving(true);
        setWarnError('');
        setWarnMsg('');
        try {
            await putWarningThresholds({
                warn_over_red_hrs: warnOverRed,
                warn_over_amber_hrs: warnOverAmber,
                warn_under_amber_hrs: warnUnderAmber,
                warn_under_red_hrs: warnUnderRed,
            });
            setWarnMsg('Saved');
            setTimeout(() => setWarnMsg(''), 2500);
        }
        catch (e) {
            setWarnError(e instanceof Error ? e.message : 'Save failed');
        }
        finally {
            setWarnSaving(false);
        }
    }
    if (loading) {
        return _jsx("div", { style: { padding: '2rem', color: 'var(--text-mid)' }, children: "Loading\u2026" });
    }
    return (_jsxs("div", { style: { padding: '1.5rem', maxWidth: '680px' }, children: [_jsx("h1", { style: { fontSize: '1.1rem', fontWeight: 700, color: 'var(--text-dark)', marginBottom: '1.5rem' }, children: "Settings" }), _jsx(SectionHeading, { title: "Room Categories" }), _jsx("p", { style: { fontSize: '0.82rem', color: 'var(--text-mid)', marginBottom: '1rem' }, children: "Drag to reorder. Toggle to exclude categories from the planner." }), error && _jsx(Banner, { type: "error", children: error }), msg && _jsx(Banner, { type: "ok", children: msg }), _jsx("div", { style: { display: 'flex', flexDirection: 'column', gap: '0.5rem', marginBottom: '1rem' }, children: cats.map((cat, i) => (_jsxs("div", { draggable: true, onDragStart: e => onDragStart(e, i), onDragOver: e => onDragOver(e, i), onDragEnd: onDragEnd, style: {
                        display: 'flex', alignItems: 'center', gap: '0.75rem',
                        padding: '0.625rem 0.875rem',
                        border: '1px solid var(--card-border)', borderRadius: '8px',
                        background: cat.excluded ? '#f8fafc' : 'var(--card-bg)',
                        opacity: dragIdx === i ? 0.5 : 1,
                    }, children: [_jsx(GripVertical, { size: 16, color: "var(--text-mid)", style: { cursor: 'grab', flexShrink: 0 } }), _jsx("span", { style: {
                                flex: 1, fontSize: '0.9rem',
                                color: cat.excluded ? 'var(--text-mid)' : 'var(--text-dark)',
                                textDecoration: cat.excluded ? 'line-through' : 'none',
                            }, children: cat.name }), _jsxs("span", { style: { fontSize: '0.75rem', color: 'var(--text-mid)', marginRight: '0.5rem' }, children: [cat.room_count, " rooms"] }), _jsxs("label", { style: { display: 'flex', alignItems: 'center', gap: '0.375rem', fontSize: '0.8rem', color: 'var(--text-mid)' }, children: [_jsx("input", { type: "checkbox", checked: !cat.excluded, onChange: () => toggleExcluded(i) }), "Active"] })] }, cat.id))) }), _jsxs("div", { style: { display: 'flex', gap: '0.75rem', flexWrap: 'wrap', marginBottom: '2.5rem' }, children: [_jsx(Btn, { onClick: saveCats, disabled: saving, primary: true, children: saving ? 'Saving…' : 'Save Order & Visibility' }), _jsx(Btn, { onClick: handleTest, disabled: testing, children: testing ? 'Testing…' : 'Test Newbook Connection' })] }), _jsx(Divider, {}), _jsx(SectionHeading, { title: "Workforce Departments" }), _jsx("p", { style: { fontSize: '0.82rem', color: 'var(--text-mid)', marginBottom: '1rem' }, children: "Select the department(s) whose shifts should appear in the HK staff rota." }), wfNotConfigured && (_jsxs("div", { style: { padding: '0.75rem', borderRadius: '8px', background: '#f8fafc', border: '1px solid var(--card-border)', color: 'var(--text-mid)', fontSize: '0.85rem', marginBottom: '2rem' }, children: ["Workforce integration not configured \u2014 add the bearer token in ", _jsx("strong", { children: "Settings \u2192 Integrations \u2192 Workforce" }), "."] })), !wfNotConfigured && wfLoading && (_jsx("div", { style: { color: 'var(--text-mid)', fontSize: '0.85rem', marginBottom: '2rem' }, children: "Loading departments\u2026" })), !wfNotConfigured && !wfLoading && (_jsxs("div", { style: { marginBottom: '2.5rem' }, children: [wfError && _jsx(Banner, { type: "error", children: wfError }), wfMsg && _jsx(Banner, { type: "ok", children: wfMsg }), wfDepts.length === 0 ? (_jsx("div", { style: { color: 'var(--text-mid)', fontSize: '0.85rem', marginBottom: '1rem' }, children: "No departments found for this location." })) : (_jsx("div", { style: { display: 'flex', flexDirection: 'column', gap: '0.4rem', marginBottom: '1rem' }, children: wfDepts.map(dept => (_jsxs("label", { style: {
                                display: 'flex', alignItems: 'center', gap: '0.625rem',
                                padding: '0.5rem 0.75rem',
                                border: '1px solid var(--card-border)', borderRadius: '7px',
                                background: wfSelected.includes(dept.id) ? 'rgba(42,100,72,0.05)' : 'var(--card-bg)',
                                cursor: 'pointer', fontSize: '0.9rem', color: 'var(--text-dark)',
                            }, children: [_jsx("input", { type: "checkbox", checked: wfSelected.includes(dept.id), onChange: () => toggleWfDept(dept.id) }), dept.name] }, dept.id))) })), wfSelected.length === 0 && wfDepts.length > 0 && (_jsx("div", { style: { marginBottom: '0.75rem', fontSize: '0.8rem', color: '#b45309' }, children: "Select at least one department to enable Workforce sync." })), _jsx(Btn, { onClick: saveWfDepts, disabled: wfSaving, primary: true, children: wfSaving ? 'Saving…' : 'Save Departments' })] })), _jsx(Divider, {}), _jsx(SectionHeading, { title: "Recurring General Tasks" }), _jsx("p", { style: { fontSize: '0.82rem', color: 'var(--text-mid)', marginBottom: '1rem' }, children: "Tasks that recur every week. Enter minutes per day. These add to the total required hours every week." }), taskError && _jsx(Banner, { type: "error", children: taskError }), taskMsg && _jsx(Banner, { type: "ok", children: taskMsg }), _jsx("div", { style: { overflowX: 'auto', marginBottom: '1rem' }, children: _jsxs("table", { className: "hk-table", style: { minWidth: '560px' }, children: [_jsx("thead", { children: _jsxs("tr", { children: [_jsx("th", { className: "col-label", children: "Task" }), WEEKDAYS.map(d => _jsx("th", { children: d }, d)), _jsx("th", { style: { width: '32px' } })] }) }), _jsxs("tbody", { children: [tasks.length === 0 && (_jsx("tr", { children: _jsx("td", { colSpan: 9, style: { color: 'var(--text-mid)', textAlign: 'center', padding: '1rem' }, children: "No tasks yet" }) })), tasks.map((task, i) => (_jsxs("tr", { children: [_jsx("td", { style: { padding: '0.3rem 0.5rem' }, children: _jsx("input", { className: "hk-text-input", value: task.name, placeholder: "Task name", onChange: e => setTaskName(i, e.target.value) }) }), WEEKDAYS.map(day => (_jsx("td", { style: { padding: '0.3rem 0.4rem' }, children: _jsx("input", { type: "number", className: "hk-num-input", min: 0, max: 999, value: task.hours[day] || '', placeholder: "0", onChange: e => setTaskHours(i, day, e.target.value) }) }, day))), _jsx("td", { children: _jsx("button", { onClick: () => removeTask(i), style: {
                                                    background: 'none', border: 'none', color: 'var(--text-mid)', fontSize: '1rem', padding: '0.2rem 0.4rem',
                                                }, children: "\u00D7" }) })] }, i)))] })] }) }), _jsxs("div", { style: { display: 'flex', gap: '0.75rem', flexWrap: 'wrap', marginBottom: '2.5rem' }, children: [_jsx(Btn, { onClick: () => setTasks([...tasks, { name: '', hours: {} }]), children: "+ Add task" }), _jsx(Btn, { onClick: saveTasks, disabled: taskSaving, primary: true, children: taskSaving ? 'Saving…' : 'Save Tasks' })] }), _jsx(Divider, {}), _jsx(SectionHeading, { title: "Time Requirements (minutes per room)" }), _jsx("p", { style: { fontSize: '0.82rem', color: 'var(--text-mid)', marginBottom: '1rem' }, children: "How many minutes each room type takes depending on guest status." }), timeError && _jsx(Banner, { type: "error", children: timeError }), timeMsg && _jsx(Banner, { type: "ok", children: timeMsg }), _jsx("div", { style: { overflowX: 'auto', marginBottom: '2rem' }, children: _jsxs("table", { className: "hk-table", style: { maxWidth: '500px' }, children: [_jsx("thead", { children: _jsxs("tr", { children: [_jsx("th", { className: "col-label", children: "Category" }), _jsx("th", { children: "Depart (mins)" }), _jsx("th", { children: "Stay (mins)" }), _jsx("th", { children: "Arrive (mins)" })] }) }), _jsx("tbody", { children: cats.filter(c => !c.excluded).map(cat => {
                                const req = timeReqs[cat.id] || { depart: 0, stay: 0, arrive: 0 };
                                return (_jsxs("tr", { children: [_jsx("td", { className: "col-label", children: cat.name }), ['depart', 'stay', 'arrive'].map(action => (_jsx("td", { style: { padding: '0.3rem 0.4rem' }, children: _jsx("input", { type: "number", className: "hk-num-input", min: 0, max: 999, value: req[action] || '', placeholder: "0", onChange: e => handleTimeReqChange(cat.id, action, parseInt(e.target.value, 10) || 0), onBlur: e => handleTimeReqChange(cat.id, action, parseInt(e.target.value, 10) || 0) }) }, action)))] }, cat.id));
                            }) })] }) }), _jsx(Divider, {}), _jsx(SectionHeading, { title: "Warning Thresholds" }), _jsx("p", { style: { fontSize: '0.82rem', color: 'var(--text-mid)', marginBottom: '1rem' }, children: "Controls the colour and icon shown on the \"with Adjustments\" row in the staff rota. All values are in hours." }), warnError && _jsx(Banner, { type: "error", children: warnError }), warnMsg && _jsx(Banner, { type: "ok", children: warnMsg }), _jsx("div", { style: { display: 'flex', flexDirection: 'column', gap: '0.625rem', marginBottom: '1.25rem', maxWidth: '420px' }, children: [
                    { label: '⚠ Red warning — spare over', value: warnOverRed, set: setWarnOverRed, help: 'default 4h' },
                    { label: '⚠ Amber warning — spare over', value: warnOverAmber, set: setWarnOverAmber, help: 'default 1h' },
                    { label: '✗ Amber cross — short over', value: warnUnderAmber, set: setWarnUnderAmber, help: 'default 1h' },
                    { label: '✗ Red cross — short over', value: warnUnderRed, set: setWarnUnderRed, help: 'default 2h' },
                ].map(({ label, value, set, help }) => (_jsxs("div", { style: { display: 'flex', alignItems: 'center', gap: '0.75rem' }, children: [_jsx("span", { style: { flex: 1, fontSize: '0.875rem', color: 'var(--text-dark)' }, children: label }), _jsx("input", { type: "number", className: "hk-num-input", min: 0, max: 24, step: 0.5, value: value, onChange: e => set(parseFloat(e.target.value) || 0), style: { width: '68px' } }), _jsx("span", { style: { fontSize: '0.75rem', color: 'var(--text-mid)', minWidth: '52px' }, children: help })] }, label))) }), _jsx("p", { style: { fontSize: '0.78rem', color: 'var(--text-mid)', marginBottom: '1rem' }, children: "Green \u2713 is automatic \u2014 shown when the difference is within the amber spare and short thresholds above." }), _jsx("div", { style: { marginBottom: '2.5rem' }, children: _jsx(Btn, { onClick: saveWarnThresholds, disabled: warnSaving, primary: true, children: warnSaving ? 'Saving…' : 'Save Thresholds' }) })] }));
}
// ── Small reusable helpers ────────────────────────────────────────────────────
function SectionHeading({ title }) {
    return (_jsx("h2", { style: { fontSize: '0.95rem', fontWeight: 700, color: 'var(--text-dark)', marginBottom: '0.25rem' }, children: title }));
}
function Divider() {
    return _jsx("div", { style: { height: '1px', background: 'var(--card-border)', margin: '0.5rem 0 2rem' } });
}
function Banner({ type, children }) {
    return (_jsx("div", { style: {
            marginBottom: '0.75rem', padding: '0.75rem', borderRadius: '8px', fontSize: '0.875rem',
            background: type === 'ok' ? '#dcfce7' : '#fee2e2',
            color: type === 'ok' ? 'var(--success)' : 'var(--danger)',
        }, children: children }));
}
function Btn({ children, onClick, disabled, primary }) {
    return (_jsx("button", { onClick: onClick, disabled: disabled, style: {
            background: primary ? 'var(--hk-green)' : 'var(--card-bg)',
            color: primary ? '#fff' : 'var(--text-dark)',
            border: `1px solid ${primary ? 'var(--hk-green)' : 'var(--card-border)'}`,
            borderRadius: '6px', padding: '0.5rem 1.25rem', fontSize: '0.875rem', fontWeight: 600,
        }, children: children }));
}
