import { ArrowRight, Search, Sparkles } from 'lucide-react';

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

import { Button } from '@/Components/ui/button';
import { cn } from '@/lib/utils';
import type { PageProps } from '@/types';

/**
 * F-SERP_AUTOFETCH launch — advertises the platform-paid "Competitor SERP
 * analyses" differentiator in-app and surfaces the honest per-user monthly cap.
 *
 * Two states, both driven by the shared `limits` Inertia prop (reused, NOT a new
 * counter):
 *   - Under cap → "Competitor SERP analyses: X of Y left this month".
 *   - At cap → upgrade-aware nudge ("you've used your competitor SERP analyses
 *     this month — upgrade for more"), so the rewrite degrading to "basic" is
 *     never a silent no-op.
 *
 * Renders nothing when:
 *   - `limits` is absent (unauthenticated),
 *   - the cap is Unlimited (`null`, Enterprise tier) — no scarcity to communicate,
 *   - the user has a validated BYOK DataForSEO key (`has_serp_key`) — the per-user
 *     PLATFORM cap does not apply to BYOK fetches, so a "you've used your platform
 *     analyses, upgrade" nudge would be wrong (codex FND-003).
 */
export function SerpQuotaMeter({
  className,
  atCapOnly = false,
}: {
  className?: string;
  /**
   * When true, render ONLY the at-cap nudge and nothing in the under-cap state.
   * Used by DraftShow (codex FND-001): a Basic draft should explain itself with the
   * nudge ONLY when the user is actually quota-blocked — a not-blocked user must not
   * see an "X of Y left" card on every Basic draft. The Settings page leaves this
   * false to show the live meter at all times.
   */
  atCapOnly?: boolean;
}) {
  const { limits, features, has_serp_key } = usePage<PageProps>().props;

  if (!limits) return null;

  // BYOK users run competitor-targeted rewrites on their own key, uncapped by the
  // platform per-user quota — the meter/nudge does not describe their reality.
  if (has_serp_key) return null;

  const cap = limits.serp_user_monthly_queries;
  // null = Unlimited (Enterprise). Nothing to meter or nudge.
  if (cap === null) return null;

  const used = limits.serp_queries_used_this_month ?? 0;
  const remaining = Math.max(0, cap - used);
  const atCap = remaining === 0;
  const proCap = limits.pro_serp_user_monthly_queries;
  const billingEnabled = features.billing;

  // QA F1: only pitch a Pro UPGRADE when Pro actually offers MORE than the user's
  // current cap. A Pro/Team user already at 200 must NOT be told "Upgrade to Pro
  // for 200" — that is factually wrong. For them (cap >= proCap), the only way to
  // get more competitor-targeted rewrites is their own DataForSEO key (BYOK).
  const proOffersMore = billingEnabled && cap < proCap;

  if (atCap) {
    return (
      <div
        role="status"
        aria-live="polite"
        className={cn(
          'rounded-lg border border-primary/30 bg-primary/10 p-4',
          className,
        )}
      >
        <div className="flex items-start gap-3">
          <Sparkles className="size-5 text-primary-strong shrink-0 mt-0.5" aria-hidden="true" />
          <div className="space-y-2">
            <div>
              {/* text-primary-strong (not text-primary) for WCAG AA on the tinted
                  bg-primary/10 surface — see resources/js/CLAUDE.md shade rule. */}
              <p className="font-medium text-primary-strong">
                You&rsquo;ve used your {cap} competitor SERP analyses this month
              </p>
              <p className="text-sm text-muted-foreground mt-1">
                New rewrites this month fall back to <span className="font-medium text-foreground">basic</span>{' '}
                (no competitor-targeted scoring) until your quota resets.{' '}
                {proOffersMore
                  ? `Upgrade to Pro for ${proCap} competitor SERP analyses a month.`
                  : 'Add your own DataForSEO key for unlimited competitor-targeted rewrites.'}
              </p>
            </div>
            {proOffersMore && (
              <Link href={route('pricing')}>
                <Button size="sm" variant="default" className="mt-1">
                  Upgrade for more
                  <ArrowRight className="ml-2 size-4" aria-hidden="true" />
                </Button>
              </Link>
            )}
          </div>
        </div>
      </div>
    );
  }

  // atCapOnly: suppress the under-cap meter entirely (DraftShow contextual nudge).
  if (atCapOnly) return null;

  return (
    <div
      className={cn(
        'rounded-lg border bg-card p-4 flex items-center gap-3',
        className,
      )}
    >
      <Search className="size-5 text-muted-foreground shrink-0" aria-hidden="true" />
      <div>
        <p className="text-sm font-medium text-foreground">
          Competitor SERP analyses: {remaining} of {cap} left this month
        </p>
        <p className="text-xs text-muted-foreground mt-0.5">
          Each competitor-targeted rewrite analyzes the top-ranking pages for your keyword. Resets monthly.
        </p>
      </div>
    </div>
  );
}
