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

/**
 * Detail for the `noindexsingle` / `seo_plugin` intervention (type `help`).
 *
 * An SEO plugin (Yoast, Rank Math, AIOSEO, SEOPress) has the noindex flag set
 * on this page. Flavio can't touch those plugins' settings, so the steps are
 * instructional. The scan re-checks the URL on its next cycle and the heartbeat
 * auto-resolves the intervention once the noindex is gone, but that can lag, so
 * we also give the user an explicit "I've already done this" action that
 * acknowledges the intervention (`status: 'acknowledge'`) and clears it now.
 *
 * Contract metadata: `page_path`, `wp_post_id`, `source:"seo_plugin"`,
 * `seo_plugin:"yoast"|"rankmath"|"aioseo"|"seopress"|null`. userResponse: none.
 *
 * Defensive on metadata: an unknown or missing `seo_plugin` falls back to a
 * generic plugin-agnostic copy.
 */

/** Display name + per-plugin steps to clear the noindex on a single post. */
const PLUGIN_INFO = {
	yoast: {
		name: 'Yoast SEO',
		steps: [
			'Open this page in the WordPress editor.',
			"Find the Yoast SEO box and open the Advanced tab.",
			'Set "Allow search engines to show this Post in search results?" to Yes.',
			'Save the page.',
		],
	},
	rankmath: {
		name: 'Rank Math',
		steps: [
			'Open this page in the WordPress editor.',
			"Open the Rank Math sidebar and go to Advanced.",
			"Turn off the Noindex flag (or set the Robots Meta to Index).",
			'Save the page.',
		],
	},
	aioseo: {
		name: 'All in One SEO',
		steps: [
			'Open this page in the WordPress editor.',
			"Find the AIOSEO box and go to Advanced → Robots Meta.",
			'Uncheck "No Index" (or switch it back to Default).',
			'Save the page.',
		],
	},
	seopress: {
		name: 'SEOPress',
		steps: [
			'Open this page in the WordPress editor.',
			"Find the SEOPress box and open the Advanced tab.",
			'Uncheck "Do not display this page in search engine results (noindex)".',
			'Save the page.',
		],
	},
};

const GENERIC_STEPS = [
	'Open this page in the WordPress editor.',
	"Find your SEO plugin's settings on the page (Yoast, Rank Math, AIOSEO, SEOPress are the usual ones).",
	'Look for an option labelled noindex, Robots Meta or "Allow search engines" and switch it back to index.',
	'Save the page.',
];

const NoindexSeoPlugin = ({
	intervention = {},
	interventionId,
	onBack,
	onResolved,
}) => {
	const m = intervention.metadata || {};
	const pluginKey = m.seo_plugin || '';
	const plugin = PLUGIN_INFO[pluginKey] || null;
	const pluginLabel = plugin?.name || 'your SEO plugin';
	const steps = plugin?.steps || GENERIC_STEPS;

	// 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 { pageLabel, pageUrl } = resolvePageRef(m);
	const siteUrl = getWordPressConfig()?.siteUrl || '';
	const editorUrl = m.wp_post_id
		? `${siteUrl.replace(/\/$/, '')}/wp-admin/post.php?post=${m.wp_post_id}&action=edit`
		: '';

	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">Got it</h1>
				<div className="max-w-md mx-auto">
					<p className="paragraph-regular text-muted-foreground mb-0!">
						Thanks. I'll re-check the page and pick things up from
						there.
					</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">
				{pluginLabel} is hiding this page from search
			</h1>
			<div className="max-w-xl mx-auto mb-8">
				<p className="paragraph-regular text-muted-foreground mb-0!">
					I found a noindex flag set by {pluginLabel} on this page, which
					means Google won't index it. SEO plugin settings live outside
					what I can edit, so you'll need to flip the switch yourself.
					It's quick.
				</p>
			</div>

			<div className="inline-flex items-center gap-3 mb-8 flex-wrap justify-center">
				{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"
						>
							<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">
							<FileText className="w-3.5 h-3.5" />
							{pageLabel}
						</div>
					))}
				{editorUrl && (
					<a
						href={editorUrl}
						target="_blank"
						rel="noopener noreferrer"
						className="inline-flex items-center gap-1.5 rounded-full bg-foreground text-background! px-3 py-1 small-medium hover:bg-foreground/90 transition-colors"
					>
						<Pencil className="w-3.5 h-3.5" />
						Open in editor
						<ExternalLink className="w-3 h-3" />
					</a>
				)}
			</div>

			<div className="rounded-2xl border border-border p-8">
				<h2 className="heading-h4 mt-0! mb-6">How to fix this</h2>
				<div className="space-y-5 text-left mt-4">
					{steps.map((text, index) => (
						<div key={text} className="flex items-start gap-4">
							<span className="flex items-center justify-center w-8 h-8 rounded-full border border-border text-muted-foreground small-semibold shrink-0">
								{index + 1}
							</span>
							<p className="paragraph-regular text-foreground my-0! pt-0.5">
								{text}
							</p>
						</div>
					))}
				</div>
			</div>

			<div className="max-w-xl mx-auto mt-6 flex items-start justify-center gap-2 small-regular text-muted-foreground">
				<AlertTriangle className="w-4 h-4 shrink-0 mt-0.5" />
				<span className="text-left">
					Once you save, I'll re-check the page on my next pass and pick
					up the change automatically.
				</span>
			</div>

			{/* Already-done escape hatch: acknowledge so it clears now, without
			    waiting for the scan to re-check the page. Replaced by the single
			    "unlock" upgrade CTA while paused. */}
			<div className="mt-8">
				{isPaused ? (
					<UpgradeLock />
				) : (
					<>
						<p className="small-regular text-muted-foreground my-0!">
							Already sorted this out? Let me know and I'll take it
							from here.
						</p>
						<Button
							onClick={() =>
								run('primary', {
									status: 'acknowledge',
									userResponse: { choice: 'already_done' },
								})
							}
							disabled={!!pending || !!resolved}
							variant="outline"
							size="lg"
							className="mt-4"
						>
							{pending === 'primary' ? (
								<Loader2 className="animate-spin" />
							) : (
								<Check />
							)}
							I've already done this
						</Button>

						{error && (
							<p className="small-regular text-destructive mt-3 mb-0!">
								{error}
							</p>
						)}
					</>
				)}
			</div>
		</div>
	);
};

export default NoindexSeoPlugin;
