import {
	ArrowLeft,
	ArrowRight,
	Check,
	Loader2,
	Link2,
	ShieldCheck,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import FlavioIcon from '@/components/ui/flavio-icon';
import { getWordPressConfig, isAppPaused } from '@/api/client';
import { useInterventionResponse } from '@/features/interventions/useInterventionResponse';
import UpgradeLock from '@/features/interventions/detail/UpgradeLock';

/**
 * Detail for the `friendlyurl` / `confirm` intervention (type selection).
 *
 * Flavio wants to switch the site's permalink structure to an SEO-friendly form
 * (e.g. plain `?p=123` → `/%postname%/`). Changing indexed URLs is flagged as a
 * non-reversible change, so the handler asks before applying.
 *
 * Contract metadata: `previous_value`, `target_value` (permalink *structures*,
 * not full URLs). options:[apply, keep_current] → { choice:"apply"|"keep_current" }.
 * Both are real decisions the handler records, so both submit as `acknowledge`
 * (neither is a dismiss; no confirmation dialog).
 *
 * The raw structure (`/%postname%/`) means nothing to a non-technical owner, so
 * we render a friendly example URL and keep the raw value muted underneath.
 */

// Sample replacements so a permalink structure reads as a real-looking URL.
const TAG_SAMPLE = {
	'%postname%': 'your-page-name',
	'%pagename%': 'your-page-name',
	'%post_id%': '123',
	'%category%': 'news',
	'%author%': 'author',
	'%year%': '2025',
	'%monthnum%': '05',
	'%day%': '25',
	'%hour%': '09',
	'%minute%': '00',
	'%second%': '00',
};

/** Turn a permalink structure into an example URL under `base`. */
const exampleUrl = (structure, base) => {
	const root = (base || 'https://your-site.com').replace(/\/$/, '');
	if (!structure) return `${root}/?p=123`; // plain permalinks
	let path = structure;
	for (const [tag, sample] of Object.entries(TAG_SAMPLE)) {
		path = path.split(tag).join(sample);
	}
	if (!path.startsWith('/')) path = `/${path}`;
	return `${root}${path}`;
};

const UrlSample = ({ label, structure, url, highlight }) => (
	<div>
		<p
			className={`small-semibold my-0! mb-2! ${
				highlight ? 'text-magenta-600' : 'text-foreground'
			}`}
		>
			{label}
		</p>
		<div
			className={`rounded-lg px-3 py-2 break-words ${
				highlight
					? 'border border-magenta-200 bg-magenta-50'
					: 'bg-muted/50'
			}`}
		>
			<span className="font-mono text-sm text-foreground break-all">
				{url}
			</span>
			<span className="block small-regular text-muted-foreground/70 mt-1">
				Format: {structure || 'plain (?p=123)'}
			</span>
		</div>
	</div>
);

const FriendlyUrl = ({
	intervention = {},
	interventionId,
	onBack,
	onResolved,
}) => {
	const m = intervention.metadata || {};
	const base = getWordPressConfig()?.siteUrl || '';
	const previous = m.previous_value ?? '';
	const target = m.target_value ?? '/%postname%/';
	// 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'
							? "Great. I'll switch your site to friendly URLs shortly."
							: "No problem. I'll keep your current URLs."}
					</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">
			<h1 className="heading-h1 mt-0! leading-tight mb-3">
				Switch to cleaner, search-friendly URLs
			</h1>
			<div className="max-w-xl mx-auto mb-8">
				<p className="paragraph-regular text-muted-foreground mb-0!">
					Your pages use addresses that are hard to read and weaker for
					search. I can switch them to clean, keyword-friendly URLs across
					your whole site.
				</p>
			</div>

			<div className="rounded-2xl border border-border p-6 text-left space-y-4">
				<UrlSample
					label="Your URLs now"
					structure={previous}
					url={exampleUrl(previous, base)}
				/>
				<div className="flex items-center justify-center text-muted-foreground">
					<ArrowRight className="w-4 h-4 rotate-90" />
				</div>
				<UrlSample
					label="After"
					structure={target}
					url={exampleUrl(target, base)}
					highlight
				/>
			</div>

			<div className="max-w-xl mx-auto mt-4 flex items-start gap-2 rounded-xl border border-border bg-muted/30 p-3 text-left small-regular text-muted-foreground">
				<ShieldCheck className="w-4 h-4 shrink-0 mt-0.5 text-emerald-600" />
				<span>
					WordPress automatically redirects your old links, so visitors and
					search engines won't hit dead ends.
				</span>
			</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 />
							)}
							Use friendly URLs
						</Button>
						<Button
							onClick={() =>
								run('secondary', {
									status: 'acknowledge',
									userResponse: { choice: 'keep_current' },
								})
							}
							disabled={!!pending || !!resolved}
							size="lg"
							variant="outline"
						>
							{pending === 'secondary' ? (
								<Loader2 className="animate-spin" />
							) : (
								<Link2 />
							)}
							Keep current URLs
						</Button>
					</>
				)}
			</div>

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

export default FriendlyUrl;
