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

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

import { BillingLink } from '@/Components/billing/BillingLink';
import { trackEvent } from '@/lib/analytics';
import { BYOK_LINK_CLICKED, UPGRADE_PROMPT_CLICKED } from '@/lib/event-catalog';
import type { PageProps } from '@/types';

/**
 * FirstRewriteBridge — dashboard FSE → deep-FSE next-action band.
 *
 * Renders on the day-2-return dashboard for the ACTIVATED-but-NOT-DEEP cohort
 * (analyzed ≥1 site, no AI rewrite draft generated yet). It is the in-app
 * sibling of the day-7 "generate your first rewrite" lifecycle email: one
 * clear headline + ONE primary CTA toward generating the first AI rewrite.
 *
 * Gating is the caller's responsibility (Dashboard.tsx renders this only when
 * `is_activated && !has_generated_draft`). The band itself decides ONLY which
 * CTA to show, branching on AI readiness exactly like AiDraftNudgeCard:
 *   - bundled credits remaining → "generate from your top recommendation" CTA
 *     into the recommendations surface (no key, no spend).
 *   - exhausted, trial user, billing on → upgrade-to-Pro.
 *   - exhausted, free user, billing on → upgrade-to-Pro.
 *   - otherwise (Pro out of credits, or billing flag off) → BYOK settings link.
 *
 * Persona note (v1 = solo bulk-rewriter): copy favours BULK rewrite framing
 * where it fits. The differentiator vocabulary (lift / before-after /
 * "Prove what worked") is reserved for results claims — this band is a
 * pre-result next-action, so it names the concrete action instead.
 *
 * No async state of its own: it reads already-shared Inertia props
 * (`ai_status`, `plan`, `trial`, `features`). There is therefore no loading
 * or error state to render — the parent dashboard owns those. Navigation is
 * an Inertia <Link> (fire-and-forget; never awaited — gotcha #11).
 */
interface FirstRewriteBridgeProps {
  siteId: string;
}

export default function FirstRewriteBridge({ siteId }: FirstRewriteBridgeProps) {
  const { ai_status, plan, trial, features } = usePage<PageProps>().props;

  // `bundled_remaining` is null when ai_status isn't shared (bundled_ai feature
  // off, or BYOK-only deployment). Treat null as "no bundled credits" so the
  // band falls through to the BYOK / upgrade path rather than promising credits
  // that don't exist.
  const bundledRemaining = ai_status?.bundled_remaining ?? null;
  const hasCredits = bundledRemaining !== null && bundledRemaining > 0;

  const isTrialUser = trial?.active === true;
  const isFreePlan = !plan && !isTrialUser;
  const isPro = !!plan && !isTrialUser;
  const planTier: 'free' | 'trial' | 'pro' = isPro ? 'pro' : isTrialUser ? 'trial' : 'free';

  return (
    <section
      aria-labelledby="first-rewrite-bridge-heading"
      className="mb-10 rounded-2xl border border-primary/30 bg-primary/5 p-5 sm:p-6"
    >
      <div className="flex items-start gap-3">
        <Sparkles className="mt-0.5 size-5 shrink-0 text-primary" aria-hidden="true" />
        <div className="min-w-0 flex-1">
          <p className="text-[10px] font-semibold uppercase tracking-[0.18em] text-primary">
            Next step
          </p>
          <h2
            id="first-rewrite-bridge-heading"
            className="mt-1 text-lg font-semibold text-foreground"
          >
            Turn your recommendations into publish-ready rewrites
          </h2>

          {hasCredits ? (
            <>
              <p className="mt-1.5 text-sm text-muted-foreground">
                You analyzed your site — now let AI rewrite the pages that need it. You have{' '}
                <span className="font-medium text-foreground">
                  {bundledRemaining} bundled AI draft{bundledRemaining !== 1 ? 's' : ''}
                </span>{' '}
                this month, no API key needed. Generate in bulk from your top recommendations.
              </p>
              <Link
                href={route('opportunity-map.index', siteId)}
                className="mt-4 inline-flex items-center gap-1.5 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
              >
                Generate your first AI rewrite from your Action Queue
                <ArrowRight className="size-4" aria-hidden="true" />
              </Link>
            </>
          ) : isTrialUser && features?.billing ? (
            <>
              <p className="mt-1.5 mb-4 text-sm text-muted-foreground">
                You're out of bundled drafts this month. Your Pro trial includes 30 drafts/month —
                upgrade to keep rewriting in bulk.
              </p>
              <BillingLink
                params={{ plan: 'pro', source: 'dashboard_first_rewrite_bridge' }}
                onClick={() =>
                  trackEvent(UPGRADE_PROMPT_CLICKED, {
                    surface: 'dashboard',
                    source: 'first_rewrite_bridge_trial',
                    site_id: String(siteId),
                  })
                }
                className="inline-flex items-center gap-1.5 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
              >
                Upgrade to Pro
                <ArrowRight className="size-4" aria-hidden="true" />
              </BillingLink>
            </>
          ) : isFreePlan && features?.billing ? (
            <>
              <p className="mt-1.5 mb-4 text-sm text-muted-foreground">
                You've used your bundled drafts this month. Upgrade to Pro for 30 AI rewrites/month
                and bulk generation.
              </p>
              <BillingLink
                params={{ plan: 'pro', source: 'dashboard_first_rewrite_bridge' }}
                onClick={() =>
                  trackEvent(UPGRADE_PROMPT_CLICKED, {
                    surface: 'dashboard',
                    source: 'first_rewrite_bridge_free',
                    site_id: String(siteId),
                  })
                }
                className="inline-flex items-center gap-1.5 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
              >
                Upgrade to Pro — 14-Day Free Trial
                <ArrowRight className="size-4" aria-hidden="true" />
              </BillingLink>
            </>
          ) : (
            <>
              {/* BYOK-only fallback: Pro users out of bundled credits, or
                  deployments with the billing flag off. Connect a key to keep
                  rewriting at cost price. */}
              <p className="mt-1.5 mb-4 text-sm text-muted-foreground">
                {bundledRemaining === 0
                  ? "You've used all bundled drafts this month. Add your OpenAI key to keep rewriting in bulk at cost price."
                  : 'Connect your own OpenAI key to generate unlimited AI rewrites at cost price.'}
              </p>
              <Link
                href={route('settings.ai')}
                onClick={() =>
                  trackEvent(BYOK_LINK_CLICKED, {
                    site_id: String(siteId),
                    plan_tier: planTier,
                    source: 'byok_only_fallback',
                  })
                }
                className="inline-flex items-center gap-1.5 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
              >
                Set up your OpenAI key to start rewriting
                <ArrowRight className="size-4" aria-hidden="true" />
              </Link>
            </>
          )}
        </div>
      </div>
    </section>
  );
}
