import {
	ArrowLeft,
	Check,
	Loader2,
	RotateCcw,
	EyeOff,
	AlertTriangle,
	FileText,
	ExternalLink,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import FlavioIcon from '@/components/ui/flavio-icon';
import { isAppPaused } from '@/api/client';
import { resolvePageRef } from '@/features/interventions/detail/pageRef';
import { useInterventionResponse } from '@/features/interventions/useInterventionResponse';
import UpgradeLock from '@/features/interventions/detail/UpgradeLock';

/**
 * Detail for the `noindexsingle` / `blog_public` intervention (type selection).
 *
 * The site has WordPress's "Discourage search engines from indexing this site"
 * option turned on (Settings → Reading), which sends `noindex` site-wide. Flavio
 * can flip that single toggle, which unblocks every page at once.
 *
 * The intervention is scoped to a single page (page_path / wp_post_id) — the
 * one that triggered the discovery — but the fix is site-wide, so we make that
 * explicit in the copy.
 *
 * Contract metadata: `page_path`, `wp_post_id`, `source:"blog_public"`,
 * `options:[apply, keep_current]`. userResponse: { choice }. Both submit as
 * `acknowledge` (no dismiss path here).
 *
 * Defensive on metadata: every field is read with a fallback.
 */
const NoindexBlogPublic = ({
	intervention = {},
	interventionId,
	onBack,
	onResolved,
}) => {
	const m = intervention.metadata || {};
	const { pageLabel, pageUrl } = resolvePageRef(m);
	// Trial ended: the intervention can't be acted on, so its action buttons are
	// swapped for the single "unlock" upgrade CTA.
	const isPaused = isAppPaused();

	const { pending, resolved, error, run } = useInterventionResponse(
		interventionId,
		{ onResolved }
	);

	if (resolved) {
		return (
			<div className="max-w-2xl mx-auto text-center">
				<FlavioIcon className="w-12 h-12 mx-auto mb-4" />
				<h1 className="heading-h2 mt-0! leading-tight mb-3">
					{resolved === 'primary' ? 'All set' : 'Got it'}
				</h1>
				<div className="max-w-md mx-auto">
					<p className="paragraph-regular text-muted-foreground mb-0!">
						{resolved === 'primary'
							? "Done. Your pages can now show up in search."
							: "No problem. I'll leave your site hidden from search for now."}
					</p>
				</div>
				{onBack && (
					<Button
						onClick={onBack}
						size="lg"
						className="mt-6 bg-foreground text-background! hover:bg-foreground/90"
					>
						<ArrowLeft />
						Back to your list
					</Button>
				)}
			</div>
		);
	}

	return (
		<div className="max-w-2xl mx-auto text-center">
			<span className="inline-flex items-center justify-center w-12 h-12 rounded-full bg-amber-50 text-amber-500 mb-4">
				<EyeOff className="w-6 h-6" />
			</span>
			<h1 className="heading-h1 mt-0! leading-tight mb-3">
				Your site is hidden from search
			</h1>
			<div className="max-w-xl mx-auto mb-8">
				<p className="paragraph-regular text-muted-foreground mb-0!">
					WordPress has the option{' '}
					<span className="font-mono text-foreground">
						Discourage search engines from indexing this site
					</span>{' '}
					turned on, so Google ignores your pages site-wide. I can turn
					it off in one click.
				</p>
			</div>

			{pageLabel &&
				(pageUrl ? (
					<a
						href={pageUrl}
						target="_blank"
						rel="noopener noreferrer"
						className="inline-flex items-center gap-1.5 rounded-full border border-border px-3 py-1 small-medium text-muted-foreground! hover:bg-muted/60 hover:text-foreground! transition-colors mb-8"
					>
						<FileText className="w-3.5 h-3.5" />
						{pageLabel}
						<ExternalLink className="w-3 h-3" />
					</a>
				) : (
					<div className="inline-flex items-center gap-1.5 rounded-full border border-border px-3 py-1 small-medium text-muted-foreground mb-8">
						<FileText className="w-3.5 h-3.5" />
						{pageLabel}
					</div>
				))}

			<div className="rounded-2xl border border-border p-6 text-left">
				<div className="flex items-start gap-3">
					<span className="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-amber-50 text-amber-500 shrink-0">
						<AlertTriangle className="w-4 h-4" />
					</span>
					<div className="min-w-0">
						<p className="small-semibold text-foreground my-0!">
							This affects every page on your site, not just this one.
						</p>
						<p className="small-regular text-muted-foreground my-0! mt-1!">
							The setting lives in WordPress' Settings → Reading, under{' '}
							<span className="font-mono">Search engine visibility</span>.
							I'll flip it for you so search engines can index your
							site again.
						</p>
					</div>
				</div>
			</div>

			<div className="flex items-center justify-center gap-3 mt-8">
				{isPaused ? (
					<UpgradeLock />
				) : (
					<>
						<Button
							onClick={() =>
								run('primary', {
									status: 'acknowledge',
									userResponse: { choice: 'apply' },
								})
							}
							disabled={!!pending || !!resolved}
							size="lg"
							className="bg-foreground text-background! hover:bg-foreground/90"
						>
							{pending === 'primary' ? (
								<Loader2 className="animate-spin" />
							) : (
								<Check />
							)}
							Allow search engines
						</Button>
						<Button
							onClick={() =>
								run('secondary', {
									status: 'acknowledge',
									userResponse: { choice: 'keep_current' },
								})
							}
							disabled={!!pending || !!resolved}
							size="lg"
							variant="outline"
						>
							{pending === 'secondary' ? (
								<Loader2 className="animate-spin" />
							) : (
								<RotateCcw />
							)}
							Keep it hidden
						</Button>
					</>
				)}
			</div>

			{!isPaused && error && (
				<p className="small-regular text-destructive text-center mt-3 mb-0!">
					{error}
				</p>
			)}
			{!isPaused && (
				<p className="small-regular text-muted-foreground text-center mt-4 mb-0!">
					Nothing changes until you choose.
				</p>
			)}
		</div>
	);
};

export default NoindexBlogPublic;
