import { ArrowRight, Lock } from 'lucide-react';

import { useEffect } from 'react';

import { Link, usePage } from '@inertiajs/react';

import { Button } from '@/Components/ui/button';
import { trackEvent } from '@/lib/analytics';
import { FEATURE_GATE_TEASER_SHOWN, FEATURE_GATE_UPGRADE_CLICKED } from '@/lib/event-catalog';
import type { PageProps } from '@/types';

interface FeatureGateTeaserProps {
  /**
   * Short feature name shown as the panel title (e.g. "Traffic Anomaly Alerts").
   */
  featureName: string;

  /**
   * One-sentence description of what the feature does and why it's valuable.
   */
  description: string;

  /**
   * CTA button label. Defaults to "Unlock with Pro".
   */
  ctaLabel?: string;
}

/**
 * Shows a locked-feature callout for free-tier users on pages that contain Pro-only features.
 * Tracks FEATURE_GATE_TEASER_SHOWN on mount and FEATURE_GATE_UPGRADE_CLICKED on CTA click.
 * Returns null when billing is disabled (non-SaaS deployments).
 */
export function FeatureGateTeaser({
  featureName,
  description,
  ctaLabel = 'Unlock with Pro',
}: FeatureGateTeaserProps) {
  const page = usePage<PageProps>();
  const billingEnabled = page.props.features?.billing ?? false;

  useEffect(() => {
    if (!billingEnabled) return;
    trackEvent(FEATURE_GATE_TEASER_SHOWN, {
      feature_name: featureName,
      surface: typeof window !== 'undefined' ? window.location.pathname : '',
    });
    // intentional: fire once on mount; featureName is stable per instance
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (!billingEnabled) return null;

  const plansUrl = `${route('billing.plans')}?highlight=pro`;

  return (
    <div
      role="region"
      aria-label={`${featureName} — Pro feature`}
      className="rounded-lg border border-primary/20 bg-primary/5 p-6 text-center space-y-4"
    >
      <div className="flex justify-center">
        <div className="rounded-full bg-primary/10 p-3">
          <Lock className="h-5 w-5 text-primary" aria-hidden="true" />
        </div>
      </div>

      <div className="space-y-1">
        <p className="font-semibold text-foreground">
          {featureName}{' '}
          <span className="text-xs font-medium uppercase tracking-wide text-primary border border-primary/30 rounded px-1.5 py-0.5 ml-1">
            Pro
          </span>
        </p>
        <p className="text-sm text-muted-foreground">{description}</p>
      </div>

      <Link
        href={plansUrl}
        onClick={() =>
          trackEvent(FEATURE_GATE_UPGRADE_CLICKED, {
            feature_name: featureName,
            surface: typeof window !== 'undefined' ? window.location.pathname : '',
          })
        }
      >
        <Button size="sm" className="mt-1">
          {ctaLabel}
          <ArrowRight className="h-4 w-4 ml-2" aria-hidden="true" />
        </Button>
      </Link>
    </div>
  );
}
