// Wire a repo to this account — manager/admin, opened from the Activity tab.
// Lists what's already wired (with sync state + unwire), then a picker of
// repos the GitHub connection can see. "Sync now" exists so wiring a repo
// gives instant gratification instead of "wait for the next poll".

const RepoWireModal = ({ accountId, onChanged, onClose }) => {
    const [wirings, setWirings]         = React.useState([]);
    const [connections, setConnections] = React.useState(null); // null = loading
    const [repos, setRepos]             = React.useState(null);
    const [selectedRepo, setSelectedRepo] = React.useState('');
    const [busy, setBusy]               = React.useState(false);
    const [error, setError]             = React.useState('');
    const [notice, setNotice]           = React.useState('');

    const github = (connections || []).find(c => c.provider === 'github' && c.status === 'active');

    const refreshWirings = () => api.getRepoWiring(accountId).then(setWirings).catch(() => {});

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

    // Repo list is fetched lazily once we know there's a live connection —
    // it's a GitHub round-trip, no point spending it when nothing's connected.
    React.useEffect(() => {
        if (github) api.getIntegrationRepos(github.id).then(setRepos).catch(err => setError(err.message));
    }, [github?.id]);

    const handleWire = async (e) => {
        e.preventDefault();
        if (!selectedRepo) return;
        setBusy(true); setError(''); setNotice('');
        try {
            const wiring = await api.wireRepo({ integration_id: github.id, account_id: accountId, repo: selectedRepo });
            setSelectedRepo('');
            // First sync right away — the last 30 days of commits land now.
            try {
                const r = await api.syncRepoWiring(wiring.id);
                setNotice(r.message);
            } catch (syncErr) {
                setNotice(`Wired — first sync failed (${syncErr.message}); the poller will retry.`);
            }
            refreshWirings();
            onChanged && onChanged();
        } catch (err) { setError(err.message); }
        finally { setBusy(false); }
    };

    const handleUnwire = async (w) => {
        if (!window.confirm(`Stop tracking ${w.repo} on this account? Commits already on the timeline stay.`)) return;
        try { await api.unwireRepo(w.id); refreshWirings(); onChanged && onChanged(); }
        catch (err) { alert(err.message); }
    };

    const handleSync = async (w) => {
        setBusy(true); setError(''); setNotice('');
        try {
            const r = await api.syncRepoWiring(w.id);
            setNotice(`${w.repo}: ${r.message}`);
            refreshWirings();
            onChanged && onChanged();
        } catch (err) { setError(err.message); }
        finally { setBusy(false); }
    };

    const wiredNames = new Set(wirings.map(w => w.repo));

    return (
        <Modal isOpen={true} onClose={onClose} title="Repos on this timeline">
            {error && <div className="api-error">{error}</div>}
            {notice && <div style={{ fontSize: '0.8125rem', color: 'var(--success, #22c55e)', marginBottom: '0.75rem' }}><i className="fas fa-check-circle"></i> {notice}</div>}

            {wirings.length > 0 && (
                <div style={{ marginBottom: '1.25rem' }}>
                    {wirings.map(w => (
                        <div key={w.id} className="contact-card-detail" style={{ marginBottom: '0.375rem', gap: '0.5rem' }}>
                            <i className="fab fa-github"></i>
                            <span style={{ fontWeight: 600, flex: 1 }}>{w.repo}</span>
                            {w.status === 'error'
                                ? <span className="badge secondary" title={w.last_error} style={{ color: 'var(--danger, #ef4444)' }}>sync error</span>
                                : <span style={{ fontSize: '0.75rem', color: 'var(--text-3)' }}>{w.last_synced_at ? `synced ${formatDate(w.last_synced_at)}` : 'not synced yet'}</span>}
                            <button className="btn-icon-sm" title="Sync now" disabled={busy} onClick={() => handleSync(w)}>
                                <i className="fas fa-sync-alt"></i>
                            </button>
                            <button className="btn-icon-sm danger" title="Stop tracking" onClick={() => handleUnwire(w)}>
                                <i className="fas fa-times"></i>
                            </button>
                        </div>
                    ))}
                </div>
            )}

            {connections === null ? (
                <div className="loading-state"><i className="fas fa-spinner fa-spin"></i> Loading…</div>
            ) : !github ? (
                <p style={{ fontSize: '0.875rem', color: 'var(--text-3)' }}>
                    {(connections || []).length
                        ? 'The GitHub connection needs attention — check Settings → Integrations.'
                        : 'No GitHub connection yet — an admin can add one in Settings → Integrations.'}
                </p>
            ) : (
                <form onSubmit={handleWire}>
                    <div className="form-group">
                        <label className="form-label">Wire a repo</label>
                        {repos === null ? (
                            <div className="loading-state" style={{ padding: '0.5rem 0' }}><i className="fas fa-spinner fa-spin"></i> Fetching repos from GitHub…</div>
                        ) : (
                            <select className="form-input" value={selectedRepo} onChange={e => setSelectedRepo(e.target.value)}>
                                <option value="">— Choose a repository —</option>
                                {repos.filter(r => !wiredNames.has(r.full_name)).map(r => (
                                    <option key={r.full_name} value={r.full_name}>
                                        {r.full_name}{r.private ? ' (private)' : ''}
                                    </option>
                                ))}
                            </select>
                        )}
                        <p style={{ fontSize: '0.75rem', color: 'var(--text-3)', marginTop: '0.35rem' }}>
                            New commits land on this account's timeline — subject line, author, and a
                            link only. The last 30 days are pulled in when you wire it.
                        </p>
                    </div>
                    <div className="btn-group">
                        <button type="button" className="btn btn-secondary" onClick={onClose}>Close</button>
                        <button type="submit" className="btn btn-primary" disabled={busy || !selectedRepo}>
                            {busy ? <><i className="fas fa-spinner fa-spin"></i> Wiring…</> : <><i className="fas fa-plug"></i> Wire Repo</>}
                        </button>
                    </div>
                </form>
            )}
        </Modal>
    );
};
