import { useEffect, useLayoutEffect, useState, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { motion } from 'motion/react';
import { X } from 'lucide-react';
import {
	SiteReportHeader,
	SiteReportBody,
} from '@/features/timeline/SiteReportContent';

// The plugin's visible area sits below the sticky header and to the right of
// the WP admin sidebar. Using the sticky header's left/bottom gives us both
// offsets in one read.
const measureBounds = () => {
	const el = document.querySelector('[data-flavio-sticky]');
	if (!el) return { top: 0, left: 0 };
	const r = el.getBoundingClientRect();
	return { top: r.bottom, left: r.left };
};

/**
 * SiteReportFullscreen
 *
 * Full-page takeover of the plugin's visible area. The outer fixed wrapper is
 * positioned below the sticky header / next to the WP admin sidebar; the inner
 * panel carries a `layoutId` that matches the source card in the timeline. The
 * shared-layout transition (motion) morphs position + size + border-radius
 * between source and modal on open, and back on close, with the inner content
 * cross-fading. Replaces the prior hand-rolled FLIP, which couldn't reliably
 * land the first paint at the source state.
 *
 * Must be rendered inside an <AnimatePresence> so the exit transition runs
 * before unmount.
 */
const SiteReportFullscreen = ({
	report,
	reportId,
	onClose,
	onOpenIntervention,
}) => {
	const [bounds, setBounds] = useState(() => measureBounds());

	// Body scroll lock for the modal's lifetime.
	useEffect(() => {
		const prev = document.body.style.overflow;
		document.body.style.overflow = 'hidden';
		return () => {
			document.body.style.overflow = prev;
		};
	}, []);

	// Keep the panel aligned with the plugin's visible area as the viewport
	// resizes (the TrialBanner can wrap, etc.).
	useLayoutEffect(() => {
		const update = () => setBounds(measureBounds());
		update();
		window.addEventListener('resize', update);
		return () => window.removeEventListener('resize', update);
	}, []);

	const handleClose = useCallback(() => {
		onClose();
	}, [onClose]);

	useEffect(() => {
		const onKey = (e) => {
			if (e.key === 'Escape') handleClose();
		};
		window.addEventListener('keydown', onKey);
		return () => window.removeEventListener('keydown', onKey);
	}, [handleClose]);

	return createPortal(
		<div
			className="fixed bottom-0 right-0 z-40"
			style={{ top: bounds.top, left: bounds.left }}
			role="dialog"
			aria-modal="true"
			aria-label="Monthly report"
		>
			<motion.div
				layoutId={`site-report-${reportId}`}
				transition={{ duration: 0.4, ease: [0.22, 1, 0.36, 1] }}
				className="relative h-full w-full overflow-y-auto bg-white"
			>
				<div className="max-w-5xl mx-auto px-6 sm:px-10 py-12 flex flex-col gap-12">
					<SiteReportHeader
						report={report}
						headerAction={
							<button
								type="button"
								onClick={handleClose}
								aria-label="Close report"
								className="inline-flex items-center justify-center w-9 h-9 rounded-md border border-border bg-white text-foreground hover:bg-neutral-50 transition-colors cursor-pointer"
							>
								<X className="w-4 h-4" />
							</button>
						}
					/>
					<SiteReportBody
						report={report}
						onOpenIntervention={onOpenIntervention}
					/>
				</div>
			</motion.div>
		</div>,
		document.body
	);
};

export default SiteReportFullscreen;
