// 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 = ({ currentUser }) => {
    const [data, setData]       = React.useState(null); // { providers, accounts }
    const [form, setForm]       = React.useState({ provider: '', label: '', notes: '' });
    const [saving, setSaving]   = React.useState(false);

    const refresh = () => api.getProviderAccounts().then(setData).catch(() => {});
    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 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); }
    };

    if (!data) return <p style={{ color: 'var(--text-3)' }}>Loading…</p>;

    return (
        <div className="settings-form">
            <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>

            <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 => (
                        <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 danger" title="Remove" onClick={() => handleDelete(a)}>
                                <i className="fas fa-trash"></i>
                            </button>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
};
