import { ArrowRight, History, Play, TrendingDown } from 'lucide-react';

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

import { RUN_NOUNS } from '@/lib/actionLexicon';
import type { InFlightBatch } from '@/types/dashboard';

/**
 * RecoveryRunHero — R6UX-003
 *
 * Daily-return entry point for the Recovery Run workflow.
 * Seeds the highest-click-loss cohort and routes directly into
 * the Content Inventory filtered by click_loss desc.
 *
 * R16-PD-02: When an active batch exists (`inFlightBatch` is non-null),
 * the primary CTA switches to "Resume run (N of M reviewed)" linking to
 * review.index instead of starting a new run. The "View past runs" history
 * link is demoted to secondary and remains visible in both states.
 *
 * Visibility rule (enforced by parent Dashboard.tsx):
 *   - User is activated (has_analysis === true)
 *   - `latestAnalysisAt` is non-null (recent analysis exists)
 *   - `decliningPageCount` > 0
 *
 * The card is shown ABOVE DailyActionHero and replaces it in the
 * hero priority stack for the daily-return activated persona.
 *
 * Design: same DailyActionCard structure as DailyActionHero
 * (full-card stretched Link + content layer z-10) for visual
 * consistency and accessibility compliance (UX-215).
 */

interface RecoveryRunHeroProps {
  /** Site public_id (passed directly to route()). */
  siteId: string;
  /** Count of pages with negative click delta from last analysis. */
  decliningPageCount: number;
  /**
   * R16-PD-02: Active BatchJob summary, or null when no batch is in flight.
   * When present, renders "Resume run" as the primary CTA.
   */
  inFlightBatch?: InFlightBatch | null;
}

export function RecoveryRunHero({ siteId, decliningPageCount, inFlightBatch = null }: RecoveryRunHeroProps) {
  // Pre-seed the Content Inventory to the highest-click-loss cohort.
  // sort_by=click_loss + sort_direction=desc mirrors the Recovery Run persona intent.
  const startHref = `${route('content-inventory.index', siteId)}?sort_by=click_loss&sort_direction=desc`;
  // R16-PD-02: Resume lands on review.index so the user picks up where they left off.
  const resumeHref = route('review.index', siteId);
  // R8UX-011: link to batch-ai.index (manual run history) from the hero so users
  // can reach their past runs without hunting through the sidebar.
  const historyHref = route('batch-ai.index', siteId);

  // R16-PD-02: determine the primary link and copy based on batch state.
  const isResuming = inFlightBatch !== null;
  const primaryHref = isResuming ? resumeHref : startHref;

  // "N of M reviewed" copy — only when count is meaningful.
  const batchPendingCount = inFlightBatch?.pending_review_count ?? 0;
  const resumeCopy = batchPendingCount > 0
    ? `Resume run — ${batchPendingCount} draft${batchPendingCount !== 1 ? 's' : ''} awaiting review`
    : 'Resume run';

  return (
    <div className="relative mb-6 flex items-center gap-4 rounded-2xl border border-destructive/30 bg-destructive/5 px-5 py-4 hover:bg-destructive/10 transition-colors">
      {/* Stretched link — full-card hit target (UX-215). sr-only span provides accessible name. */}
      <Link
        href={primaryHref}
        className="absolute inset-0 rounded-2xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"
      >
        <span className="sr-only">{isResuming ? resumeCopy : 'Start Recovery Run'}</span>
      </Link>

      {/* Icon layer */}
      <span className="relative z-10 shrink-0" aria-hidden="true">
        {isResuming
          ? <Play className="size-5 text-destructive-strong" />
          : <TrendingDown className="size-5 text-destructive-strong" />
        }
      </span>

      {/* Content layer */}
      <div className="relative z-10 flex-1 min-w-0">
        <p className="text-[10px] font-semibold uppercase tracking-[0.18em] text-destructive-strong/70 mb-0.5">
          {RUN_NOUNS.manualRun}
        </p>
        {isResuming ? (
          <span className="text-sm font-semibold text-foreground inline-flex items-center gap-1">
            {resumeCopy}
            <ArrowRight className="size-3.5" aria-hidden="true" />
          </span>
        ) : (
          <span className="text-sm font-semibold text-foreground inline-flex items-center gap-1">
            {decliningPageCount} page{decliningPageCount !== 1 ? 's' : ''} losing clicks — start recovery
            <ArrowRight className="size-3.5" aria-hidden="true" />
          </span>
        )}
      </div>

      {/* R8UX-011: "View past runs" link to batch-ai.index — sits above the stretched
          overlay (z-10) so it captures its own click without the card intercepting.
          R16-PD-02: demoted to secondary when isResuming; also show "Start new" link
          so the user can bypass resume if they want a fresh run. */}
      {isResuming && (
        <Link
          href={startHref}
          className="relative z-10 shrink-0 flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
          aria-label="Start a new Recovery Run"
        >
          <span>Start new</span>
        </Link>
      )}
      <Link
        href={historyHref}
        className="relative z-10 shrink-0 flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
        aria-label={`${RUN_NOUNS.heroHistoryLink} — Recovery Runs history`}
      >
        <History className="size-3.5" aria-hidden="true" />
        <span>{RUN_NOUNS.heroHistoryLink}</span>
      </Link>
    </div>
  );
}
