// Spreadsheet import (2026-10-30) — "load the spreadsheet and you're done."
// Three screens: pick a file → review (what matched, which columns become
// custom fields, each group's status, what to publish) → done. Nothing is
// written until Import; the preview is re-computed from the same file so
// the server stays stateless. Opened from Add property → From a spreadsheet.
const BOARD_STATUSES = [
    { id: 'skip',               label: 'Skip this group' },
    { id: 'planned',            label: 'Permitting' },
    { id: 'under_construction', label: 'Under Construction' },
    { id: 'move_in_ready',      label: 'Active' },
    { id: 'pending',            label: 'Pending' },
    { id: 'rented',             label: 'Rented' },
    { id: 'sold',               label: 'Sold' },
    { id: 'archived',           label: 'Archived' },
];

const BoardImportModal = ({ onDone, onClose }) => {
    const [file, setFile] = React.useState(null);
    const [preview, setPreview] = React.useState(null);
    const [busy, setBusy] = React.useState(false);
    const [error, setError] = React.useState('');
    const [result, setResult] = React.useState(null);
    // Options the person confirms on the review screen.
    const [groups, setGroups] = React.useState({});          // title → status | 'skip'
    const [publish, setPublish] = React.useState({});        // title → bool
    const [skipNew, setSkipNew] = React.useState({});        // header → true = don't create
    const [defaultCity, setDefaultCity] = React.useState('');
    const [showRows, setShowRows] = React.useState('warnings');
    const inputRef = React.useRef(null);

    const options = () => ({
        groups, publishGroups: Object.keys(publish).filter(t => publish[t]),
        skipNew: Object.keys(skipNew).filter(h => skipNew[h]), defaultCity: defaultCity.trim() || null, createFields: true,
    });

    const load = async (f, opts) => {
        if (!f) return;
        setError(''); setBusy(true);
        try {
            const p = await api.previewBoardImport(f, opts);
            setFile(f); setPreview(p);
            if (!opts) {   // first look: seed the group choices from the server's guesses
                const g = {}; for (const grp of p.groups) g[grp.title] = grp.status || 'skip';
                setGroups(g); setPublish({}); setSkipNew({});
            }
        } catch (err) { setError(err.message); }
        finally { setBusy(false); if (inputRef.current) inputRef.current.value = ''; }
    };
    // Any option change re-plans against the same file (counts stay honest).
    const replan = (next) => { const o = { ...options(), ...next }; load(file, o); };
    const setGroup = (title, st) => { const g = { ...groups, [title]: st }; setGroups(g); replan({ groups: g }); };
    const togglePublish = (title) => { const p = { ...publish, [title]: !publish[title] }; setPublish(p); replan({ publishGroups: Object.keys(p).filter(t => p[t]) }); };
    const toggleNew = (h) => { const s = { ...skipNew, [h]: !skipNew[h] }; setSkipNew(s); replan({ skipNew: Object.keys(s).filter(k => s[k]) }); };

    const run = async () => {
        setError(''); setBusy(true);
        try { const r = await api.applyBoardImport(file, options()); setResult(r); onDone && onDone(r); }
        catch (err) { setError(err.message); }
        finally { setBusy(false); }
    };

    const c = preview?.counts;
    const matched = preview ? preview.columns.filter(x => x.kind === 'builtin' || x.kind === 'custom') : [];
    const fresh = preview ? preview.columns.filter(x => x.kind === 'new') : [];
    const ignored = preview ? preview.columns.filter(x => x.kind === 'ignore' && x.header) : [];
    const rowsShown = preview ? preview.rows.filter(r => showRows === 'all' || (showRows === 'warnings' ? r.warnings.length : r.verb === showRows)) : [];

    return (
        <div className="modal-overlay" onClick={busy ? undefined : onClose}>
            <div className="modal modal-large" onClick={(e) => e.stopPropagation()}>
                <div className="modal-header">
                    <h2 className="modal-title"><i className="fas fa-file-excel" style={{ marginRight: '0.5rem' }}></i>Import from a spreadsheet</h2>
                    <button type="button" className="modal-close-btn" onClick={onClose} aria-label="Close" disabled={busy}>×</button>
                </div>
                <div className="modal-body">
                    {error && <div className="api-error" style={{ marginBottom: '1rem' }}>{error}</div>}

                    {result ? (
                        <div>
                            <h3 style={{ marginTop: 0 }}>Done</h3>
                            <p>{result.created} home{result.created === 1 ? '' : 's'} added, {result.updated} filled in{result.newFields.length ? `, ${result.newFields.length} custom field${result.newFields.length === 1 ? '' : 's'} created` : ''}{result.shown.length ? `, ${result.shown.length} field${result.shown.length === 1 ? '' : 's'} switched on so your data shows on the form` : ''}.</p>
                            {result.leftOut > 0 && <p className="text-muted">{result.leftOut} row{result.leftOut === 1 ? '' : 's'} left out (skipped groups).</p>}
                            <p className="text-muted">You can upload the same sheet again any time — homes already here are only ever filled in, never overwritten.</p>
                            <div style={{ display: 'flex', justifyContent: 'flex-end' }}><button type="button" className="btn btn-primary" onClick={onClose}>Close</button></div>
                        </div>
                    ) : !preview ? (
                        <div>
                            <p>Pick the spreadsheet your listings live in — a Monday.com board export, your own Excel file, or a CSV. The first column should be the address.</p>
                            <ul className="text-muted" style={{ fontSize: '0.875rem', lineHeight: 1.6 }}>
                                <li>Columns are matched by their header name (Price, Beds, Lockbox code, …). Anything we don't recognise becomes a custom field, so nothing is lost.</li>
                                <li>Homes already here are matched by address and only ever <strong>filled in</strong> — a value you typed is never overwritten, and nothing is deleted.</li>
                                <li>Nothing is saved until you click Import on the next screen.</li>
                            </ul>
                            <input ref={inputRef} type="file" accept=".xlsx,.csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,text/csv" style={{ display: 'none' }} onChange={(e) => load(e.target.files?.[0])} />
                            <button type="button" className="btn btn-primary" disabled={busy} onClick={() => inputRef.current?.click()}>
                                {busy ? <><i className="fas fa-spinner fa-spin"></i> Reading…</> : <><i className="fas fa-upload"></i> Choose file</>}
                            </button>
                        </div>
                    ) : (
                        <div>
                            {/* 1. The numbers */}
                            <div className="stat-row" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(120px, 1fr))', gap: '0.75rem', marginBottom: '1.25rem' }}>
                                {[['New homes', c.create], ['Filled in', c.update], ['Already here', c.unchanged], ['Not on the sheet', preview.tenantOnly.length], ['Left out', preview.leftOut.length], ['With notes', c.warned]].map(([l, n]) => (
                                    <div key={l} className="stat-card" style={{ padding: '0.75rem' }}><div style={{ fontSize: '1.5rem', fontWeight: 700 }}>{n}</div><div className="text-muted" style={{ fontSize: '0.8rem' }}>{l}</div></div>
                                ))}
                            </div>

                            {/* 2. Groups → status */}
                            <h4 style={{ margin: '0 0 0.5rem' }}>Groups on the sheet</h4>
                            <p className="text-muted" style={{ fontSize: '0.875rem', marginTop: 0 }}>Each group becomes a status. Tick "on the website" to publish a group's new homes right away (existing homes are never re-published).</p>
                            <table className="data-table" style={{ marginBottom: '1.25rem' }}>
                                <thead><tr><th>Group</th><th>Homes</th><th>Status</th><th>On the website</th></tr></thead>
                                <tbody>
                                    {preview.groups.map(g => (
                                        <tr key={g.title}>
                                            <td>{g.title || <em>(whole sheet)</em>}</td>
                                            <td>{g.rows}</td>
                                            <td><select className="form-input" value={groups[g.title] || 'skip'} onChange={(e) => setGroup(g.title, e.target.value)} disabled={busy}>
                                                {BOARD_STATUSES.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
                                            </select></td>
                                            <td><label style={{ display: 'flex', alignItems: 'center', gap: '0.4rem' }}>
                                                <input type="checkbox" checked={!!publish[g.title]} onChange={() => togglePublish(g.title)} disabled={busy || (groups[g.title] || 'skip') === 'skip' || groups[g.title] === 'archived'} /> publish new homes
                                            </label></td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>

                            {/* 3. Columns */}
                            <h4 style={{ margin: '0 0 0.5rem' }}>Columns</h4>
                            <p className="text-muted" style={{ fontSize: '0.875rem', marginTop: 0 }}>
                                {matched.length} matched a field here{ignored.length ? `, ${ignored.length} ignored (${ignored.map(x => x.header).join(', ')})` : ''}.
                                {fresh.length ? ` ${fresh.length} aren't fields yet — each becomes a custom field unless you untick it:` : ' Every column has a home.'}
                            </p>
                            {fresh.length > 0 && (
                                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem 1rem', marginBottom: '1rem' }}>
                                    {fresh.map(x => <label key={x.header} style={{ display: 'flex', alignItems: 'center', gap: '0.35rem', fontSize: '0.875rem' }}>
                                        <input type="checkbox" checked={!skipNew[x.header]} onChange={() => toggleNew(x.header)} disabled={busy} /> {x.header}
                                    </label>)}
                                </div>
                            )}
                            <details style={{ marginBottom: '1.25rem' }}>
                                <summary className="text-muted" style={{ cursor: 'pointer', fontSize: '0.875rem' }}>Show how each column matched</summary>
                                <div style={{ columns: 2, fontSize: '0.8125rem', marginTop: '0.5rem' }}>
                                    {preview.columns.filter(x => x.header).map((x, i) => <div key={i}><strong>{x.header}</strong> → {x.kind === 'key' ? 'address' : x.kind === 'maplink' ? 'map pin (coordinates)' : x.kind === 'hint' ? 'city hint' : x.kind === 'new' ? 'new custom field' : x.kind === 'ignore' ? `ignored${x.note ? ` (${x.note})` : ''}` : (x.target || '').replace(/^top\./, '')}</div>)}
                                </div>
                            </details>

                            {/* 4. Options */}
                            <div className="form-grid" style={{ marginBottom: '1.25rem' }}>
                                <div className="form-group">
                                    <label className="form-label">Default city for rows missing one <span className="text-muted">(optional)</span></label>
                                    <input className="form-input" placeholder="Citrus Springs, FL" value={defaultCity} onChange={(e) => setDefaultCity(e.target.value)} onBlur={() => replan({ defaultCity: defaultCity.trim() || null })} disabled={busy} />
                                </div>
                            </div>

                            {/* 5. Rows */}
                            <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', marginBottom: '0.5rem' }}>
                                <h4 style={{ margin: 0 }}>Rows</h4>
                                <select className="form-input" style={{ width: 'auto' }} value={showRows} onChange={(e) => setShowRows(e.target.value)}>
                                    <option value="warnings">with notes ({c.warned})</option><option value="create">new ({c.create})</option><option value="update">filled in ({c.update})</option><option value="unchanged">already here ({c.unchanged})</option><option value="all">all</option>
                                </select>
                            </div>
                            <div style={{ maxHeight: '18rem', overflow: 'auto', border: '1px solid var(--border)', borderRadius: '0.375rem', fontSize: '0.8125rem' }}>
                                {rowsShown.length === 0 && <div className="text-muted" style={{ padding: '0.75rem' }}>Nothing here.</div>}
                                {rowsShown.map((r, i) => (
                                    <div key={i} style={{ padding: '0.4rem 0.75rem', borderBottom: '1px solid var(--border)' }}>
                                        <span className={`badge badge-${r.verb === 'create' ? 'success' : r.verb === 'update' ? 'info' : 'neutral'}`} style={{ marginRight: '0.5rem' }}>{r.verb === 'create' ? 'new' : r.verb === 'update' ? 'fill in' : r.verb}</span>
                                        {r.label}{r.verb === 'create' ? ` — ${r.fields} fields${r.published ? ', on the website' : ''}` : r.verb === 'update' ? ` — ${r.fields} fields` : ''}
                                        {r.statusDiffers && <span className="text-muted"> (status here: {r.statusDiffers.tenant}, sheet: {r.statusDiffers.sheet} — kept)</span>}
                                        {r.warnings.length > 0 && <div className="text-muted" style={{ marginLeft: '0.25rem' }}>⚠ {r.warnings.join('; ')}</div>}
                                    </div>
                                ))}
                            </div>
                            {preview.tenantOnly.length > 0 && (
                                <details style={{ marginTop: '0.75rem' }}>
                                    <summary className="text-muted" style={{ cursor: 'pointer', fontSize: '0.875rem' }}>{preview.tenantOnly.length} home{preview.tenantOnly.length === 1 ? ' is' : 's are'} here but not on the sheet (left alone)</summary>
                                    <ul style={{ fontSize: '0.8125rem' }}>{preview.tenantOnly.map(t => <li key={t.id}>{t.label} ({t.status}){t.near ? <span className="text-muted"> — the sheet has "{t.near}": same home? Fix the spelling on one side and upload again.</span> : null}</li>)}</ul>
                                </details>
                            )}
                            {preview.leftOut.length > 0 && (
                                <details style={{ marginTop: '0.5rem' }}>
                                    <summary className="text-muted" style={{ cursor: 'pointer', fontSize: '0.875rem' }}>{preview.leftOut.length} row{preview.leftOut.length === 1 ? '' : 's'} left out</summary>
                                    <ul style={{ fontSize: '0.8125rem' }}>{preview.leftOut.map((l, i) => <li key={i}>{l.address || '(no address)'} — {l.group || 'sheet'}: {l.reason}</li>)}</ul>
                                </details>
                            )}

                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '1.25rem' }}>
                                <button type="button" className="btn btn-secondary" disabled={busy} onClick={() => { setPreview(null); setFile(null); }}>Choose a different file</button>
                                <button type="button" className="btn btn-primary" disabled={busy || (c.create + c.update) === 0} onClick={run}>
                                    {busy ? <><i className="fas fa-spinner fa-spin"></i> Working…</> : <><i className="fas fa-file-import"></i> Import {c.create} new{c.update ? ` + fill in ${c.update}` : ''}</>}
                                </button>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};
