import {
	HousePlug,
	ExternalLink,
	AlertTriangle,
	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 { useInterventionResponse } from '@/features/interventions/useInterventionResponse';
import UpgradeLock from '@/features/interventions/detail/UpgradeLock';

/**
 * Detail for the `homeerror` / `home_unreachable` intervention (type `help`).
 *
 * Unlike `no500` (which sweeps the whole sitemap for 5xx pages), `homeerror`
 * checks a single URL, the homepage, and fails on *any* status other than 200:
 * 5xx, 4xx, 3xx, 403, etc. So the metadata is just `{ status }` (one integer, no
 * pending_items), and the right fix depends on which code came back. We classify
 * the status into a kind and tailor the diagnosis, steps and admin links to it.
 *
 * The steps are instructional. The scan (or a live re-check) verifies the
 * homepage on its next cycle and the heartbeat auto-resolves once it returns 200
 * again, 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.
 *
 * Defensive on metadata: the base contract only guarantees `variant`, so `status`
 * is read with a fallback and may be absent.
 */

/** Human-readable name for the common HTTP codes a homepage can return. */
const STATUS_TEXT = {
	301: 'Moved Permanently',
	302: 'Found',
	303: 'See Other',
	307: 'Temporary Redirect',
	308: 'Permanent Redirect',
	400: 'Bad Request',
	401: 'Unauthorized',
	403: 'Forbidden',
	404: 'Not Found',
	410: 'Gone',
	429: 'Too Many Requests',
	500: 'Internal Server Error',
	502: 'Bad Gateway',
	503: 'Service Unavailable',
	504: 'Gateway Timeout',
};

/** Bucket the HTTP status into a kind that decides the diagnosis and steps. */
const classify = (status) => {
	if (!status) return 'unknown';
	if (status >= 500) return 'server';
	if (status === 401 || status === 403 || status === 429) return 'forbidden';
	if (status === 404 || status === 410) return 'notfound';
	if (status >= 300 && status < 400) return 'redirect';
	return 'unknown';
};

const CLOSER = {
	text: "Once your homepage loads again, I'll pick up where I left off.",
};

/** Reason + tailored steps (with resolved admin links) for the status kind. */
const getPlan = (status, config) => {
	const adminUrl = config?.adminUrl || '';
	const siteUrl = config?.siteUrl || '';
	const adminLink = (slug, label) =>
		adminUrl ? { label, url: `${adminUrl}${slug}` } : null;
	const homeLink = (label) => (siteUrl ? { label, url: siteUrl } : null);

	switch (classify(status)) {
		case 'server':
			return {
				reason: 'Your server hit an error while building the homepage. This usually follows a recent change or a temporary hosting hiccup.',
				steps: [
					{
						text: 'Undo your most recent change.',
						hint: 'A plugin update, a new plugin, or an edit often triggers this. Deactivating it usually clears it.',
						link: adminLink('plugins.php', 'Review plugins'),
					},
					{
						text: 'Still down? Contact your hosting provider.',
						hint: 'They can read the server log and tell you exactly what failed.',
					},
					CLOSER,
				],
			};
		case 'redirect':
			return {
				reason: 'Your homepage is redirecting instead of loading. A redirect rule, a plugin, or a mismatched site address can cause this, sometimes a loop.',
				steps: [
					{
						text: 'Check your site address settings.',
						hint: 'Make sure WordPress Address and Site Address match how people reach you (http vs https, with or without www).',
						link: adminLink(
							'options-general.php',
							'Open General settings'
						),
					},
					{
						text: 'Review any redirect plugins or rules.',
						hint: 'A redirect pointing the homepage at itself or a missing page creates a loop.',
					},
					CLOSER,
				],
			};
		case 'notfound':
			return {
				reason: "Your homepage can't be found. Often the page set as your front page was deleted, or your permalinks changed.",
				steps: [
					{
						text: 'Check which page is your homepage.',
						hint: 'In Settings → Reading, confirm your front page points to a page that still exists.',
						link: adminLink(
							'options-reading.php',
							'Open Reading settings'
						),
					},
					{
						text: 'Re-save your permalinks.',
						hint: 'In Settings → Permalinks, just hit Save to rebuild your links.',
						link: adminLink(
							'options-permalink.php',
							'Open Permalink settings'
						),
					},
					CLOSER,
				],
			};
		case 'forbidden':
			return {
				reason: 'Your homepage is blocking visitors. This is usually a coming-soon or maintenance mode, password protection, or a security rule.',
				steps: [
					{
						text: 'Turn off any coming-soon or maintenance mode.',
						hint: 'Many themes and plugins have one, and it hides your site from visitors.',
						link: adminLink('plugins.php', 'Review plugins'),
					},
					{
						text: 'Check for password protection or a firewall rule.',
						hint: 'A security plugin or your host may be blocking access.',
					},
					CLOSER,
				],
			};
		default:
			return {
				reason: "Your homepage isn't returning a normal response, so visitors can't see it.",
				steps: [
					{
						text: 'Open your homepage to see what happens.',
						hint: 'The error you see there is a strong clue to what went wrong.',
						link: homeLink('Open my homepage'),
					},
					{
						text: 'Undo your most recent change, or contact your hosting provider.',
						hint: 'A recent plugin or theme change is the usual cause; your host can read the server log.',
					},
					CLOSER,
				],
			};
	}
};

const HomeError = ({
	intervention = {},
	interventionId,
	onBack,
	onResolved,
}) => {
	const config = getWordPressConfig();
	const metadata = intervention.metadata || {};
	const status = Number(metadata.status) || null;
	const siteUrl = config?.siteUrl || '';

	const statusText = status ? STATUS_TEXT[status] : '';
	const { reason, steps } = getPlan(status, config);

	// 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">Got it</h1>
				<div className="max-w-md mx-auto">
					<p className="paragraph-regular text-muted-foreground mb-0!">
						Thanks. I'll re-check your homepage 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">
			<h1 className="heading-h1 mt-0! leading-tight mb-3">
				Your homepage isn't loading
			</h1>
			<div className="max-w-xl mx-auto mb-8">
				<p className="paragraph-regular text-muted-foreground mb-0!">
					Your homepage is the first thing visitors and search engines
					see. Right now it isn't responding normally, so people can't
					land on it. Here's what's happening and how to fix it.
				</p>
			</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-10 h-10 rounded-xl border border-border shrink-0">
						<HousePlug className="w-5 h-5 text-muted-foreground" />
					</span>
					<div className="min-w-0 flex-1">
						<p className="small-medium text-foreground my-0!">
							Your homepage
						</p>
						{siteUrl && (
							<a
								href={siteUrl}
								target="_blank"
								rel="noopener noreferrer"
								className="inline-flex items-center gap-1 min-w-0 mt-0.5 small-regular text-muted-foreground! hover:underline"
							>
								<span className="truncate">{siteUrl}</span>
								<ExternalLink className="w-3 h-3 shrink-0" />
							</a>
						)}
					</div>
					<div className="shrink-0 text-right">
						<span className="inline-block rounded-md border border-red-200 bg-red-50 px-2 py-0.5 small-medium text-red-700">
							{status ? `HTTP ${status}` : 'No response'}
						</span>
						{statusText && (
							<p className="small-regular text-muted-foreground mt-1 mb-0!">
								{statusText}
							</p>
						)}
					</div>
				</div>
				<p className="small-regular text-muted-foreground mt-3 mb-0!">
					{reason}
				</p>
			</div>

			<div className="rounded-2xl border border-border p-8 mt-4">
				<h2 className="heading-h4 mt-0! mb-6">How to fix this</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 className="min-w-0">
								<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>
								)}
								{step.link && (
									<a
										href={step.link.url}
										target="_blank"
										rel="noopener noreferrer"
										className="inline-flex items-center gap-1 mt-1.5 small-medium text-foreground! hover:underline"
									>
										{step.link.label}
										<ExternalLink className="w-3 h-3 shrink-0" />
									</a>
								)}
							</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 your homepage loads, visitors bounce and search engines
					can't crawl the rest of your site.
				</span>
			</div>

			{isPaused ? (
				<div className="mt-8">
					<UpgradeLock />
				</div>
			) : (
				/* Already-done escape hatch: acknowledge so it clears now, without
				    waiting for the scan to re-check the homepage. */
				<div className="mt-8">
					<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 HomeError;
