/**
 * FeatureRoute - Route protection for disabled features
 *
 * Wraps routes to check if the feature is enabled.
 * If disabled, redirects to home page or shows a disabled message.
 */

import { Navigate, useLocation } from 'react-router-dom'
import { useEnabledFeatures } from '../hooks/useEnabledFeatures'
import { AlertTriangle } from 'lucide-react'

interface FeatureRouteProps {
  path: string
  children: React.ReactNode
  redirectTo?: string
  showDisabledMessage?: boolean
}

export function FeatureRoute({
  path,
  children,
  redirectTo = '/',
  showDisabledMessage = false,
}: FeatureRouteProps) {
  const { isFeatureEnabled, isLoading } = useEnabledFeatures()
  const location = useLocation()

  // While loading, render children to prevent flash
  if (isLoading) {
    return <>{children}</>
  }

  // Check if feature is enabled
  if (!isFeatureEnabled(path)) {
    if (showDisabledMessage) {
      return (
        <div className="min-h-[50vh] flex items-center justify-center">
          <div className="text-center max-w-md">
            <AlertTriangle className="w-16 h-16 text-amber-500 mx-auto mb-4" />
            <h1 className="text-2xl font-bold text-slate-900 dark:text-slate-100 mb-2">
              Feature Disabled
            </h1>
            <p className="text-slate-600 dark:text-slate-400 mb-4">
              This feature has been disabled by an administrator.
              Please contact your administrator if you need access.
            </p>
            <a
              href="/"
              className="inline-block px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700"
            >
              Go to Dashboard
            </a>
          </div>
        </div>
      )
    }

    // Redirect to home or specified path
    return <Navigate to={redirectTo} state={{ from: location }} replace />
  }

  return <>{children}</>
}

export default FeatureRoute
