"use client"

import { Suspense, useEffect } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { MainDashboard } from "@/components/main-dashboard"
import { useAuth } from "@/contexts/auth-context"

// Component that uses useSearchParams - needs to be wrapped in Suspense
function ProjectBuilderContent() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { user, isLoading } = useAuth()

  useEffect(() => {
    if (isLoading) return
    if (!user) {
      const returnUrl = encodeURIComponent("/project-builder")
      router.replace(`/signin?returnUrl=${returnUrl}`)
    }
  }, [user, isLoading, router])

  // Handle GitHub OAuth callback parameters
  useEffect(() => {
    if (isLoading || !user) return

    const githubConnected = searchParams.get('github_connected')
    const githubUser = searchParams.get('user')
    const processing = searchParams.get('processing')
    const repoAttached = searchParams.get('repo_attached')
    const repositoryId = searchParams.get('repository_id')
    const syncStatus = searchParams.get('sync_status')

    if (githubConnected === '1') {
      console.log('🎉 GitHub OAuth callback successful!', {
        githubUser,
        processing,
        repoAttached,
        repositoryId,
        syncStatus
      })

      // Clear any pending git attach from sessionStorage
      try {
        sessionStorage.removeItem('pending_git_attach')
      } catch (e) {
        console.warn('Failed to clear pending attach:', e)
      }

      // Show success message
      if (processing === '1') {
        // Repository is being processed in background
        alert(`GitHub account connected successfully!\n\nGitHub User: ${githubUser}\n\nYour repository is being processed in the background. This may take a few moments.\n\nYou can start working, and the repository will be available shortly.`)
      } else if (repoAttached === '1' && repositoryId) {
        alert(`Repository attached successfully!\n\nGitHub User: ${githubUser}\nRepository ID: ${repositoryId}\nSync Status: ${syncStatus}`)
      } else {
        // Generic success message
        alert(`GitHub account connected successfully!\n\nGitHub User: ${githubUser}`)
      }

      // Clean up URL parameters
      router.replace('/project-builder')
    }
  }, [isLoading, user, searchParams, router])

  if (isLoading || !user) {
    return <div className="min-h-screen flex items-center justify-center">Loading...</div>
  }

  return <MainDashboard />
}

export default function ProjectBuilderPage() {
  return (
    <Suspense fallback={<div className="min-h-screen flex items-center justify-center">Loading...</div>}>
      <ProjectBuilderContent />
    </Suspense>
  )
}
