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` / `unknown` intervention (type `help`).
 *
 * A page sends a noindex signal but Flavio can't tell where it comes from:
 * could be theme code, a custom plugin, an embed, hard-coded markup, … The user
 * has to track it down. The steps are instructional. The scan re-checks on its
 * next cycle and the heartbeat auto-resolves 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:"unknown"`.
 *
 * Defensive on metadata: every field is read with a fallback.
 */

const STEPS = [
	{
		text: 'Open this page in a private/incognito window and view its HTML source.',
		hint: 'Right-click → View Page Source, then search for "robots".',
	},
	{
		text: 'Look for a meta tag like <meta name="robots" content="noindex"> or an X-Robots-Tag in the response headers.',
		hint: 'That tag is the one telling Google not to index the page.',
	},
	{
		text: 'Check the usual sources: an SEO plugin you forgot was installed, your theme settings, a page builder block, or hard-coded markup in the post.',
	},
	{
		text: 'Remove the noindex from whichever source set it. If you can\'t find it, ask whoever maintains your site.',
		hint: "I'll re-check this page on my next pass and pick up the change automatically.",
	},
];

const NoindexUnknown = ({
	intervention = {},
	interventionId,
	onBack,
	onResolved,
}) => {
	const m = intervention.metadata || {};
	// 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">
				This page is hidden from search
			</h1>
			<div className="max-w-xl mx-auto mb-8">
				<p className="paragraph-regular text-muted-foreground mb-0!">
					I can see the page sends a noindex signal, but I couldn't
					trace where it comes from. It's not WordPress' site-wide
					setting and not one of the SEO plugins I know about, so it
					takes a bit of digging.
				</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 track it down</h2>
				<div className="space-y-5 text-left mt-4">
					{STEPS.map((step, index) => (
						<div key={step.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>
							<div>
								<p className="paragraph-regular text-foreground my-0! pt-0.5">
									{step.text}
								</p>
								{step.hint && (
									<p className="small-regular text-muted-foreground mt-1! mb-0!">
										{step.hint}
									</p>
								)}
							</div>
						</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">
					Until the noindex is removed, this page won't appear in search
					results.
				</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 NoindexUnknown;
