import { Navigate, useLocation } from 'react-router-dom'
import { useAuth } from '../hooks/useAuth'
import { isSupabaseConfigured } from '../lib/supabase'

interface ProtectedRouteProps {
  children: React.ReactNode
  redirectTo?: string
}

/**
 * @ai-hint Wrap pages that require authentication
 * Usage: <ProtectedRoute><Admin /></ProtectedRoute>
 */
export function ProtectedRoute({ children, redirectTo = '/login' }: ProtectedRouteProps) {
  const { isAuthenticated, loading } = useAuth()
  const location = useLocation()

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center px-4">
        <p className="text-muted-foreground text-sm">Checking authentication...</p>
      </div>
    )
  }

  // Without Supabase, sign-in cannot work and redirecting to /login would loop.
  // Show a clear message instead.
  if (!isSupabaseConfigured()) {
    return (
      <div className="min-h-screen flex items-center justify-center px-4">
        <div className="max-w-md text-center">
          <h1 className="text-xl font-semibold text-foreground mb-2">
            Authentication not configured
          </h1>
          <p className="text-muted-foreground">
            This page requires sign-in, but Supabase Authentication has not been set up
            for this project yet.
          </p>
        </div>
      </div>
    )
  }

  if (!isAuthenticated) {
    return <Navigate to={redirectTo} state={{ from: location }} replace />
  }

  return <>{children}</>
}
