'use client'; import { useState, useEffect } from 'react'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Github, Loader2, CheckCircle2, ExternalLink, X } from 'lucide-react'; import { auth } from '@/lib/firebase/config'; import { doc, updateDoc, serverTimestamp } from 'firebase/firestore'; import { db } from '@/lib/firebase/config'; import { toast } from 'sonner'; import { initiateGitHubOAuth } from '@/lib/github/oauth'; interface GitHubRepoPickerProps { projectId: string; onRepoSelected?: (repo: any) => void; onClose?: () => void; } export function GitHubRepoPicker({ projectId, onRepoSelected, onClose }: GitHubRepoPickerProps) { const [loading, setLoading] = useState(false); const [connected, setConnected] = useState(false); const [repos, setRepos] = useState([]); const [selectedRepo, setSelectedRepo] = useState(null); const [saving, setSaving] = useState(false); useEffect(() => { checkConnection(); }, []); const checkConnection = async () => { setLoading(true); try { const user = auth.currentUser; if (!user) return; const token = await user.getIdToken(); const statusResponse = await fetch('/api/github/connect', { headers: { 'Authorization': `Bearer ${token}`, }, }); if (statusResponse.ok) { const statusData = await statusResponse.json(); setConnected(statusData.connected); if (statusData.connected) { const reposResponse = await fetch('/api/github/repos', { headers: { 'Authorization': `Bearer ${token}`, }, }); if (reposResponse.ok) { const reposData = await reposResponse.json(); setRepos(reposData); } } } } catch (error) { console.error('Error checking GitHub connection:', error); } finally { setLoading(false); } }; const handleConnect = () => { const redirectUri = `${window.location.origin}/api/github/oauth/callback`; initiateGitHubOAuth(redirectUri); }; const handleSelectRepo = async (repo: any) => { setSelectedRepo(repo); setSaving(true); try { const user = auth.currentUser; if (!user) { toast.error('Please sign in'); return; } // Update project with GitHub info await updateDoc(doc(db, 'projects', projectId), { githubRepo: repo.full_name, githubRepoId: repo.id, githubRepoUrl: repo.html_url, githubDefaultBranch: repo.default_branch, hasGithub: true, updatedAt: serverTimestamp(), }); // Try to automatically associate existing sessions with this repo try { const token = await user.getIdToken(); const associateResponse = await fetch(`/api/projects/${projectId}/associate-github-sessions`, { method: 'POST', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ githubRepo: repo.full_name, githubRepoUrl: repo.html_url, }), }); if (associateResponse.ok) { const data = await associateResponse.json(); console.log('🔗 Session association result:', data); if (data.sessionsAssociated > 0) { toast.success(`Connected to ${repo.full_name}!`, { description: `Found and linked ${data.sessionsAssociated} existing chat sessions from this repository`, duration: 5000, }); } else { // No sessions found - show helpful message toast.success(`Connected to ${repo.full_name}!`, { description: `Repository linked! Future chat sessions from this repo will be automatically tracked here.`, duration: 5000, }); console.log(`â„šī¸ No matching sessions found. This could mean: - No chat sessions exist yet for this repo - Sessions are already linked to other projects - Workspace folder name doesn't match repo name (${repo.name})`); } } else { // Connection succeeded but session association failed - still show success toast.success(`Connected to ${repo.full_name}!`); console.warn('Session association failed but connection succeeded'); } } catch (associateError) { // Don't fail the whole operation if association fails console.error('Error associating sessions:', associateError); toast.success(`Connected to ${repo.full_name}!`); } // Notify parent component if (onRepoSelected) { onRepoSelected(repo); } } catch (error) { console.error('Error connecting repo:', error); toast.error('Failed to connect repository'); setSelectedRepo(null); } finally { setSaving(false); } }; if (loading) { return ( ); } if (!connected) { return ( Connect GitHub Connect your GitHub account to select a repository ); } if (selectedRepo) { return (

{selectedRepo.full_name}

Repository connected!

View {onClose && ( )}
); } return ( Select Repository Choose which repository to connect to this project
{repos.length === 0 ? (

No repositories found

) : ( repos.map((repo) => ( )) )}
); }