import { createElement, useEffect, useState } from 'react';
import { ArrowLeft } from 'lucide-react';
import { get, getWordPressConfig } from '@/api/client';
import { logError } from '@/errors/logger';
import { resolveDetailComponent } from '@/features/interventions/detail/registry';
import InterventionBadges from '@/features/interventions/InterventionBadges';

/**
 * InterventionDetailPage
 *
 * Per-intervention detail, reachable via a shareable URL
 * (?view=interventions&id=<id>). Fetches the single intervention from
 * GET /interventions/:id and dispatches to a per-handler detail component
 * (byKey[key][variant]); unmapped handlers fall back to a minimal stub.
 */
const InterventionDetailPage = ({ interventionId, onBack, transition }) => {
	const [intervention, setIntervention] = useState(null);
	const [isLoading, setIsLoading] = useState(true);
	const [error, setError] = useState(null);
	const [isResolved, setIsResolved] = useState(false);
	// Set when we land on an intervention that's no longer pending; the effect
	// below then slips back to the list (we can't navigate mid-fetch).
	const [isStale, setIsStale] = useState(false);

	useEffect(() => {
		let active = true;

		const fetchDetail = async () => {
			try {
				const config = getWordPressConfig();
				const response = await get(
					`${config.endpoints.interventions}/${interventionId}`
				);
				if (!active) return;

				const data = response.data || null;
				const status = data?.attributes?.status;
				// Already acted on (acknowledged/dismissed/resolved): there's
				// nothing to do here, so flag it and let the effect below slip
				// back to the list. Stay in the loading state until we navigate.
				if (status && status !== 'pending') {
					setIsStale(true);
					return;
				}

				setIntervention(data);
				setIsLoading(false);
			} catch (err) {
				logError(err, {
					action: 'fetch_intervention',
					component: 'InterventionDetailPage',
				});
				if (active) {
					setError(err);
					setIsLoading(false);
				}
			}
		};

		fetchDetail();
		return () => {
			active = false;
		};
	}, [interventionId]);

	// Leave silently once we know the intervention is no longer actionable.
	useEffect(() => {
		if (isStale) onBack?.();
	}, [isStale, onBack]);

	const transitionClass =
		transition === 'action-enter'
			? 'animate-slide-in-from-right'
			: transition === 'action-exit'
				? 'animate-slide-out-to-right'
				: '';

	// Dispatch to the per-handler detail component (by tag + variant). Lowercase
	// + createElement keeps the React Compiler from treating a registry lookup as
	// a component "created" during render.
	const attributes = intervention?.attributes || {};
	const detailComponent = resolveDetailComponent(
		attributes.tag,
		attributes.metadata?.variant
	);

	return (
		<main className={`flex-1 pt-8 pb-24 ${transitionClass}`}>
			<div className="max-w-3xl mx-auto px-8">
				{!isResolved && (
					<button
						type="button"
						onClick={onBack}
						className="inline-flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors cursor-pointer mb-6"
					>
						<ArrowLeft className="w-4 h-4" />
						Back
					</button>
				)}

				{isLoading && (
					<p className="paragraph-regular text-muted-foreground">
						Loading…
					</p>
				)}
				{error && (
					<p className="paragraph-regular text-destructive">
						Couldn't load this right now.
					</p>
				)}
				{!isLoading &&
					!error &&
					(detailComponent ? (
						<>
							<InterventionBadges intervention={attributes} />
							{createElement(detailComponent, {
								intervention: attributes,
								interventionId,
								onBack,
								onResolved: () => setIsResolved(true),
							})}
						</>
					) : (
						<p className="paragraph-regular text-foreground">
							Intervention ID:{' '}
							{attributes.id ?? interventionId}
						</p>
					))}
			</div>
		</main>
	);
};

export default InterventionDetailPage;
