// Domain Providers — the registrar accounts this workspace HOLDS (metadata
// only: provider, label, notes — credentials live in a password manager,
// never here, by design). The quote-accept flow matches a customer's
// provider choice against this list: a hit links their account
// automatically, a miss opens a follow-up task. Milestones pattern:
// self-fetching, admin-gated by the Settings card.

const ProvidersSection = () => {
    const [data, setData]       = React.useState(null); // { providers, accounts }
    const [form, setForm]       = React.useState({ provider: '', label: '', notes: '' });
    const [saving, setSaving]   = React.useState(false);
    const [editing, setEditing] = React.useState(null); // { id, provider, label, notes } mid-edit
    const [newProv, setNewProv] = React.useState('');   // vocabulary: name being added
    const [renaming, setRenaming] = React.useState(null); // vocabulary: { id, name } mid-rename

    // A failed refresh after a mutation must not show a silently stale list
    // (swallowed-error rule) — surface it with a retry.
    const [loadErr, setLoadErr] = React.useState(false);
    const refresh = () => api.getProviderAccounts().then(d => { setData(d); setLoadErr(false); }).catch(() => setLoadErr(true));
    React.useEffect(() => { refresh(); }, []);

    const providerName = (key) => data?.providers.find(p => p.key === key)?.name || key;

    const handleAdd = async (e) => {
        e.preventDefault();
        if (!form.provider || !form.label.trim()) return;
        setSaving(true);
        try {
            await api.addProviderAccount({ provider: form.provider, label: form.label.trim(), notes: form.notes.trim() || null });
            setForm({ provider: '', label: '', notes: '' });
            refresh();
        } catch (err) { alert(err.message); }
        finally { setSaving(false); }
    };

    const handleSaveEdit = async (e) => {
        e.preventDefault();
        if (!editing.provider || !editing.label.trim()) return;
        try {
            await api.updateProviderAccount(editing.id, { provider: editing.provider, label: editing.label.trim(), notes: editing.notes.trim() || null });
            setEditing(null); refresh();
        } catch (err) { alert(err.message); }
    };

    const handleDelete = async (a) => {
        if (!window.confirm(`Remove "${a.label}"? Customer accounts keep their provider name — only the registry link goes away.`)) return;
        try { await api.deleteProviderAccount(a.id); refresh(); }
        catch (err) { alert(err.message); }
    };

    // ── Vocabulary (the picker's contents — per-tenant since 0046) ──
    const handleAddProvider = async (e) => {
        e.preventDefault();
        if (!newProv.trim()) return;
        try { await api.addDomainProvider({ name: newProv.trim() }); setNewProv(''); refresh(); }
        catch (err) { alert(err.message); }
    };
    const handleRenameProvider = async (e) => {
        e.preventDefault();
        if (!renaming.name.trim()) return;
        try { await api.updateDomainProvider(renaming.id, { name: renaming.name.trim() }); setRenaming(null); refresh(); }
        catch (err) { alert(err.message); }
    };
    const handleDeleteProvider = async (p) => {
        if (!window.confirm(`Remove "${p.name}" from the picker? Existing records keep the name; the server refuses if registry entries still use it.`)) return;
        try { await api.deleteDomainProvider(p.id); refresh(); }
        catch (err) { alert(err.message); }
    };

    if (!data) {
        return loadErr
            ? <LoadErrorBanner what="providers" hasData={false} onRetry={refresh} />
            : <p style={{ color: 'var(--text-3)' }}>Loading…</p>;
    }

    return (
        <div className="settings-form">
            {loadErr && (
                <LoadErrorBanner what="providers" hasData={true} onRetry={refresh} />
            )}
            <p style={{ fontSize: '0.875rem', color: 'var(--text-3)', marginBottom: '0.5rem' }}>
                List the registrar accounts you hold. When a customer accepts a quote and picks
                their domain provider, a match here connects them automatically — no match opens
                a follow-up task instead.
            </p>
            <p style={{ fontSize: '0.75rem', color: 'var(--text-3)', marginBottom: '1.25rem' }}>
                <i className="fas fa-lock" style={{ marginRight: '0.35rem' }}></i>
                Metadata only — passwords and API keys belong in your password manager, never in the CRM.
            </p>

            {/* Provider list — what customers see in the accept-page picker. */}
            <div className="detail-info-card" style={{ marginBottom: '1.5rem' }}>
                <div className="detail-info-label" style={{ marginBottom: '0.5rem' }}>Provider list (shown to customers)</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.4rem', marginBottom: '0.75rem' }}>
                    {data.providers.map(p => renaming?.id === p.id ? (
                        <form key={p.id} onSubmit={handleRenameProvider} style={{ display: 'inline-flex', gap: '0.25rem' }}>
                            <input className="form-input" style={{ width: 150, padding: '0.2rem 0.5rem' }} autoFocus
                                   value={renaming.name} maxLength={100}
                                   onChange={e => setRenaming(r => ({ ...r, name: e.target.value }))} />
                            <button type="submit" className="btn btn-primary btn-small"><i className="fas fa-check"></i></button>
                            <button type="button" className="btn btn-secondary btn-small" onClick={() => setRenaming(null)}><i className="fas fa-times"></i></button>
                        </form>
                    ) : (
                        <span key={p.id} className="tag-pill" style={{ display: 'inline-flex', alignItems: 'center', gap: '0.35rem' }}>
                            {p.name}
                            <i className="fas fa-pencil-alt" style={{ cursor: 'pointer', fontSize: '0.65rem' }}
                               title="Rename" onClick={() => setRenaming({ id: p.id, name: p.name })}></i>
                            <i className="fas fa-times" style={{ cursor: 'pointer', fontSize: '0.7rem' }}
                               title="Remove from picker" onClick={() => handleDeleteProvider(p)}></i>
                        </span>
                    ))}
                </div>
                <form onSubmit={handleAddProvider} style={{ display: 'flex', gap: '0.5rem' }}>
                    <input className="form-input" style={{ maxWidth: 220 }} placeholder="Add a provider…"
                           value={newProv} maxLength={100} onChange={e => setNewProv(e.target.value)} />
                    <button type="submit" className="btn btn-secondary btn-small" disabled={!newProv.trim()}>
                        <i className="fas fa-plus"></i> Add
                    </button>
                </form>
            </div>

            <form onSubmit={handleAdd} style={{ display: 'flex', gap: '0.75rem', alignItems: 'flex-end', marginBottom: '1.5rem', flexWrap: 'wrap' }}>
                <div className="form-group" style={{ minWidth: 160 }}>
                    <label className="form-label">Provider</label>
                    <select className="form-input" value={form.provider} onChange={e => setForm(p => ({ ...p, provider: e.target.value }))}>
                        <option value="">Choose…</option>
                        {data.providers.map(p => <option key={p.key} value={p.key}>{p.name}</option>)}
                    </select>
                </div>
                <div className="form-group" style={{ flex: 1, minWidth: 180 }}>
                    <label className="form-label">Label</label>
                    <input className="form-input" value={form.label} maxLength={255}
                           placeholder='e.g. "Main Namecheap account"'
                           onChange={e => setForm(p => ({ ...p, label: e.target.value }))} />
                </div>
                <button type="submit" className="btn btn-primary btn-small" disabled={saving || !form.provider || !form.label.trim()}>
                    <i className="fas fa-plus"></i> Add
                </button>
            </form>

            {data.accounts.length === 0 ? (
                <p style={{ color: 'var(--text-3)', fontSize: '0.875rem' }}>No provider accounts on record yet.</p>
            ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
                    {data.accounts.map(a => editing?.id === a.id ? (
                        <form key={a.id} onSubmit={handleSaveEdit} className="detail-info-card" style={{ display: 'flex', alignItems: 'flex-end', gap: '0.75rem', flexWrap: 'wrap' }}>
                            <div className="form-group" style={{ minWidth: 150, marginBottom: 0 }}>
                                <label className="form-label">Provider</label>
                                <select className="form-input" value={editing.provider} onChange={e => setEditing(p => ({ ...p, provider: e.target.value }))}>
                                    {data.providers.map(p => <option key={p.key} value={p.key}>{p.name}</option>)}
                                </select>
                            </div>
                            <div className="form-group" style={{ flex: 1, minWidth: 160, marginBottom: 0 }}>
                                <label className="form-label">Label</label>
                                <input className="form-input" value={editing.label} maxLength={255}
                                       onChange={e => setEditing(p => ({ ...p, label: e.target.value }))} />
                            </div>
                            <div className="form-group" style={{ flex: 1, minWidth: 160, marginBottom: 0 }}>
                                <label className="form-label">Notes</label>
                                <input className="form-input" value={editing.notes}
                                       onChange={e => setEditing(p => ({ ...p, notes: e.target.value }))} />
                            </div>
                            <button type="submit" className="btn btn-primary btn-small"><i className="fas fa-check"></i></button>
                            <button type="button" className="btn btn-secondary btn-small" onClick={() => setEditing(null)}><i className="fas fa-times"></i></button>
                        </form>
                    ) : (
                        <div key={a.id} className="detail-info-card" style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
                            <div style={{ flex: 1 }}>
                                <div style={{ fontWeight: 600 }}>{providerName(a.provider)}
                                    <span style={{ marginLeft: '0.5rem', color: 'var(--text-3)', fontWeight: 400 }}>{a.label}</span>
                                </div>
                                {a.notes && <div style={{ fontSize: '0.75rem', color: 'var(--text-3)', marginTop: '0.15rem' }}>{a.notes}</div>}
                            </div>
                            <button className="btn-icon-sm" title="Edit" onClick={() => setEditing({ id: a.id, provider: a.provider, label: a.label, notes: a.notes || '' })}>
                                <i className="fas fa-pencil-alt"></i>
                            </button>
                            <button className="btn-icon-sm danger" title="Remove" onClick={() => handleDelete(a)}>
                                <i className="fas fa-trash"></i>
                            </button>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
};
