// Integrations — connect GitHub so commits show up on client-account
// timelines. Self-fetching like MilestonesSection: not needed app-wide.
//
// The token field is write-only by design: the server validates it against
// GitHub, encrypts it, and never returns it — so there is nothing to "show"
// after connecting except who it authenticates as.

const IntegrationsSection = ({ currentUser }) => {
    const [connections, setConnections] = React.useState([]);
    const [token, setToken]   = React.useState('');
    const [label, setLabel]   = React.useState('');
    const [saving, setSaving] = React.useState(false);
    const [error, setError]   = React.useState('');

    const refresh = () => api.getIntegrations().then(setConnections).catch(() => {});
    React.useEffect(() => { refresh(); }, []);

    const github = connections.find(c => c.provider === 'github');

    const handleConnect = async (e) => {
        e.preventDefault();
        setSaving(true); setError('');
        try {
            await api.createIntegration({ provider: 'github', token: token.trim(), label: label.trim() });
            setToken(''); setLabel('');
            refresh();
        } catch (err) { setError(err.message); }
        finally { setSaving(false); }
    };

    const handleDisconnect = async () => {
        if (!window.confirm('Disconnect GitHub? Repo wirings will be removed; commits already on timelines stay.')) return;
        try { await api.deleteIntegration(github.id); refresh(); }
        catch (err) { alert(err.message); }
    };

    return (
        <div className="settings-form">
            <p style={{ fontSize: '0.875rem', color: 'var(--text-3)', marginBottom: '1.25rem' }}>
                Connect your GitHub account and wire repositories to client accounts — commits
                then appear on that client's activity timeline automatically, so the work you
                ship for them is part of their story.
            </p>

            {github ? (
                <div className="detail-info-card" style={{ maxWidth: 560 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
                        <i className="fab fa-github" style={{ fontSize: '1.5rem' }}></i>
                        <div style={{ flex: 1 }}>
                            <div style={{ fontWeight: 600 }}>
                                {github.label || 'GitHub'}
                                {github.provider_login && <span style={{ color: 'var(--text-3)', fontWeight: 400 }}> — connected as {github.provider_login}</span>}
                            </div>
                            <div style={{ fontSize: '0.8125rem', marginTop: '0.15rem' }}>
                                {github.status === 'active'
                                    ? <span style={{ color: 'var(--success, #22c55e)' }}><i className="fas fa-check-circle"></i> Active</span>
                                    : <span style={{ color: 'var(--danger, #ef4444)' }}><i className="fas fa-exclamation-circle"></i> {github.status === 'revoked' ? 'Token expired or revoked — reconnect with a fresh token' : 'Error'}{github.last_error ? ` · ${github.last_error}` : ''}</span>}
                            </div>
                        </div>
                        <button className="btn btn-danger btn-small" onClick={handleDisconnect}>
                            <i className="fas fa-unlink"></i> Disconnect
                        </button>
                    </div>
                    <p style={{ fontSize: '0.8125rem', color: 'var(--text-3)', marginTop: '0.75rem', marginBottom: 0 }}>
                        Wire repos to accounts from an account's Activity tab (managers and admins).
                    </p>
                </div>
            ) : (
                <form onSubmit={handleConnect} style={{ maxWidth: 560 }}>
                    {error && <div className="api-error">{error}</div>}

                    <div className="detail-info-card" style={{ marginBottom: '1rem' }}>
                        <div style={{ fontWeight: 600, marginBottom: '0.5rem' }}>
                            <i className="fab fa-github" style={{ marginRight: '0.4rem' }}></i>
                            Get a token from GitHub — takes about a minute
                        </div>
                        <ol style={{ fontSize: '0.8125rem', color: 'var(--text-2)', lineHeight: 1.7, margin: 0, paddingLeft: '1.25rem' }}>
                            <li>
                                <a href="https://github.com/settings/personal-access-tokens/new" target="_blank" rel="noopener noreferrer">
                                    Open GitHub's new-token page <i className="fas fa-external-link-alt" style={{ fontSize: '0.65rem' }}></i>
                                </a>
                                {' '}(a <strong>fine-grained</strong> personal access token)
                            </li>
                            <li><strong>Repository access:</strong> "Only select repositories" — pick the repos you want on client timelines</li>
                            <li><strong>Permissions → Contents:</strong> Read-only. That's the only permission it needs.</li>
                            <li>Set an expiration — this page will show when it needs renewing</li>
                            <li>Generate, copy the token, and paste it below</li>
                        </ol>
                    </div>

                    <div className="form-group">
                        <label className="form-label">Personal Access Token *</label>
                        <input className="form-input" type="password" value={token}
                               onChange={e => setToken(e.target.value)}
                               placeholder="github_pat_…" required autoComplete="off" />
                        <p style={{ fontSize: '0.75rem', color: 'var(--text-3)', marginTop: '0.35rem' }}>
                            The token is verified with GitHub before it's saved, and stored encrypted.
                        </p>
                    </div>
                    <div className="form-group">
                        <label className="form-label">Label</label>
                        <input className="form-input" value={label} onChange={e => setLabel(e.target.value)}
                               placeholder="e.g. Company GitHub" maxLength={100} />
                    </div>
                    <button type="submit" className="btn btn-primary" disabled={saving || !token.trim()}>
                        {saving ? <><i className="fas fa-spinner fa-spin"></i> Checking with GitHub…</> : <><i className="fab fa-github"></i> Connect GitHub</>}
                    </button>
                </form>
            )}
        </div>
    );
};
