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

/**
 * Detail for the `friendlyurl` / `htaccess_help` intervention (type `help`).
 *
 * Flavio switched the site to friendly URLs, but on Apache the rewrite rules
 * live in `.htaccess`, and that file isn't writable by the PHP process. The new
 * structure is saved in the database, yet the URLs may 404 until the rules are
 * written manually (see `update_permalink_structure`, action-endpoint.md:289).
 *
 * The fix lives on the user's/host's side, so the steps are instructional. The
 * scan re-checks the URLs on its next cycle and the heartbeat auto-resolves once
 * they respond, 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 from their list right away.
 *
 * Defensive on metadata: `reason` is optional context shown when present.
 */

/** What the user can do to make the new friendly URLs work. */
const STEPS = [
	{
		text: "Simplest fix: ask your hosting provider to make your site's .htaccess file writable.",
		hint: "Then I'll finish the setup automatically on my next pass.",
	},
	{
		text: 'Prefer to do it yourself? Open Settings → Permalinks in your WordPress dashboard.',
		hint: "Scroll to the bottom: WordPress shows the rewrite rules it couldn't save.",
	},
	{
		text: 'Copy those rules into your .htaccess file and save.',
		hint: 'Once saved, your friendly URLs work everywhere and I re-check automatically.',
	},
];

const FriendlyUrlHtaccess = ({
	intervention = {},
	interventionId,
	onBack,
	onResolved,
}) => {
	const reason = intervention.metadata?.reason || '';
	// 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 URLs 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">
				One quick step to finish your new URLs
			</h1>
			<div className="max-w-xl mx-auto mb-8">
				<p className="paragraph-regular text-muted-foreground mb-0!">
					I switched your site to cleaner URLs, but your server's
					configuration file (.htaccess) isn't writable, so I couldn't
					save the rules that make them work. Some links may show "Not
					Found" until that's done.
				</p>
			</div>

			{reason && (
				<div className="max-w-xl mx-auto mb-8 flex items-start gap-3 rounded-xl border border-amber-300 bg-amber-50 p-4 text-left">
					<AlertTriangle className="w-5 h-5 shrink-0 text-amber-500 mt-0.5" />
					<div>
						<p className="small-semibold text-amber-800 my-0!">
							What's blocking this
						</p>
						<span className="inline-block mt-1.5 rounded-md border border-amber-200 bg-amber-100/70 px-2 py-0.5 font-mono text-[0.8125rem] text-amber-900">
							{reason}
						</span>
					</div>
				</div>
			)}

			<div className="rounded-2xl border border-border p-8">
				<h2 className="heading-h4 mt-0! mb-6">How we finish 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>
								<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 this is done, your new URLs may return 404 and search
					engines can't index them. Your old URLs keep working in the
					meantime.
				</span>
			</div>

			{/* Already-done escape hatch: acknowledge so it clears now, without
			    waiting for the scan to re-check the URLs. While paused, the
			    acknowledge action is swapped for the single "unlock" upgrade CTA. */}
			<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 FriendlyUrlHtaccess;
