import type { ReactNode } from 'react';

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

import type { PageProps } from '@/types';

interface BillingLinkProps {
  /**
   * Route params forwarded to `route('billing.plans', params)`.
   * Preserves utm_* tracking and plan/source params from each call site.
   */
  params?: Record<string, string>;

  /** Click handler forwarded to the <Link>. Used for analytics tracking. */
  onClick?: () => void;

  className?: string;
  children: ReactNode;

  /**
   * Rendered in place of the billing link when billing is disabled.
   * When omitted the component renders null (invisible) when billing is off.
   */
  fallback?: ReactNode;

  /** data-testid for the rendered <Link>. */
  'data-testid'?: string;
}

/**
 * Feature-gated billing link.
 *
 * Reads `features.billing` from Inertia shared props. When billing is
 * enabled it renders an Inertia <Link> to `route('billing.plans', params)`;
 * when disabled it renders the `fallback` prop (or null).
 *
 * This is the single source of truth for billing.plans links across the app.
 * Every call site that previously called `route('billing.plans')` directly
 * should use this component instead.
 *
 * Usage:
 *   <BillingLink params={{ plan: 'pro', utm_source: 'foo' }} onClick={track}>
 *     Upgrade to Pro
 *   </BillingLink>
 *
 *   // With a fallback when billing is disabled:
 *   <BillingLink fallback={<span>Contact support to upgrade.</span>}>
 *     Upgrade
 *   </BillingLink>
 */
export function BillingLink({
  params,
  onClick,
  className,
  children,
  fallback = null,
  'data-testid': dataTestId,
}: BillingLinkProps) {
  const { features } = usePage<PageProps>().props;

  if (!features?.billing) {
    return <>{fallback}</>;
  }

  return (
    <Link
      href={route('billing.plans', params as Record<string, unknown> | undefined)}
      onClick={onClick}
      className={className}
      data-testid={dataTestId}
    >
      {children}
    </Link>
  );
}
