// Settings → MLS Connections — hold the keys for MLS data platforms so the
// v2 listing import has somewhere to plug in the moment credentials arrive.
//
// The whole form is driven by the server's provider registry (GET /api/mls)
// — this file knows nothing about specific platforms, so adding one on the
// server lights it up here automatically.
//
// Secret handling: secret fields are write-only. A saved secret renders as a
// password input with a "saved" placeholder and is never fetched back;
// saving always re-sends the full set of fields for that platform.

const MlsSection = () => {
    const [data, setData] = React.useState(null);       // GET /api/mls payload
    const [open, setOpen] = React.useState(null);       // provider id with form expanded
    const [form, setForm] = React.useState({});         // field key → value being typed
    const [agreed, setAgreed] = React.useState({});     // attestation id → checked
    const [busy, setBusy] = React.useState(false);
    const [error, setError] = React.useState(null);
    const [notice, setNotice] = React.useState(null);

    const load = () => api.getMlsProviders().then(setData).catch(err => setError(err.message));
    React.useEffect(() => { load(); }, []);

    const openForm = (p) => {
        // Pre-fill non-secret values so editing doesn't force retyping IDs.
        const initial = {};
        p.fields.forEach(f => {
            if (!f.secret && typeof p.values[f.key] === 'string') initial[f.key] = p.values[f.key];
        });
        setForm(initial); setAgreed({}); setOpen(p.id); setError(null); setNotice(null);
    };

    // Server enforces this too (the checkboxes ride along as attestation ids)
    // — the UI just refuses to enable Save until everything is confirmed.
    const allAgreed = (data?.attestations || []).every(a => agreed[a.id]);

    const save = async (p) => {
        setBusy(true); setError(null);
        try {
            const res = await api.saveMlsCredentials(p.id, {
                ...form,
                attestations: Object.keys(agreed).filter(id => agreed[id]),
            });
            setNotice(res.message); setOpen(null); setForm({}); setAgreed({});
            await load();
        } catch (err) { setError(err.message); }
        finally { setBusy(false); }
    };

    const remove = async (p) => {
        if (!await confirmAction(`Remove the saved ${p.label} credentials?`)) return;
        setBusy(true); setError(null);
        try {
            await api.removeMlsCredentials(p.id);
            setNotice(`${p.label} credentials removed.`); setOpen(null);
            await load();
        } catch (err) { setError(err.message); }
        finally { setBusy(false); }
    };

    if (!data) return <div className="settings-form"><p style={{ color: 'var(--text-3)' }}>{error || 'Loading…'}</p></div>;

    return (
        <div className="settings-form">
            <p style={{ fontSize: '0.875rem', color: 'var(--text-3)', marginBottom: '1rem' }}>
                When your MLS grants data access, it happens through one of these platforms —
                save the keys they issue here and SPEC's listing import can use them.
                Keys are encrypted before they're stored and are never shown again once saved.
            </p>

            {!data.crypto_ready && (
                <p style={{ color: 'var(--danger)', fontSize: '0.875rem', marginBottom: '1rem' }}>
                    <i className="fas fa-exclamation-triangle"></i>{' '}
                    Credential encryption isn't configured on this server (MLS_CRED_KEY) — saving is disabled.
                </p>
            )}
            {error && <p style={{ color: 'var(--danger)', fontSize: '0.875rem', marginBottom: '0.75rem' }}>{error}</p>}
            {notice && !error && <p style={{ color: 'var(--success)', fontSize: '0.875rem', marginBottom: '0.75rem' }}><i className="fas fa-check"></i> {notice}</p>}

            {data.providers.map(p => (
                <div key={p.id} style={{ border: '1px solid var(--border)', borderRadius: '8px', padding: '1rem', marginBottom: '0.75rem' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', flexWrap: 'wrap' }}>
                        <div style={{ flex: 1, minWidth: '200px' }}>
                            <div style={{ fontWeight: 600 }}>{p.label}</div>
                            <div style={{ fontSize: '0.8125rem', color: 'var(--text-3)' }}>
                                {p.configured
                                    ? <><i className="fas fa-check-circle" style={{ color: 'var(--success)' }}></i> Keys saved{p.status === 'error' ? ' — needs attention' : ''}</>
                                    : 'Not connected'}
                                {' · '}
                                <a href={p.docs_url} target="_blank" rel="noopener noreferrer">platform docs</a>
                            </div>
                            {p.last_error && <div style={{ fontSize: '0.8125rem', color: 'var(--danger)', marginTop: '0.25rem' }}>{p.last_error}</div>}
                            {p.attestation && (
                                <div style={{ fontSize: '0.75rem', color: 'var(--text-3)', marginTop: '0.25rem' }}>
                                    <i className="fas fa-file-signature"></i>{' '}
                                    Confirmed{p.attestation.by ? ` by ${p.attestation.by}` : ''} on {new Date(p.attestation.at).toLocaleDateString()}
                                </div>
                            )}
                        </div>
                        {open !== p.id && (
                            <div style={{ display: 'flex', gap: '0.5rem' }}>
                                <button className="btn btn-secondary" disabled={busy || !data.crypto_ready} onClick={() => openForm(p)}>
                                    {p.configured ? 'Replace keys' : 'Add keys'}
                                </button>
                                {p.configured && (
                                    <button className="btn btn-secondary" disabled={busy} onClick={() => remove(p)} title="Remove saved credentials">
                                        <i className="fas fa-trash"></i>
                                    </button>
                                )}
                            </div>
                        )}
                    </div>

                    {open === p.id && (
                        <div style={{ marginTop: '0.75rem' }}>
                            {p.fields.map(f => (
                                <div key={f.key} className="form-group" style={{ marginBottom: '0.6rem' }}>
                                    <label style={{ fontSize: '0.8125rem' }}>{f.label}</label>
                                    <input
                                        type={f.secret ? 'password' : 'text'}
                                        autoComplete="off"
                                        value={form[f.key] || ''}
                                        placeholder={f.secret && p.values[f.key]?.set ? '•••••••• (saved — paste to replace)' : ''}
                                        onChange={e => setForm({ ...form, [f.key]: e.target.value })}
                                    />
                                </div>
                            ))}
                            <div style={{ margin: '0.75rem 0', padding: '0.75rem', background: 'var(--bg-2)', borderRadius: '6px' }}>
                                {data.attestations.map(a => (
                                    <label key={a.id} style={{ display: 'flex', gap: '0.5rem', alignItems: 'flex-start', fontSize: '0.8125rem', marginBottom: '0.5rem', cursor: 'pointer' }}>
                                        <input
                                            type="checkbox"
                                            checked={!!agreed[a.id]}
                                            onChange={e => setAgreed({ ...agreed, [a.id]: e.target.checked })}
                                            style={{ marginTop: '0.2rem' }}
                                        />
                                        <span>{a.text}</span>
                                    </label>
                                ))}
                                <div style={{ fontSize: '0.75rem', color: 'var(--text-3)' }}>
                                    Your name and today's date are recorded with this confirmation.
                                </div>
                            </div>
                            <div style={{ display: 'flex', gap: '0.5rem' }}>
                                <button className="btn btn-primary" disabled={busy || !allAgreed} onClick={() => save(p)}
                                        title={allAgreed ? '' : 'Check each confirmation first'}>
                                    {busy ? <><i className="fas fa-spinner fa-spin"></i> Saving…</> : 'Save keys'}
                                </button>
                                <button className="btn btn-secondary" disabled={busy} onClick={() => { setOpen(null); setForm({}); }}>Cancel</button>
                            </div>
                        </div>
                    )}
                </div>
            ))}
        </div>
    );
};
