import { Link } from 'react-router-dom';
import { Lock, Sparkles } from 'lucide-react';
import {
  useFeatureGate,
  type Feature,
  TIER_LABELS,
  FEATURE_MIN_TIER,
} from '../../hooks/useFeatureGate';
import { LoadingSpinner } from './LoadingSpinner';

const FEATURE_LABELS: Record<Feature, string> = {
  dashboard: 'Dashboard',
  forecasting: 'Forecasting',
  cascading_goals: 'Cascading Goals',
  strategic_intelligence: 'Strategic Intelligence',
  scale_optimization: 'Scale Optimization',
  multi_market: 'Multi-Market Command',
  enterprise: 'Enterprise Features',
};

interface FeatureGateProps {
  feature: Feature;
  children: React.ReactNode;
  /** Optional custom fallback instead of the default upgrade prompt */
  fallback?: React.ReactNode;
}

/**
 * FeatureGate — renders children only if the current user's subscription tier
 * includes `feature`. Otherwise shows an upgrade prompt linking to billing.
 *
 * <FeatureGate feature="multi_market"><MultiMarketPage /></FeatureGate>
 */
export function FeatureGate({ feature, children, fallback }: FeatureGateProps) {
  const { hasFeature, tierLabel, isLoading } = useFeatureGate();

  if (isLoading) {
    return (
      <div className="flex min-h-[50vh] items-center justify-center">
        <LoadingSpinner size="lg" />
      </div>
    );
  }

  if (hasFeature(feature)) {
    return <>{children}</>;
  }

  if (fallback) return <>{fallback}</>;

  const requiredLabel = TIER_LABELS[FEATURE_MIN_TIER[feature]];

  return (
    <div className="flex min-h-[60vh] items-center justify-center p-6">
      <div className="w-full max-w-lg rounded-2xl border border-slate-200 bg-white p-10 text-center shadow-sm">
        <div className="mx-auto mb-5 flex h-14 w-14 items-center justify-center rounded-full bg-indigo-50">
          <Lock className="h-7 w-7 text-indigo-600" />
        </div>
        <h2 className="text-xl font-bold text-slate-900">
          {FEATURE_LABELS[feature]} requires the {requiredLabel} plan
        </h2>
        <p className="mt-3 text-sm text-slate-600">
          You're currently on the <span className="font-semibold">{tierLabel}</span> plan.
          Upgrade to {requiredLabel} to unlock {FEATURE_LABELS[feature]} and more.
        </p>
        <div className="mt-6 flex items-center justify-center gap-3">
          <Link
            to="/app/billing"
            className="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-5 py-2.5 text-sm font-semibold text-white transition hover:bg-indigo-700"
          >
            <Sparkles className="h-4 w-4" />
            View plans & upgrade
          </Link>
          <Link
            to="/app"
            className="rounded-lg border border-slate-300 px-5 py-2.5 text-sm font-medium text-slate-700 transition hover:bg-slate-50"
          >
            Back to dashboard
          </Link>
        </div>
      </div>
    </div>
  );
}