import React, { useState, useEffect } from 'react'; import { GitBranch, GitCommit, FolderGit2, CheckCircle2, AlertCircle, ExternalLink, RefreshCw, Eye, EyeOff, LogOut, UploadCloud, Check, Zap, } from 'lucide-react'; import { getGitHubConfig, getStoredGitHubUser, saveGitHubConfig, clearGitHubConfig, connectWithGitHubOAuth, verifyGitHubToken, initGitHubRepo, syncAllSolutionsToGitHub, pushSolutionToGitHub, } from '../services/githubSyncService'; import type { GitHubConfig, GitHubUser, PushSolutionPayload } from '../types/githubTypes'; interface GitHubSyncWindowProps { onClose: () => void; currentProblem?: { id?: string; problem_number?: number | null; name?: string; difficulty?: string; pattern?: string; optimal_time?: string; optimal_space?: string; description?: string; reference_code?: string; code?: string; } | null; } export const GitHubSyncWindow: React.FC = ({ onClose, currentProblem, }) => { const [config, setConfig] = useState(() => getGitHubConfig()); const [user, setUser] = useState(() => getStoredGitHubUser()); const [manualToken, setManualToken] = useState(''); const [showManualInput, setShowManualInput] = useState(false); const [showToken, setShowToken] = useState(false); // States const [connectingOAuth, setConnectingOAuth] = useState(false); const [verifyingToken, setVerifyingToken] = useState(false); const [initializingRepo, setInitializingRepo] = useState(false); const [syncingAll, setSyncingAll] = useState(false); const [pushingCurrent, setPushingCurrent] = useState(false); const [statusMessage, setStatusMessage] = useState<{ type: 'success' | 'error' | 'info'; text: string; linkUrl?: string; } | null>(null); const isConnected = Boolean(config.token && (config.username || user?.login)); // Sync state if user changes useEffect(() => { if (config.token && !user) { void verifyGitHubToken(config.token).then((res) => { if (res.valid && res.user) { setUser(res.user); saveGitHubConfig({ username: res.user.login }, res.user); } }); } }, [config.token, user]); const handleOAuthConnect = async () => { setConnectingOAuth(true); setStatusMessage(null); try { const { token, user: ghUser } = await connectWithGitHubOAuth(); setUser(ghUser); const updatedConfig = getGitHubConfig(); setConfig(updatedConfig); // Auto-initialize repository if not created try { await initGitHubRepo(token, updatedConfig.repoName, updatedConfig.isPrivate); } catch { // Safe fallback if repo check times out } setStatusMessage({ type: 'success', text: `Connected successfully to GitHub as @${ghUser.login}!`, linkUrl: ghUser.html_url, }); } catch (err: unknown) { const error = err as Error; setStatusMessage({ type: 'error', text: error.message || 'GitHub OAuth authorization failed.', }); } finally { setConnectingOAuth(false); } }; const handleManualTokenSubmit = async () => { const trimmed = manualToken.trim(); if (!trimmed) { setStatusMessage({ type: 'error', text: 'Please enter a valid GitHub token.' }); return; } setVerifyingToken(true); setStatusMessage(null); try { const res = await verifyGitHubToken(trimmed); if (res.valid && res.user) { setUser(res.user); saveGitHubConfig( { token: trimmed, username: res.user.login, }, res.user ); setConfig(getGitHubConfig()); // Initialize repository try { await initGitHubRepo(trimmed, config.repoName, config.isPrivate); } catch { // Ignore } setManualToken(''); setShowManualInput(false); setStatusMessage({ type: 'success', text: `Verified and connected as @${res.user.login}!`, linkUrl: res.user.html_url, }); } else { setStatusMessage({ type: 'error', text: res.error || 'Token verification failed. Please check permissions.', }); } } catch (err: unknown) { const error = err as Error; setStatusMessage({ type: 'error', text: error.message || 'Failed to connect with token.', }); } finally { setVerifyingToken(false); } }; const handleInitRepo = async () => { if (!config.token) return; setInitializingRepo(true); setStatusMessage(null); try { const res = await initGitHubRepo(config.token, config.repoName, config.isPrivate); saveGitHubConfig({ repoName: config.repoName }); setStatusMessage({ type: 'success', text: res.created ? `Created new repository ${res.full_name} on GitHub!` : `Connected to existing repository ${res.full_name}!`, linkUrl: res.html_url, }); } catch (err: unknown) { const error = err as Error; setStatusMessage({ type: 'error', text: error.message || 'Failed to initialize repository.', }); } finally { setInitializingRepo(false); } }; const handleSyncAll = async () => { if (!config.token || !config.repoName) return; setSyncingAll(true); setStatusMessage(null); try { const res = await syncAllSolutionsToGitHub(config.token, config.repoName, config.branch); setStatusMessage({ type: 'success', text: res.message || `Synced ${res.synced_count} solutions to ${config.repoName}!`, linkUrl: res.repo_url, }); } catch (err: unknown) { const error = err as Error; setStatusMessage({ type: 'error', text: error.message || 'Batch sync failed.', }); } finally { setSyncingAll(false); } }; const handlePushCurrent = async () => { if (!currentProblem || !config.token) return; const code = currentProblem.code || currentProblem.reference_code; if (!code || !code.trim()) { setStatusMessage({ type: 'error', text: 'Current problem has no code to push. Write or save code first!', }); return; } setPushingCurrent(true); setStatusMessage(null); try { const payload: PushSolutionPayload = { token: config.token, repo: config.repoName, branch: config.branch, problem_number: currentProblem.problem_number, problem_name: currentProblem.name || 'Algorithm Problem', difficulty: currentProblem.difficulty || 'Medium', pattern: currentProblem.pattern || 'Algorithms', optimal_time: currentProblem.optimal_time || 'O(N)', optimal_space: currentProblem.optimal_space || 'O(1)', description: currentProblem.description || '', code, }; const res = await pushSolutionToGitHub(payload); setStatusMessage({ type: 'success', text: `Committed ${currentProblem.name} to GitHub!`, linkUrl: res.html_url, }); } catch (err: unknown) { const error = err as Error; setStatusMessage({ type: 'error', text: error.message || 'Failed to push current solution.', }); } finally { setPushingCurrent(false); } }; const handleToggleAutoCommit = (enabled: boolean) => { saveGitHubConfig({ autoCommit: enabled }); setConfig((prev) => ({ ...prev, autoCommit: enabled })); setStatusMessage({ type: 'info', text: enabled ? 'Auto-commit ENABLED: Solutions will sync automatically on submission.' : 'Auto-commit DISABLED: You can still push manually any time.', }); }; const handleDisconnect = () => { if (window.confirm('Disconnect your GitHub account from AlgoSpaced?')) { clearGitHubConfig(); setConfig(getGitHubConfig()); setUser(null); setStatusMessage({ type: 'info', text: 'Disconnected from GitHub.' }); } }; return (
{/* Header Strip */}

GitHub Solutions Station

Sync algorithm solutions & auto-commit to your personal portfolio repository

{isConnected ? 'CONNECTED' : 'DISCONNECTED'}
{/* CONNECTED VIEW */} {isConnected ? (
{/* User Profile & Repo Banner */}
{user?.avatar_url ? ( {user.login} ) : (
GH
)}
{user?.name || user?.login || config.username} (@{user?.login || config.username})
{config.username || user?.login}/{config.repoName} ({config.branch})
View Repo
{/* Repository Configuration Card */}
Target Repository & Branch
{ const val = e.target.value; setConfig((p) => ({ ...p, repoName: val })); saveGitHubConfig({ repoName: val }); }} placeholder="algospaced-solutions" className="w-full bg-slate-50 border-2 border-ink-black rounded py-1.5 px-2.5 text-xs font-mono font-medium focus:outline-none focus:bg-white" />
{ const val = e.target.value; setConfig((p) => ({ ...p, branch: val })); saveGitHubConfig({ branch: val }); }} placeholder="main" className="w-full bg-slate-50 border-2 border-ink-black rounded py-1.5 px-2.5 text-xs font-mono font-medium focus:outline-none focus:bg-white" />
{/* Auto-Commit Toggle */}
Auto-commit on every submission Automatically push code to your repo when grading a review card or saving a solution.
{/* Sync & Push Operations Card */}
Manual Push & Sync Operations
{/* Push Current Problem */} {/* Batch Sync Entire Library */}
) : ( /* DISCONNECTED VIEW */
{/* 1-Click Connect Button Card */}

Connect Your GitHub Account

Sync all your DSA solutions directly to your GitHub repository. Commit automatically on review completion or push anytime with 1-click.

{/* Native OAuth Button */}
Direct 1-click OAuth (works for guest and signed-in users). Requests repo access.
{/* Manual Token Fallback Accordion */}
{showManualInput && (
Personal Access Token: Generate token with repo scope
setManualToken(e.target.value)} placeholder="ghp_... or github_pat_..." className="w-full bg-slate-50 border-2 border-ink-black rounded py-2 pl-3 pr-9 text-xs font-mono focus:outline-none focus:bg-white" />
)}
)} {/* Feedback Alert Banner */} {statusMessage && (
{statusMessage.type === 'success' ? ( ) : ( )} {statusMessage.text}
{statusMessage.linkUrl && ( Open )}
)}
{/* Footer Close Button */}
); }; export default GitHubSyncWindow;