'use client'
import { useState, useEffect, Suspense } from 'react'
import { useSearchParams, useRouter } from 'next/navigation'
import { LoginForm } from '@/components/auth/LoginForm'
import { RegisterForm } from '@/components/auth/RegisterForm'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { useAuth } from '@/contexts/AuthContext'
import { Header } from '@/components/header'
import { Footer } from '@/components/footer'
import Link from 'next/link'
import { BookOpen, Search, Settings, User, Edit, Tag } from 'lucide-react'

// Main auth component with search params handling
function AuthPageContent() {
  const searchParams = useSearchParams()
  const router = useRouter()
  const [mode, setMode] = useState<'login' | 'register'>('login')
  const [shouldRedirect, setShouldRedirect] = useState(false)

  useEffect(() => {
    const modeParam = searchParams.get('mode')
    if (modeParam === 'register') {
      setMode('register')
    }

    // Only redirect if there's a returnUrl (user was redirected here) or if they just logged in
    const returnUrl = searchParams.get('returnUrl')
    if (returnUrl) {
      setShouldRedirect(true)
    }
  }, [searchParams])
  const { user, logout, loading } = useAuth()

  // Only redirect if shouldRedirect is true (not just because user exists)
  useEffect(() => {
    if (!loading && user && shouldRedirect) {
      const returnUrl = searchParams.get('returnUrl')
      if (returnUrl) {
        router.push(decodeURIComponent(returnUrl))
      } else {
        router.push('/dashboard')
      }
    }
  }, [user, loading, router, searchParams, shouldRedirect])

  if (loading) {
    return (
      <div className="min-h-screen bg-background">
        <Header />
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
            <p>Loading...</p>
          </div>
        </div>
        <Footer />
      </div>
    )
  }

  if (user) {
    return (
      <div className="min-h-screen bg-background">
        <Header />
        <div className="container mx-auto px-4 pt-24 pb-8">
          <div className="max-w-4xl mx-auto space-y-6">
            {/* Welcome Section */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <User className="w-5 h-5" />
                  Welcome back, {user.name}!
                </CardTitle>
                <CardDescription>
                  You're logged in and ready to start creating amazing content
                </CardDescription>
              </CardHeader>
            </Card>

            {/* Quick Actions */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Edit className="w-5 h-5" />
                    Topic Management
                  </CardTitle>
                  <CardDescription>Create and manage your topics</CardDescription>
                </CardHeader>
                <CardContent className="space-y-3">
                  <Button asChild className="w-full justify-start">
                    <Link href="/topics/new">
                      <BookOpen className="w-4 h-4 mr-2" />
                      Create New Topic
                    </Link>
                  </Button>
                  <Button asChild variant="outline" className="w-full justify-start">
                    <Link href="/topics">
                      <Search className="w-4 h-4 mr-2" />
                      View All Topics
                    </Link>
                  </Button>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Settings className="w-5 h-5" />
                    Account Settings
                  </CardTitle>
                  <CardDescription>Manage your account and preferences</CardDescription>
                </CardHeader>
                <CardContent className="space-y-3">
                  <Button asChild variant="outline" className="w-full justify-start">
                    <Link href="/profile">
                      <User className="w-4 h-4 mr-2" />
                      Edit Profile
                    </Link>
                  </Button>
                  <Button asChild variant="outline" className="w-full justify-start">
                    <Link href="/dashboard">
                      <Settings className="w-4 h-4 mr-2" />
                      Dashboard
                    </Link>
                  </Button>
                  <Button
                    onClick={() => logout()}
                    variant="destructive"
                    className="w-full justify-start"
                  >
                    Sign Out
                  </Button>
                </CardContent>
              </Card>
            </div>

            {/* User Info */}
            <Card>
              <CardHeader>
                <CardTitle>Account Information</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                  <div>
                    <strong>Email:</strong> {user.email}
                  </div>
                  <div>
                    <strong>Role:</strong> {user.role}
                  </div>
                  <div>
                    <strong>Provider:</strong> {user.provider}
                  </div>
                  <div>
                    <strong>Verified:</strong> {user.isVerified ? 'Yes' : 'No'}
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
        <Footer />
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-background">
      <Header />
      <div className="container mx-auto px-4 pt-24 pb-8">
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold mb-4">Authentication Demo</h1>
          <p className="text-muted-foreground mb-6">
            Test the authentication system with login and registration
          </p>
          <div className="flex justify-center gap-2 mb-6">
            <Button
              variant={mode === 'login' ? 'default' : 'outline'}
              onClick={() => setMode('login')}
            >
              Sign In
            </Button>
            <Button
              variant={mode === 'register' ? 'default' : 'outline'}
              onClick={() => setMode('register')}
            >
              Create Account
            </Button>
          </div>
        </div>

        {mode === 'login' ? (
          <LoginForm onSwitchToRegister={() => setMode('register')} />
        ) : (
          <RegisterForm onSwitchToLogin={() => setMode('login')} />
        )}
      </div>
      <Footer />
    </div>
  )
}

// Wrapper component with Suspense boundary
export default function AuthPage() {
  return (
    <Suspense
      fallback={
        <div className="min-h-screen flex items-center justify-center">
          <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
        </div>
      }
    >
      <AuthPageContent />
    </Suspense>
  )
}
